diff --git a/itrialspace/.dockerignore b/itrialspace/.dockerignore deleted file mode 100644 index 1462a9301dbe2de81242a9581c7a9fc08d61b83e..0000000000000000000000000000000000000000 --- a/itrialspace/.dockerignore +++ /dev/null @@ -1,39 +0,0 @@ -.git -.github -**/__pycache__ -*.py[cod] -*.egg-info -.pytest_cache -.ruff_cache -.ipynb_checkpoints - -# Never copy heavy/host-specific artifacts into the image -models/ -weights/ -logs/ -*.log -*.out -*.err -*_artifacts/ -outputs/ -generated_cts/ -inserted_masks/ -paper_analysis/ -*.pt -*.pth -*.ckpt -*.nii -*.nii.gz -*.parquet - -# Local config & secrets -.env -configs/datasets.yaml -configs/paths.yaml -configs/integration.yaml -configs/mask_inserter.yaml -configs/eval.yaml - -docs/_build/ -.venv/ -venv/ diff --git a/itrialspace/.env b/itrialspace/.env deleted file mode 100644 index b04a913be744654ee22646d0b26ca6aa361314d2..0000000000000000000000000000000000000000 --- a/itrialspace/.env +++ /dev/null @@ -1,32 +0,0 @@ -# iTrialSpace environment — this machine (Duke DRCC). Gitignored; edit freely. -# Read automatically by infra/slurm/env.sh and itrialspace.config.settings. - -# ── Data root (inputs: raw_ct/ masks/ profiles/ meta/) ────────────────────── -ITRIALSPACE_DATA_DIR=/path/iTrialSpace - -# ── Output root (generated: manifests/ inserted_masks/ generated_cts/ ...) ── -# Defaults to ITRIALSPACE_DATA_DIR. Uncomment to send all outputs elsewhere: -ITRIALSPACE_OUTPUT_DIR=/path/outputs_iTrialSpace - -# ── NoduleMap build artifacts (embeddings, edges, metadata) ───────────────── -# Default would be $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts; set explicitly here: -NODULEMAP_ARTIFACTS=/path/nodulemap_artifacts - -# ── Conda env used by SLURM scripts ───────────────────────────────────────── -ITRIALSPACE_CONDA_ENV=itrialspace - -# ── Service ports ──────────────────────────────────────────────────────────── -NODULEMAP_PORT=8422 -RETRIEVER_API_PORT=8421 -RETRIEVER_UI_PORT=8501 - -# ── SLURM partitions (Duke DRCC) ──────────────────────────────────────────── -SLURM_PARTITION_GPU=vram48 -SLURM_PARTITION_CPU=defq - -# ── NodMAISI synthesis model weights (Step 3 of the pipeline) ─────────────── -NODMAISI_MODELS_DIR=/path/nodmaisi_synth/models - -# ── Optional CADe/CADx external dependencies (see docs) ───────────────────── -# EVAL_WEIGHTS_DIR=/path/to/weights -# EVAL_CONFIGS_DIR=/path/to/configs diff --git a/itrialspace/.env.example b/itrialspace/.env.example deleted file mode 100644 index 0193686e6824570de1e6ad7f296dfc3f0e45c402..0000000000000000000000000000000000000000 --- a/itrialspace/.env.example +++ /dev/null @@ -1,54 +0,0 @@ -# iTrialSpace environment configuration — copy to `.env` and edit for your machine. -# These variables drive ALL path resolution; nothing is hardcoded in code or configs. -# -# cp .env.example .env -# -# `itrialspace.config.settings` reads these (falling back to the defaults shown). - -# ── Data root ──────────────────────────────────────────────────────────────── -# Single base directory holding the unified data layout: -# $ITRIALSPACE_DATA_DIR/{raw_ct,masks,profiles,meta,manifests,...} -# Default: ~/.itrialspace/data -ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace/data - -# Repo root (auto-detected from the installed package if unset). -# ITRIALSPACE_ROOT=/home/you/itrialspace - -# Directory for generated outputs (manifests, inserted masks, synthetic CTs, reports). -# Default: $ITRIALSPACE_DATA_DIR -# ITRIALSPACE_OUTPUT_DIR=/path/to/iTrialSpace/outputs - -# ── Build artifacts ────────────────────────────────────────────────────────── -# Where NoduleMap build artifacts (embeddings, edge graphs, metadata) are written — -# and read back from when serving. Set this to point the server at pre-built artifacts, -# or to choose where `its-nodulemap build/edges` (and rebuild_nodulemap.sub) save them. -# Default: $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts -# NODULEMAP_ARTIFACTS=/path/to/iTrialSpace/outputs/nodulemap_artifacts -# NODULEMAP_EXPORTS=/path/to/iTrialSpace/outputs/nodulemap_exports # neighbour/donor exports - -# ── Model weights (NOT bundled — see docs/installation.md) ────────────────── -# NodMAISI synthesis model weights (autoencoder.pt, diffusion_unet.pt, controlnet *.pt) -# NODMAISI_MODELS_DIR=/path/to/nodmaisi/models - -# ── Optional CADe/CADx external dependencies (see docs/evaluation_external_dependencies.md) ── -# EVAL_WEIGHTS_DIR=/path/to/cade_cadx/weights -# EVAL_CONFIGS_DIR=/path/to/cade_cadx/configs -# EVAL_SCRIPTS_DIR=/path/to/cade_cadx/scripts # e.g. generate_transforms.py -# PINS_ROOT=/path/to/PiNS # world-coordinate patch extractor -# FPRDL_ROOT=/path/to/fprDL # false-positive-reduction inference -# NOMAISI_ROOT=/path/to/NoMAISI # NodMAISI core (synthesis) -# MAISI_CORE_ROOT=/path/to/MAISI_Core # FID / metrics utilities -# LUNGRADS_ROOT=/path/to/LungRADS_Modeling # CADx classifier (cadx_meta) -# ANOD_ROOT=/path/to/ANod # umbrella external workspace (legacy) - -# ── Service ports ──────────────────────────────────────────────────────────── -NODULEMAP_PORT=8422 -RETRIEVER_API_PORT=8421 -RETRIEVER_UI_PORT=8501 - -# ── HPC / SLURM (only used by infra/slurm/*) ──────────────────────────────── -ITRIALSPACE_CONDA_ENV=itrialspace -SLURM_PARTITION_GPU=vram48 -SLURM_PARTITION_CPU=defq -# SLURM_ACCOUNT= -# CONDA_PROFILE=/cm/shared/apps/miniconda/etc/profile.d/conda.sh diff --git a/itrialspace/.pytest_cache/.gitignore b/itrialspace/.pytest_cache/.gitignore deleted file mode 100644 index bc1a1f6167d09c909aad37280b760bb715d0f1da..0000000000000000000000000000000000000000 --- a/itrialspace/.pytest_cache/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Created by pytest automatically. -* diff --git a/itrialspace/.pytest_cache/CACHEDIR.TAG b/itrialspace/.pytest_cache/CACHEDIR.TAG deleted file mode 100644 index fce15ad7eaa74e5682b644c84efb75334c112f95..0000000000000000000000000000000000000000 --- a/itrialspace/.pytest_cache/CACHEDIR.TAG +++ /dev/null @@ -1,4 +0,0 @@ -Signature: 8a477f597d28d172789f06886806bc55 -# This file is a cache directory tag created by pytest. -# For information about cache directory tags, see: -# https://bford.info/cachedir/spec.html diff --git a/itrialspace/.pytest_cache/README.md b/itrialspace/.pytest_cache/README.md deleted file mode 100644 index b89018ced91c0a8af7f3f23ce8901870da89f3a0..0000000000000000000000000000000000000000 --- a/itrialspace/.pytest_cache/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# pytest cache directory # - -This directory contains data from the pytest's cache plugin, -which provides the `--lf` and `--ff` options, as well as the `cache` fixture. - -**Do not** commit this to version control. - -See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information. diff --git a/itrialspace/.pytest_cache/v/cache/nodeids b/itrialspace/.pytest_cache/v/cache/nodeids deleted file mode 100644 index 5ec860982de667e5b70248133fd981e649afdd01..0000000000000000000000000000000000000000 --- a/itrialspace/.pytest_cache/v/cache/nodeids +++ /dev/null @@ -1,56 +0,0 @@ -[ - "tests/nodulemap/test_models.py::TestAlignment::test_all_models_aligned", - "tests/nodulemap/test_models.py::TestArtifacts::test_embedding_shape[PCA_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embedding_shape[PCA_32]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embedding_shape[TSNE_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embedding_shape[UMAP_16]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embedding_shape[UMAP_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embedding_shape[UMAP_32]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embeddings_exist[PCA_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embeddings_exist[PCA_32]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embeddings_exist[TSNE_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embeddings_exist[UMAP_16]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embeddings_exist[UMAP_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_embeddings_exist[UMAP_32]", - "tests/nodulemap/test_models.py::TestArtifacts::test_metadata_exist[PCA_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_metadata_exist[PCA_32]", - "tests/nodulemap/test_models.py::TestArtifacts::test_metadata_exist[TSNE_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_metadata_exist[UMAP_16]", - "tests/nodulemap/test_models.py::TestArtifacts::test_metadata_exist[UMAP_2D]", - "tests/nodulemap/test_models.py::TestArtifacts::test_metadata_exist[UMAP_32]", - "tests/nodulemap/test_models.py::TestCanonicalization::test_alias_loads_embeddings", - "tests/nodulemap/test_models.py::TestCanonicalization::test_canon[PCA_32D-PCA_32]", - "tests/nodulemap/test_models.py::TestCanonicalization::test_canon[UMAP_32-UMAP_32]", - "tests/nodulemap/test_models.py::TestCanonicalization::test_canon[pca_32d-PCA_32]", - "tests/nodulemap/test_models.py::TestCanonicalization::test_canon[tSNE_2D-TSNE_2D]", - "tests/nodulemap/test_models.py::TestCanonicalization::test_canon[tsne_2d-TSNE_2D]", - "tests/nodulemap/test_models.py::TestCanonicalization::test_canon[umap_16d-UMAP_16]", - "tests/nodulemap/test_models.py::TestLayoutModels::test_positions_shape[PCA_2D]", - "tests/nodulemap/test_models.py::TestLayoutModels::test_positions_shape[TSNE_2D]", - "tests/nodulemap/test_models.py::TestLayoutModels::test_positions_shape[UMAP_2D]", - "tests/nodulemap/test_models.py::TestLayoutModels::test_tsne_2d_finite", - "tests/nodulemap/test_models.py::TestLayoutModels::test_tsne_2d_spread", - "tests/nodulemap/test_models.py::TestModelClassification::test_all_expected_layout", - "tests/nodulemap/test_models.py::TestModelClassification::test_layout_models_are_2d", - "tests/nodulemap/test_models.py::TestModelClassification::test_search_includes_all", - "tests/nodulemap/test_models.py::TestSearchModels::test_high_d_embedding_dims[PCA_32]", - "tests/nodulemap/test_models.py::TestSearchModels::test_high_d_embedding_dims[UMAP_16]", - "tests/nodulemap/test_models.py::TestSearchModels::test_high_d_embedding_dims[UMAP_32]", - "tests/nodulemap/test_models.py::TestSearchModels::test_neighbor_query[PCA_2D]", - "tests/nodulemap/test_models.py::TestSearchModels::test_neighbor_query[PCA_32]", - "tests/nodulemap/test_models.py::TestSearchModels::test_neighbor_query[TSNE_2D]", - "tests/nodulemap/test_models.py::TestSearchModels::test_neighbor_query[UMAP_16]", - "tests/nodulemap/test_models.py::TestSearchModels::test_neighbor_query[UMAP_2D]", - "tests/nodulemap/test_models.py::TestSearchModels::test_neighbor_query[UMAP_32]", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_embeddings_match_metadata", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_info_yaml_n_samples", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_metadata_expected_datasets", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_metadata_files_exist", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_metadata_node_count", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_no_nlst3d_in_edges", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_no_nlst3d_in_metadata", - "tests/nodulemap/test_nlst3d_purge.py::TestArtifactPurge::test_no_nlst3d_in_node_ids", - "tests/nodulemap/test_nlst3d_purge.py::TestConfigPurge::test_datasets_yaml_expected_datasets", - "tests/nodulemap/test_nlst3d_purge.py::TestConfigPurge::test_datasets_yaml_no_nlst3d", - "tests/nodulemap/test_nlst3d_purge.py::TestConfigPurge::test_demographics_map_no_nlst3d" -] \ No newline at end of file diff --git a/itrialspace/.ruff_cache/.gitignore b/itrialspace/.ruff_cache/.gitignore deleted file mode 100644 index b100327770759f0efb7859fe78aca4801d69ed61..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Automatically created by ruff. -* diff --git a/itrialspace/.ruff_cache/0.3.1/10268710207549842396 b/itrialspace/.ruff_cache/0.3.1/10268710207549842396 deleted file mode 100644 index 7ac137e6cbe9a549606293e33af5039f1d5aaeac..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/10268710207549842396 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/10402261062355903691 b/itrialspace/.ruff_cache/0.3.1/10402261062355903691 deleted file mode 100644 index a8710dc1685529ed135dcbb11b70f517cd52e815..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/10402261062355903691 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/11438927756675949518 b/itrialspace/.ruff_cache/0.3.1/11438927756675949518 deleted file mode 100644 index b0d59d3c087d51448d1ad8e824bb57a60f661f28..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/11438927756675949518 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/11541497334420936011 b/itrialspace/.ruff_cache/0.3.1/11541497334420936011 deleted file mode 100644 index 6996bc41bdbc87c4eac3d3b07391db563f13ac99..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/11541497334420936011 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/11661378374734224415 b/itrialspace/.ruff_cache/0.3.1/11661378374734224415 deleted file mode 100644 index 2daf7512ca87095b63e7cef327f2b085001138ae..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/11661378374734224415 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/11687147208567312006 b/itrialspace/.ruff_cache/0.3.1/11687147208567312006 deleted file mode 100644 index 3413682c009b27a2b367a13de51e424dbae80066..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/11687147208567312006 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/13270962227840114613 b/itrialspace/.ruff_cache/0.3.1/13270962227840114613 deleted file mode 100644 index ff7993515dff551752bfcd8a3388d73a7ea87d90..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/0.3.1/13270962227840114613 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6bba94a5fa726b12eeebe409d298782bd67b0bffd01328b1412d3421f94152e8 -size 285662 diff --git a/itrialspace/.ruff_cache/0.3.1/1332919568706824206 b/itrialspace/.ruff_cache/0.3.1/1332919568706824206 deleted file mode 100644 index d66691848e76461f00e2dae1a73c0e01b5d6a97f..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/1332919568706824206 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/13717733759444567451 b/itrialspace/.ruff_cache/0.3.1/13717733759444567451 deleted file mode 100644 index 0911cd73db98c98ae199d7d047b6c6f95a6d7854..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/13717733759444567451 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/14304968425227739574 b/itrialspace/.ruff_cache/0.3.1/14304968425227739574 deleted file mode 100644 index 770b8e5faa0848927c13147f21c44f0ecea5939b..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/14304968425227739574 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/15042522414794972590 b/itrialspace/.ruff_cache/0.3.1/15042522414794972590 deleted file mode 100644 index 0296ba0c8148fb4778c58206f67d259c67366903..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/15042522414794972590 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/15336951827600494100 b/itrialspace/.ruff_cache/0.3.1/15336951827600494100 deleted file mode 100644 index 9c58313f2c0b8235389338299f8959b3f699eb72..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/15336951827600494100 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/15704746501454451485 b/itrialspace/.ruff_cache/0.3.1/15704746501454451485 deleted file mode 100644 index 32825f284a51f3a001646c044e63654372bc1b47..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/15704746501454451485 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/15889485565577009416 b/itrialspace/.ruff_cache/0.3.1/15889485565577009416 deleted file mode 100644 index 9b5cb07feae1aa51a1b94a113abe46b419d4776b..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/15889485565577009416 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/1590084174280165373 b/itrialspace/.ruff_cache/0.3.1/1590084174280165373 deleted file mode 100644 index 178da8ebecbebd55a0c0eaf85e10e20a47e22784..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/1590084174280165373 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/15940156036810644891 b/itrialspace/.ruff_cache/0.3.1/15940156036810644891 deleted file mode 100644 index dda8969120c787420f7121a1b91cb23f807bcb12..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/0.3.1/15940156036810644891 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:01ff303b068975e95b67a0f646a846cdc6c0da0a73ebb7643a8a42e1c573e1b5 -size 438540 diff --git a/itrialspace/.ruff_cache/0.3.1/16228296161243405102 b/itrialspace/.ruff_cache/0.3.1/16228296161243405102 deleted file mode 100644 index 5e38112376b6f650437cefcdc36471f1cef2d755..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/16228296161243405102 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/16698537861176403021 b/itrialspace/.ruff_cache/0.3.1/16698537861176403021 deleted file mode 100644 index 0c0eda154a8731e6e9295965896feba90567e796..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/0.3.1/16698537861176403021 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:235b4a9a720411cd913d148fa514ebe138b90fcfce6a4abae185ab211f81b214 -size 1448726 diff --git a/itrialspace/.ruff_cache/0.3.1/1727747652348082283 b/itrialspace/.ruff_cache/0.3.1/1727747652348082283 deleted file mode 100644 index b142bee6f15d5127b1f55416f765a99c33abc84f..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/1727747652348082283 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2072497558732444295 b/itrialspace/.ruff_cache/0.3.1/2072497558732444295 deleted file mode 100644 index a7fbb7ca8e1a109f5da19ec18a1aa6b84abef6d5..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2072497558732444295 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2113321950824001541 b/itrialspace/.ruff_cache/0.3.1/2113321950824001541 deleted file mode 100644 index 87484c00f8f7616dae41f37e06a6462c0d0f67da..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2113321950824001541 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2236754750473151329 b/itrialspace/.ruff_cache/0.3.1/2236754750473151329 deleted file mode 100644 index bd86dde73e0c7273194a0bc8c3c66afebfb77f04..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2236754750473151329 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2392906786021029028 b/itrialspace/.ruff_cache/0.3.1/2392906786021029028 deleted file mode 100644 index f1ac92521d9f1365bf81b600527273b9eea593ae..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2392906786021029028 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2546986302533298011 b/itrialspace/.ruff_cache/0.3.1/2546986302533298011 deleted file mode 100644 index 0f24e89440f5f7650e23979998dacfb197b84244..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2546986302533298011 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2693543438262934321 b/itrialspace/.ruff_cache/0.3.1/2693543438262934321 deleted file mode 100644 index 852e622c7d8c36f86097aaf77a8aa9d426b2a81a..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/0.3.1/2693543438262934321 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:33b642cf93fd178f4eba80faa6d3e721009d753a2f5a3f6e87991d327a18ff40 -size 165553 diff --git a/itrialspace/.ruff_cache/0.3.1/2898795975690374683 b/itrialspace/.ruff_cache/0.3.1/2898795975690374683 deleted file mode 100644 index 4bcca6da2f778222ee35dbaa913400fcd2ae44d5..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2898795975690374683 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/2923937702929825373 b/itrialspace/.ruff_cache/0.3.1/2923937702929825373 deleted file mode 100644 index 133bb548395dbe3cf4c3c079f0de75256187e719..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/2923937702929825373 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/3093689026378722260 b/itrialspace/.ruff_cache/0.3.1/3093689026378722260 deleted file mode 100644 index b67c3db97ccd21baa99642678218d1edacb80325..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/3093689026378722260 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/3415075985824578642 b/itrialspace/.ruff_cache/0.3.1/3415075985824578642 deleted file mode 100644 index 1282c43dd20c065b9af32196570b7d82a7904a0d..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/3415075985824578642 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/4648463968754632694 b/itrialspace/.ruff_cache/0.3.1/4648463968754632694 deleted file mode 100644 index 67d4f1884b454e5f6bf71fb4b5cf77f3e1c90278..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/4648463968754632694 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/4660698010403683286 b/itrialspace/.ruff_cache/0.3.1/4660698010403683286 deleted file mode 100644 index 37c985bee7024dcc295a541306191b47895e4653..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/4660698010403683286 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/4812025117260835000 b/itrialspace/.ruff_cache/0.3.1/4812025117260835000 deleted file mode 100644 index 44dd601457ff412bb73f29eacf5ef4083e12efb6..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/4812025117260835000 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/523922309083657476 b/itrialspace/.ruff_cache/0.3.1/523922309083657476 deleted file mode 100644 index a44681d019707122047481ef4ecb5646978bb75d..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/0.3.1/523922309083657476 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c11fe04e34e329d064cd35d836625721225a7fdcbd1969807caac84293d4bca6 -size 101520 diff --git a/itrialspace/.ruff_cache/0.3.1/5352381337535761743 b/itrialspace/.ruff_cache/0.3.1/5352381337535761743 deleted file mode 100644 index 2fd3515429518cfb7b8dfa4b91108b5e57348ba3..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/5352381337535761743 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/54354719732180887 b/itrialspace/.ruff_cache/0.3.1/54354719732180887 deleted file mode 100644 index 32b93cd4e2067d905d3e4294a7347dc1849f1788..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/54354719732180887 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/5508166548609114175 b/itrialspace/.ruff_cache/0.3.1/5508166548609114175 deleted file mode 100644 index 572bc56f5391453b799a67d08b7f8a09710363ed..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/5508166548609114175 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/6658706702627705797 b/itrialspace/.ruff_cache/0.3.1/6658706702627705797 deleted file mode 100644 index 480ffd5453c387cf972102ef81b6293db8e8d9c7..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/6658706702627705797 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/6960321295612271921 b/itrialspace/.ruff_cache/0.3.1/6960321295612271921 deleted file mode 100644 index 68f00aa8afa53575194b089d676957ab4e12fe79..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/0.3.1/6960321295612271921 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7ed6f90264c64d5f874dd541e772e4277380820d9c41838c5094038efabf4b2f -size 664613 diff --git a/itrialspace/.ruff_cache/0.3.1/7183184745613353585 b/itrialspace/.ruff_cache/0.3.1/7183184745613353585 deleted file mode 100644 index 63b39937897cfe50bebacf577d8c72d5fbd2f865..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/7183184745613353585 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/7318657020121329762 b/itrialspace/.ruff_cache/0.3.1/7318657020121329762 deleted file mode 100644 index 6a182ca54ee9f9b86ebfcd428df48a9906138f3a..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/7318657020121329762 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/8529725525395523834 b/itrialspace/.ruff_cache/0.3.1/8529725525395523834 deleted file mode 100644 index 56a8a38f151a2c0f17535a6c00affbd98c016f2c..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/8529725525395523834 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/8697535389249467727 b/itrialspace/.ruff_cache/0.3.1/8697535389249467727 deleted file mode 100644 index 5b2c5fa9ab8210db3e0bcfd8e604dd8c7ef97690..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/8697535389249467727 and /dev/null differ diff --git a/itrialspace/.ruff_cache/0.3.1/9250766668787263456 b/itrialspace/.ruff_cache/0.3.1/9250766668787263456 deleted file mode 100644 index 2e6121b2cda27c2a8ee126222697b1f1bbd7112b..0000000000000000000000000000000000000000 Binary files a/itrialspace/.ruff_cache/0.3.1/9250766668787263456 and /dev/null differ diff --git a/itrialspace/.ruff_cache/CACHEDIR.TAG b/itrialspace/.ruff_cache/CACHEDIR.TAG deleted file mode 100644 index bc1ecb967a482524e7736038de0df6e08f9ee452..0000000000000000000000000000000000000000 --- a/itrialspace/.ruff_cache/CACHEDIR.TAG +++ /dev/null @@ -1 +0,0 @@ -Signature: 8a477f597d28d172789f06886806bc55 \ No newline at end of file diff --git a/itrialspace/CITATION.cff b/itrialspace/CITATION.cff deleted file mode 100644 index a5b6781157bff56d1b5965cbc53b2920a025f264..0000000000000000000000000000000000000000 --- a/itrialspace/CITATION.cff +++ /dev/null @@ -1,25 +0,0 @@ -cff-version: 1.2.0 -title: "iTrialSpace — Synthetic Imaging Clinical Trial Engine" -message: "If you use this software, please cite it as below." -type: software -authors: - - family-names: "TODO" - given-names: "TODO" - # orcid: "https://orcid.org/0000-0000-0000-0000" -repository-code: "https://github.com/TODO/itrialspace" -abstract: >- - iTrialSpace is a framework for constructing virtual lung cancer screening - clinical trials. It harmonizes 13,140 nodule profiles from 7 public datasets, - generates cohort manifests across 13 trial modes, inserts donor nodule masks - into host CT anatomy, synthesizes CT volumes with a ControlNet-conditioned - rectified-flow diffusion model (NodMAISI), and evaluates CADe/CADx detectors - and vision-language models under controlled conditions. -keywords: - - medical imaging - - lung CT - - synthetic data - - virtual clinical trial - - vision-language models -version: "0.1.0" -# license: TODO # set once the LICENSE is finalized -# date-released: "2026-01-01" diff --git a/itrialspace/configs/datasets.example.yaml b/itrialspace/configs/datasets.example.yaml deleted file mode 100644 index 65993e4fa2f62e34235a19f4235c13bb68d05437..0000000000000000000000000000000000000000 --- a/itrialspace/configs/datasets.example.yaml +++ /dev/null @@ -1,35 +0,0 @@ -# iTrialSpace Dataset Registry — maps dataset name → nodule-profile CSV path. -# -# Copy to `configs/datasets.yaml` and adjust if your layout differs. Paths use the -# ${ITRIALSPACE_DATA_DIR} placeholder, which is expanded by itrialspace.config.settings -# (default: ~/.itrialspace/data). You usually only need to set ITRIALSPACE_DATA_DIR in .env. - -datasets: - - DLCS24: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/DLCS24_nodule_profiles.csv - notes: "Binary label. Lung-RADS scores, smoking, age/sex. 2,487 nodules." - - LUNA25: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA25_nodule_profiles.csv - notes: "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening." - - LUNA16: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA16_nodule_profiles.csv - notes: "No malignancy label. Use for reinsertion/anatomy analysis only." - - LUNGx: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNGx_nodule_profiles.csv - notes: "Benchmark challenge. 49.4% malignant. Has CADe detection scores." - - LNDbv4: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LNDbv4_nodule_profiles.csv - notes: "Malignancy is continuous float (radiologist avg 1-5). Threshold 3.0 used." - - NSCLCR: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/NSCLCR_nodule_profiles.csv - notes: "All malignant (100%). Large tumours (median 52mm). Has staging/survival." - - IMDCT: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/IMDCT_nodule_profiles.csv - notes: "Label is string benign/cancer. Has nodule type, PET, spiculation." diff --git a/itrialspace/configs/eval.example.yaml b/itrialspace/configs/eval.example.yaml deleted file mode 100644 index 2c4ae19e3f065d13a8cf37b773fec7dfc0a33332..0000000000000000000000000000000000000000 --- a/itrialspace/configs/eval.example.yaml +++ /dev/null @@ -1,38 +0,0 @@ -# Optional CADe/CADx evaluation configuration. -# -# These pipelines require EXTERNAL models and repositories that are NOT bundled with -# iTrialSpace. See docs/evaluation_external_dependencies.md before using. Copy to -# `configs/eval.yaml` and fill in the paths for your machine. -# -# All values may use ${VAR} placeholders resolved from your environment / .env. - -# Root of the unified data directory (synthetic CTs to evaluate live here). -data_dir: ${ITRIALSPACE_DATA_DIR} - -# ── External repositories (clone separately) ──────────────────────────────── -external: - pins_root: ${PINS_ROOT} # PiNS — world-coordinate patch extractor - fprdl_root: ${FPRDL_ROOT} # fprDL — false-positive-reduction inference - nomaisi_root: ${NOMAISI_ROOT} # NoMAISI core (for FID / synthesis utilities) - -# ── External model weights & training configs ─────────────────────────────── -weights_dir: ${EVAL_WEIGHTS_DIR} -configs_dir: ${EVAL_CONFIGS_DIR} - -# CADe detection models -cade: - nodet_weights: ${EVAL_WEIGHTS_DIR}/model_DukeLungRADs_cvit_luna16_luna25_BaseModel_epoch300_patch192x192y80z_fold1.pt - nodet_config: ${EVAL_CONFIGS_DIR}/tr_config_NODet.json - banodet_weights: ${EVAL_WEIGHTS_DIR}/model_DukeLungRADs_cvit_luna16_luna25_noduleonly_BaseModel_epoch300_patch192x192y80z_fold1.pt - banodet_config: ${EVAL_CONFIGS_DIR}/tr_config_BaNODet.json - -# CADx classification + false-positive-reduction models -cadx: - dlcs24_weights: ${EVAL_WEIGHTS_DIR}/DLCS24CADx_Fold1_resnet50SWS.pt - dlcs24_config: ${EVAL_CONFIGS_DIR}/tr_config_DLCS24CADxr50SWS.json - luna25_weights: ${EVAL_WEIGHTS_DIR}/LUNA25CADx_prct100_resnet50.pt - luna25_config: ${EVAL_CONFIGS_DIR}/tr_config_LUNA25CADx_r50.json - fpr_r50ssl_weights: ${EVAL_WEIGHTS_DIR}/Dukeluna1625cvit_FPR_r50SSL_BaseModel_multigpu_fold1_resnet50_SSL.pt - fpr_r50ssl_config: ${EVAL_CONFIGS_DIR}/tr_config_fprDL_r50SSL.json - fpr_r50wspp_weights: ${EVAL_WEIGHTS_DIR}/Dukeluna1625cvit_FPR_r50WSPP_BaseModel_multigpu_fold1_resnet50.pt - fpr_r50wspp_config: ${EVAL_CONFIGS_DIR}/tr_config_fprDL_r50WSPP.json diff --git a/itrialspace/configs/features.yaml b/itrialspace/configs/features.yaml deleted file mode 100644 index 48adfc5a1faed648be9a4374f5fcfdd15455b0e8..0000000000000000000000000000000000000000 --- a/itrialspace/configs/features.yaml +++ /dev/null @@ -1,111 +0,0 @@ -# Feature-set definitions for NoduleMap embeddings. -# Each feature set defines the columns used, their types, and preprocessing. - -feature_sets: - - # ── reinsertion_core ────────────────────────────────────────────────────── - # Safe default: uses only reinsertion_* columns (100% complete, no NaNs). - reinsertion_core: - description: "Reinsertion-only features — no NaNs, 12 columns" - numeric: - - reinsertion_lobe_cc_pct - - reinsertion_lobe_ml_pct - - reinsertion_lobe_ap_pct - - reinsertion_lung_cc_pct - - reinsertion_lung_ml_pct - - reinsertion_lung_ap_pct - - reinsertion_pleural_dist_mm - - reinsertion_airway_dist_mm - - reinsertion_nodule_diam_mm - categorical: - - reinsertion_lobe - - reinsertion_lung_side - - reinsertion_lung_zone - scaler: standard # standard | robust - imputer: none # none | median | mean - - # ── core_53 ─────────────────────────────────────────────────────────────── - # Full 53-column profile: anatomy, distances, inter-nodule, reinsertion. - # May contain NaNs in non-reinsertion columns. - core_53: - description: "All 53 core pipeline features — requires imputation" - numeric: - - nodule_mean_diam_mm - - nodule_vol_mm3 - - cranio_caudal_pct - - mediolateral_pct - - anteroposterior_pct - - lobe_cc_pct - - lobe_ml_pct - - lobe_ap_pct - - dist_to_trachea_mm - - dist_to_aorta_mm - - dist_to_heart_mm - - dist_to_esophagus_mm - - dist_to_pulmonary_vein_mm - - dist_to_superior_vena_cava_mm - - pleural_distance_mm - - airway_distance_mm - - n_nodules_in_patient - - nearest_nodule_dist_mm - - nearest_dx_mm - - nearest_dy_mm - - nearest_dz_mm - - reinsertion_lobe_cc_pct - - reinsertion_lobe_ml_pct - - reinsertion_lobe_ap_pct - - reinsertion_lung_cc_pct - - reinsertion_lung_ml_pct - - reinsertion_lung_ap_pct - - reinsertion_pleural_dist_mm - - reinsertion_airway_dist_mm - - reinsertion_nodule_diam_mm - categorical: - - lobe_name - - lung_side - - lung_zone - - central_peripheral - - reinsertion_lobe - - reinsertion_lung_side - - reinsertion_lung_zone - scaler: robust - imputer: median - -# ── Embedding model presets ──────────────────────────────────────────────── -models: - - PCA_2D: - algorithm: pca - n_components: 2 - - PCA_32: - algorithm: pca - n_components: 32 - - UMAP_2D: - algorithm: umap - n_components: 2 - n_neighbors: 30 - min_dist: 0.3 - metric: euclidean - - UMAP_16: - algorithm: umap - n_components: 16 - n_neighbors: 30 - min_dist: 0.1 - metric: euclidean - - UMAP_32: - algorithm: umap - n_components: 32 - n_neighbors: 30 - min_dist: 0.1 - metric: euclidean - - TSNE_2D: - algorithm: tsne - n_components: 2 - perplexity: 30 - learning_rate: auto - n_iter: 1000 diff --git a/itrialspace/configs/integration.example.yaml b/itrialspace/configs/integration.example.yaml deleted file mode 100644 index 4613a38f94a484b31b23aa0c1b4cc61d41b1a063..0000000000000000000000000000000000000000 --- a/itrialspace/configs/integration.example.yaml +++ /dev/null @@ -1,76 +0,0 @@ -# ============================================================================ -# iTrialSpace -> NodMAISI Integration Pipeline — Configuration -# ============================================================================ - -# -- Paths to NodMAISI model components ----------------------------------- -# Paths use ${VAR} placeholders expanded by itrialspace.config.settings. -# Model weights are NOT bundled — set NODMAISI_MODELS_DIR to the directory holding -# autoencoder.pt / diffusion_unet.pt / controlnet *.pt (see docs/installation.md). -nodmaisi: - project_dir: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis - model_config: configs/config_maisi3d-rflow.json - controlnet_config: configs/infr_config_NoMAISI_controlnet.json - env_config: configs/infr_env_NoMAISI_DLCSD24_demo.json - # Model checkpoints (absolute via NODMAISI_MODELS_DIR, or relative to project_dir) - autoencoder_path: ${NODMAISI_MODELS_DIR}/autoencoder.pt - diffusion_unet_path: ${NODMAISI_MODELS_DIR}/diffusion_unet.pt - controlnet_path: ${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt - -# -- Inference parameters ------------------------------------------------- -inference: - num_inference_steps: 30 - autoencoder_sliding_window_infer_size: [80, 80, 64] - autoencoder_sliding_window_infer_overlap: 0.25 - noise_factor: 1.0 - modality: 1 # 1 = CT - seed: 42 - device: "cuda:0" - -# -- iTrialSpace mask parameters ------------------------------------------ -itrialspace: - nodule_label_value: 23 # Label value used by iTrialSpace for inserted nodules - # Base directory for resolving relative paths in iTrialSpace manifests/audits - base_dir: ${ITRIALSPACE_DATA_DIR} - # Root of iTrialSpace trial manifests (JSON/CSV with host_ct_path per case) - manifest_root: ${ITRIALSPACE_DATA_DIR}/manifests - -# -- Output structure ----------------------------------------------------- -output: - # Root for generated CTs. {trial_name} is substituted at runtime. - root: ${ITRIALSPACE_OUTPUT_DIR}/generated_cts - # Per-case subdirectory template - case_dir_template: "case_{case_id}" - # Filenames inside each case directory - synthetic_ct_name: synthetic_ct.nii.gz - input_mask_name: input_mask.nii.gz - host_ct_link_name: host_ct.nii.gz - qc_dir_name: qc - audit_name: nodmaisi_audit.json - -# -- QC settings ---------------------------------------------------------- -qc: - enabled: true - # Number of axial slices to render (evenly spaced through the nodule region) - num_slices: 3 - # Window level / width for CT display (HU) - window_center: -600 - window_width: 1500 - # PNG DPI - dpi: 150 - -# -- Geometry constraints (from NodMAISI check_input) --------------------- -geometry: - # Valid XY sizes for NodMAISI (first two dims must be equal) - valid_xy_sizes: [256, 384, 512] - # Valid Z sizes - valid_z_sizes: [128, 256, 384, 512, 640, 768] - # Target spacing for resampling if needed (null = use mask's native spacing) - target_spacing: null - # If true, resample mask to nearest valid size; if false, skip cases that don't fit - auto_resize: true - -# -- Conda / environment (for SLURM scripts) ----------------------------- -environment: - conda_module: "" - conda_env: ${ITRIALSPACE_CONDA_ENV} - monai_data_directory: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis diff --git a/itrialspace/configs/mask_inserter.example.yaml b/itrialspace/configs/mask_inserter.example.yaml deleted file mode 100644 index 2035657fa4cdbd99f3db7c794fd23b2868fcbdaa..0000000000000000000000000000000000000000 --- a/itrialspace/configs/mask_inserter.example.yaml +++ /dev/null @@ -1,113 +0,0 @@ -# iTrialSpace Mask Insertion Engine — defaults -# Override per-site via --config flag or INSERTER_CONFIG env var. - -# ── Lobe label mapping (VISTA3D integer labels) ───────────────────────────── -lobe_labels: - left_lung_upper_lobe: 28 - left_lung_lower_lobe: 29 - right_lung_upper_lobe: 30 - right_lung_middle_lobe: 31 - right_lung_lower_lobe: 32 - -# String ↔ integer aliases accepted in manifest ``insertion_lobe`` column. -# Keys are normalised lowercased names; values map to the canonical key above. -lobe_aliases: - lul: left_lung_upper_lobe - lll: left_lung_lower_lobe - rul: right_lung_upper_lobe - rml: right_lung_middle_lobe - rll: right_lung_lower_lobe - left_upper: left_lung_upper_lobe - left_lower: left_lung_lower_lobe - right_upper: right_lung_upper_lobe - right_middle: right_lung_middle_lobe - right_lower: right_lung_lower_lobe - -# Labels treated as "whole lung" for fallback placement. -lung_labels: [28, 29, 30, 31, 32] - -# ── Nodule output label ───────────────────────────────────────────────────── -# Integer value written into the host output mask for inserted nodule voxels. -# The intermediate binary mask (0/1) is converted to this label before writing. -# Default 23; change without code edits by overriding this value. -nodule_label_value: 23 - -# Future extension: per-nodule-type label mapping (unused for now). -# When populated, keys are nodule type strings and values are integer labels. -# Example: {"malignant": 23, "benign": 24} -nodule_type_to_label: {} - -# ── Placement parameters ──────────────────────────────────────────────────── -placement: - # Maximum search radius (voxels) when snapping an out-of-mask candidate to - # the nearest valid voxel inside the target mask. - max_snap_radius_vox: 25 - - # Minimum distance (mm) from the lung boundary that an insertion centre must - # satisfy. Set to 0 to disable. - min_pleural_dist_mm: 2.0 - - # If True, check for overlap with existing nodules in the combined mask and - # attempt to shift the placement to avoid it. - check_overlap: true - - # Maximum fraction of donor mask voxels allowed to overlap with an existing - # nodule mask before the placement is declared infeasible. - max_overlap_fraction: 0.05 - - # Maximum additional shift (voxels) attempted to resolve overlap collisions. - max_collision_shift_vox: 15 - -# ── Resampling parameters ─────────────────────────────────────────────────── -resample: - # Interpolation for binary masks: "nearest" (default) or "linear" then - # threshold. - interpolation: nearest - - # After resampling, voxels with value >= this threshold are set to 1. - binary_threshold: 0.5 - - # Remove connected components smaller than this (voxels) after resampling. - min_component_size_vox: 3 - - # Fill holes in the binary mask after resampling. - fill_holes: true - -# ── Output naming ─────────────────────────────────────────────────────────── -output: - # Flat directory — all combined masks in one folder, no subdirectories. - use_case_subdirs: false - - # Combined mask template. - # Delimiter convention: '--' separates fields, '-' separates key from value. - # Parsing: dict(f.split('-', 1) for f in stem.split('--')[1:] if '-' in f) - # Available placeholders: {trial_name}, {case_id}, {host_id}, {host_dataset}, {donor_id}. - # case_id is zero-padded to 4 digits. host_id is SHA-256[:8] when >20 chars. - combined_mask_template: "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz" - - # Whether to save individual per-nodule binary masks (in addition to the combined mask). - save_per_nodule_mask: false - - # Per-nodule mask template (only used when save_per_nodule_mask is true). - nodule_mask_template: "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz" - - # Audit log filename. - audit_name: audit.json - - # Compress NIfTI outputs. - compress: true - -# ── Optional CT intensity insertion (experimental, off by default) ────────── -ct_insertion: - enabled: false - blending_mode: poisson # poisson | direct | alpha - boundary_width_mm: 2.0 - -# ── Parallelism ───────────────────────────────────────────────────────────── -parallel: - backend: loky # loky | threading | sequential - n_jobs: 1 - verbose: 10 - -# ── Reproducibility ───────────────────────────────────────────────────────── -seed: 42 diff --git a/itrialspace/configs/paths.example.yaml b/itrialspace/configs/paths.example.yaml deleted file mode 100644 index 2403d5cf4b3aa23e4dc43291f759f0527d87ce28..0000000000000000000000000000000000000000 --- a/itrialspace/configs/paths.example.yaml +++ /dev/null @@ -1,61 +0,0 @@ -# iTrialSpace path layout — unified data directory. -# -# Copy to `configs/paths.yaml` and adjust if your layout differs. ${ITRIALSPACE_DATA_DIR} -# is expanded by itrialspace.config.settings (default: ~/.itrialspace/data). -# -# ${ITRIALSPACE_DATA_DIR}/ -# ├── raw_ct/{DATASET}/ CT scans (resampled NIfTI) -# ├── masks/{DATASET}/ -# │ ├── nodule_seg/ Individual nodule masks -# │ ├── combined_seg/ Combined patient masks -# │ ├── organ_seg/ VISTA3D organ segmentations (raw, deprecated) -# │ └── refined_seg/ Refined organ + body segmentations (used by default) -# ├── profiles/ Nodule profile CSVs -# └── meta/ Original dataset metadata CSVs -# -# ct_path values in profile CSVs are relative to raw_ct/, e.g. -# "DLCS24/DLCS_0001.nii.gz" → ${ITRIALSPACE_DATA_DIR}/raw_ct/DLCS24/DLCS_0001.nii.gz - -# ── Global base directory ────────────────────────────────────────────────── -base_dir: ${ITRIALSPACE_DATA_DIR} - -# ── Per-dataset configuration ────────────────────────────────────────────── -# Only override patterns/flags when they differ from the defaults: -# organ_seg_pattern: "{ct_id}_seg.nii.gz" -# nodule_seg_pattern: "{annotation_id}.nii.gz" -# combined_mask_pattern: "{ct_id}_mask.nii.gz" - -datasets: - - DLCS24: - profile_csv: DLCS24_nodule_profiles.csv - meta_csv: DLCS24_BMdataset_FEB192026_FIT_v1.csv - - LUNA25: - profile_csv: LUNA25_nodule_profiles.csv - meta_csv: LUNA25_dataset_FEB192026_FIT_v1.csv - - LUNA16: - profile_csv: LUNA16_nodule_profiles.csv - meta_csv: LUNA16_dataset_FEB192026_FIT_v1.csv - - LUNGx: - profile_csv: LUNGx_nodule_profiles.csv - meta_csv: LUNGx_dataset_FEB192026_FIT_v1.csv - - LNDbv4: - profile_csv: LNDbv4_nodule_profiles.csv - meta_csv: LNDBv4_dataset_FEB192026_FIT_v1.csv - - NSCLCR: - profile_csv: NSCLCR_nodule_profiles.csv - meta_csv: NSCLCR_dataset_FEB192026_FIT_v1.csv - nodule_seg_pattern: "{annotation_id}.nii.gz" - combined_mask_pattern: "{ct_id}.nii.gz" - - IMDCT: - profile_csv: IMDCT_nodule_profiles.csv - meta_csv: IMDCT_dataset_FEB192026_FIT_v1.csv - nodule_seg_use_ct_id: true - nodule_seg_pattern: "{ct_id}_seg.nii.gz" - combined_mask_pattern: "{ct_id}_seg.nii.gz" diff --git a/itrialspace/configs/trials.yaml b/itrialspace/configs/trials.yaml deleted file mode 100644 index f1059ea91828b3a631423a6407986df9ae46f1d7..0000000000000000000000000000000000000000 --- a/itrialspace/configs/trials.yaml +++ /dev/null @@ -1,157 +0,0 @@ -# Published lung cancer screening trial parameters. -# Used by TrialKnowledgeBase to instantiate TrialSpec objects. -# -# Sources: -# NLST: Aberle et al. NEJM 2011; 365:395-409 -# NELSON: de Koning et al. NEJM 2020; 382:503-513 -# UKLS: Field et al. Lancet Respir Med 2016; 4:699-709 -# DANTE: Infante et al. AJRCCM 2009; 180:445-453 -# MILD: Pastorino et al. ERJ 2012; 39:1354-1362 - -trials: - - NLST: - full_name: "National Lung Screening Trial" - publication: "Aberle et al. NEJM 2011" - population: screening - n_participants: 26722 - demographics: - age_range: [55, 74] - age_mean: 61.4 - age_std: 5.0 - sex_ratio_male: 0.59 - smoking_status: ["Current", "Former"] - pack_years_min: 30 - nodule_prevalence: - any_nodule: 0.245 - malignancy_rate: 0.04 - size_distribution: - bucket_weights: - "<5mm": 0.42 - "5-10mm": 0.38 - "10-15mm": 0.11 - "15-20mm": 0.05 - "20-30mm": 0.03 - ">30mm": 0.01 - malignancy_rate_by_size: - "<5mm": 0.01 - "5-10mm": 0.024 - "10-15mm": 0.094 - "15-20mm": 0.178 - "20-30mm": 0.222 - ">30mm": 0.362 - lobe_distribution: - right_lung_upper_lobe: 0.30 - right_lung_middle_lobe: 0.08 - right_lung_lower_lobe: 0.18 - left_lung_upper_lobe: 0.28 - left_lung_lower_lobe: 0.16 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] - - NELSON: - full_name: "Nederlands-Leuvens Longkanker Screenings Onderzoek" - publication: "de Koning et al. NEJM 2020" - population: screening - n_participants: 7557 - demographics: - age_range: [50, 75] - age_mean: 58.0 - age_std: 5.5 - sex_ratio_male: 0.84 - smoking_status: ["Current", "Former"] - pack_years_min: 15 - nodule_prevalence: - any_nodule: 0.50 - malignancy_rate: 0.022 - size_distribution: - bucket_weights: - "<5mm": 0.55 - "5-10mm": 0.30 - "10-15mm": 0.09 - "15-20mm": 0.04 - ">20mm": 0.02 - malignancy_rate_by_size: - "<5mm": 0.005 - "5-10mm": 0.014 - "10-15mm": 0.063 - "15-20mm": 0.156 - ">20mm": 0.308 - lobe_distribution: - right_lung_upper_lobe: 0.30 - right_lung_middle_lobe: 0.08 - right_lung_lower_lobe: 0.18 - left_lung_upper_lobe: 0.28 - left_lung_lower_lobe: 0.16 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] - - UKLS: - full_name: "UK Lung Cancer Screening Trial" - publication: "Field et al. Lancet Respir Med 2016" - population: screening - n_participants: 1994 - demographics: - age_range: [50, 75] - sex_ratio_male: 0.52 - smoking_status: ["Current", "Former"] - pack_years_min: 20 - nodule_prevalence: - any_nodule: 0.34 - malignancy_rate: 0.017 - size_distribution: - bucket_weights: - "<5mm": 0.48 - "5-10mm": 0.35 - "10-15mm": 0.10 - "15-20mm": 0.04 - ">20mm": 0.03 - lobe_distribution: - right_lung_upper_lobe: 0.30 - right_lung_middle_lobe: 0.08 - right_lung_lower_lobe: 0.18 - left_lung_upper_lobe: 0.28 - left_lung_lower_lobe: 0.16 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] - - DANTE: - full_name: "Detection And screening of early lung Neoplasm with LDCT" - publication: "Infante et al. AJRCCM 2009" - population: screening - n_participants: 1276 - demographics: - age_range: [60, 75] - sex_ratio_male: 1.0 - smoking_status: ["Current", "Former"] - pack_years_min: 20 - nodule_prevalence: - any_nodule: 0.31 - malignancy_rate: 0.028 - size_distribution: - bucket_weights: - "<5mm": 0.40 - "5-10mm": 0.37 - "10-15mm": 0.13 - "15-20mm": 0.06 - ">20mm": 0.04 - applicable_source_datasets: ["DLCS24", "LUNA25"] - - MILD: - full_name: "Multicentric Italian Lung Detection Trial" - publication: "Pastorino et al. ERJ 2012" - population: screening - n_participants: 2376 - demographics: - age_range: [49, 75] - sex_ratio_male: 0.66 - smoking_status: ["Current", "Former"] - pack_years_min: 20 - nodule_prevalence: - any_nodule: 0.28 - malignancy_rate: 0.012 - size_distribution: - bucket_weights: - "<5mm": 0.52 - "5-10mm": 0.33 - "10-15mm": 0.09 - "15-20mm": 0.04 - ">20mm": 0.02 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] diff --git a/itrialspace/docker/Dockerfile b/itrialspace/docker/Dockerfile deleted file mode 100644 index d4eba00ae82e16a2a819adfea95081afbe77e337..0000000000000000000000000000000000000000 --- a/itrialspace/docker/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -# iTrialSpace — lightweight image for the core pipeline + web tools. -# -# docker build -t itrialspace -f docker/Dockerfile . -# docker run --rm -e ITRIALSPACE_DATA_DIR=/data -v /host/data:/data itrialspace its config -# -# GPU stages (synthesis, VLM) need a CUDA base image + torch; this image covers the -# core/imaging/web extras. See docs/installation.md for the GPU setup. -FROM python:3.11-slim - -ENV PYTHONUNBUFFERED=1 \ - PIP_NO_CACHE_DIR=1 \ - ITRIALSPACE_DATA_DIR=/data - -# System libs needed by nibabel/SimpleITK/matplotlib/faiss -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential libgl1 libglib2.0-0 git \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /app - -# Install dependencies first (better layer caching), then the package. -COPY pyproject.toml README.md ./ -COPY src ./src -COPY configs ./configs -RUN pip install --upgrade pip && pip install ".[imaging,web]" - -# Bring in the rest (docs, tests, infra, sample data) -COPY . . - -# Non-root user -RUN useradd -m -u 1000 its && mkdir -p /data && chown -R its:its /app /data -USER its - -ENTRYPOINT ["its"] -CMD ["config"] diff --git a/itrialspace/docker/Dockerfile.gpu b/itrialspace/docker/Dockerfile.gpu deleted file mode 100644 index 5c1b02c55782d2f140cdce0a276439e69f6bcc9c..0000000000000000000000000000000000000000 --- a/itrialspace/docker/Dockerfile.gpu +++ /dev/null @@ -1,51 +0,0 @@ -# iTrialSpace — GPU image for synthesis (NodMAISI) and VLM evaluation. -# Pinned to the development environment: CUDA 12.1, torch 2.4.1, git-pinned MONAI. -# -# docker build -t itrialspace-gpu -f docker/Dockerfile.gpu . -# -# # Step 3 synthesis (mount data, outputs, and the NodMAISI weights): -# docker run --rm --gpus all \ -# -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out \ -# -e NODMAISI_MODELS_DIR=/models \ -# -v /host/iTrialSpace:/data -v /host/outputs:/out -v /host/nodmaisi/models:/models \ -# --entrypoint python itrialspace-gpu \ -# -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ -# --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ -# --config src/itrialspace/synthesis/tools/integration_config.yaml \ -# --outdir /out/generated_cts/mode1_controlled_prevalence -# -# For a byte-for-byte clone of the dev env instead, build from requirements.lock.txt -# (see docs/installation.md). Base matches torch 2.4.1+cu121. -FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04 - -ENV DEBIAN_FRONTEND=noninteractive \ - PYTHONUNBUFFERED=1 \ - PIP_NO_CACHE_DIR=1 \ - ITRIALSPACE_DATA_DIR=/data \ - ITRIALSPACE_OUTPUT_DIR=/out \ - NODMAISI_MODELS_DIR=/models - -# System Python (3.10 on 22.04; package requires >=3.10) + libs for nibabel/SimpleITK/matplotlib -RUN apt-get update && apt-get install -y --no-install-recommends \ - python3 python3-pip python3-dev build-essential git \ - libgl1 libglib2.0-0 \ - && ln -sf /usr/bin/python3 /usr/bin/python \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /app -COPY . . - -# Match the dev env: torch 2.4.1 (cu121) and the git-pinned MONAI build, then the -# package (editable so the synthesis subprocess path model resolves like dev). -RUN pip install --upgrade pip \ - && pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 \ - && pip install "monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a" \ - && pip install -e ".[imaging,synthesis,vlm]" - -# Non-root user; create the runtime mount points -RUN useradd -m -u 1000 its && mkdir -p /data /out /models && chown -R its:its /app /data /out /models -USER its - -# Default to the umbrella CLI; override --entrypoint for synthesis/VLM module runs. -ENTRYPOINT ["its"] -CMD ["config"] diff --git a/itrialspace/docker/itrialspace.def b/itrialspace/docker/itrialspace.def deleted file mode 100644 index 57c2d95b23c93518956b525dd4d698f659fd1ca4..0000000000000000000000000000000000000000 --- a/itrialspace/docker/itrialspace.def +++ /dev/null @@ -1,68 +0,0 @@ -# Apptainer/Singularity recipe for iTrialSpace (GPU) — for HPC clusters that use -# Apptainer instead of Docker. Builds rootless, no Docker daemon required. -# -# # Build the image (.sif) — run from the repo root: -# apptainer build itrialspace.sif docker/itrialspace.def -# -# # Or convert the already-built Docker image: -# apptainer build itrialspace.sif docker-daemon://itrialspace-gpu:latest -# -# # Run the umbrella CLI (Apptainer bind-mounts $HOME and $PWD by default; add others): -# apptainer run --nv \ -# --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ -# -B /scratch/.../iTrialSpace:/data,/scratch/.../outputs:/out,/path/nodmaisi/models:/models \ -# itrialspace.sif config -# -# # Step 3 synthesis: -# apptainer exec --nv \ -# --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ -# -B /host/iTrialSpace:/data,/host/outputs:/out,/host/nodmaisi/models:/models \ -# itrialspace.sif \ -# python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ -# --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ -# --config /opt/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml \ -# --outdir /out/generated_cts/mode1_controlled_prevalence -# -# NOTE: build from the repo root so %files can copy the source tree. - -Bootstrap: docker -From: nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04 - -%files - . /opt/itrialspace - -%post - export DEBIAN_FRONTEND=noninteractive - apt-get update && apt-get install -y --no-install-recommends \ - python3 python3-pip python3-dev build-essential git \ - libgl1 libglib2.0-0 - ln -sf /usr/bin/python3 /usr/bin/python - rm -rf /var/lib/apt/lists/* - - cd /opt/itrialspace - # Drop any host-local state copied in via %files - rm -rf .git .env logs/* **/__pycache__ 2>/dev/null || true - pip install --upgrade pip - pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 - pip install "monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a" - pip install -e ".[imaging,synthesis,vlm]" - -%environment - export ITRIALSPACE_ROOT=/opt/itrialspace - export ITRIALSPACE_DATA_DIR=${ITRIALSPACE_DATA_DIR:-/data} - export ITRIALSPACE_OUTPUT_DIR=${ITRIALSPACE_OUTPUT_DIR:-/out} - export NODMAISI_MODELS_DIR=${NODMAISI_MODELS_DIR:-/models} - export PYTHONUNBUFFERED=1 - -%runscript - exec its "$@" - -%labels - Name iTrialSpace - Description Synthetic Imaging Clinical Trial Engine (GPU) - -%help - iTrialSpace container. Bind your data/outputs/weights and set the matching - ITRIALSPACE_DATA_DIR / ITRIALSPACE_OUTPUT_DIR / NODMAISI_MODELS_DIR env vars. - Use `apptainer run` for the `its` CLI, or `apptainer exec ... python -m ...` - for synthesis/VLM module runs. See docs/installation.md. diff --git a/itrialspace/docs/architecture.md b/itrialspace/docs/architecture.md deleted file mode 100644 index 2c83caae17c1a2410c23cf10ee15125b6735943c..0000000000000000000000000000000000000000 --- a/itrialspace/docs/architecture.md +++ /dev/null @@ -1,64 +0,0 @@ -# Architecture - -iTrialSpace is one installable package, `itrialspace`, using a `src/` layout. Each former -top-level project is now a subpackage under a single namespace. - -``` -src/itrialspace/ -├── config/ Portable path/settings resolution (settings.py) -├── core/ Data model: NoduleProfile, LabelNormaliser, schema, enums -├── io/ Dataset loading: DatasetLoader, DatasetRegistry, adapters -├── index/ NoduleIndex — merged multi-dataset DataFrame -├── query/ NoduleQuery (fluent filters), ReinsertionMatcher (k-NN) -├── site/ Synthetic trial engine: specs, sampling, planner, cohort builder -├── trials/ Trial manifest runner (the 13 modes) -├── mask_inserter/ Voxel-level nodule mask insertion (label 23) -├── synthesis/ NodMAISI CT synthesis (model weights external) -├── apps/ -│ ├── nodulemap/ Embedding graph viz (FastAPI + sigma.js) -│ └── retriever/ Faceted search + similarity UI (FastAPI + Streamlit) -├── evaluation/ OPTIONAL evaluation extras -│ ├── vlm_eval/ Vision-language model evaluation -├── utils/ Shared helpers -└── cli.py Umbrella `its` CLI -``` - -Supporting top-level directories: - -``` -configs/ Example configs (*.example.yaml) + non-path configs (trials, features) -infra/slurm/ HPC submission scripts, cluster-portable via env.sh -docs/ This documentation -tests/ Unified pytest suite (runs with no external data) -docker/ Container build -``` - -## Component map (old → new) - -| Original top-level | New namespace | Console script | -|--------------------|---------------|----------------| -| `itrialspace/` (core) | `itrialspace.{core,io,index,query,site}` | `its` | -| `itrialspace_mask_inserter/` | `itrialspace.mask_inserter` | `its-insert` | -| `site_trials/` | `itrialspace.trials` | `its-trials` | -| `nodmaisi_synth/` (code) | `itrialspace.synthesis` | (subprocess) | -| `nodulemap/` | `itrialspace.apps.nodulemap` | `its-nodulemap` | -| `retriever/` | `itrialspace.apps.retriever` | `its-retriever` | -| `vlm_evaluation/` | `itrialspace.evaluation.vlm_eval` | (module/scripts)* | - - -\* VLM evaluation runs via its module scripts (`python -m itrialspace.evaluation.vlm_eval...`) -rather than a console entry point; see [reference/08_VLM_EVALUATION.md](reference/08_VLM_EVALUATION.md). - -## Data flow - -``` -NoduleIndex ──▶ CohortBuilder ──▶ mask_inserter ──▶ synthesis ──▶ evaluation - (7 datasets) (TrialSpec → (donor mask (NodMAISI (CADe/CADx/VLM) - manifest) @ label 23) CT volume) - │ - ├─▶ nodulemap (graph viz) - └─▶ retriever (search) -``` - -See [pipeline.md](pipeline.md) for the full end-to-end flow and -[SKILL.md](../SKILL.md) for an exhaustive per-file reference. diff --git a/itrialspace/docs/configuration.md b/itrialspace/docs/configuration.md deleted file mode 100644 index 7ff623526278c1cdeb48fb6906c18b1ac4d1955c..0000000000000000000000000000000000000000 --- a/itrialspace/docs/configuration.md +++ /dev/null @@ -1,79 +0,0 @@ -# Configuration & path model - -iTrialSpace resolves **every** filesystem path from environment variables (with sensible -defaults), so the same code and configs run unchanged on a laptop, a workstation, or an -HPC cluster. Nothing is hardcoded. - -The single source of truth is [`itrialspace.config.settings`](../src/itrialspace/config/settings.py). - -## Environment variables - -Copy `.env.example` → `.env` and edit. (`infra/slurm/env.sh` and the synthesis -config loaders all read these.) - -| Variable | Default | Meaning | -|----------|---------|---------| -| `ITRIALSPACE_DATA_DIR` | `~/.itrialspace/data` | Root of the unified data layout | -| `ITRIALSPACE_OUTPUT_DIR` | `=DATA_DIR` | Where generated artifacts are written | -| `ITRIALSPACE_ROOT` | auto-detected | Repo root (for resolving `configs/`) | -| `NODMAISI_MODELS_DIR` | — | NodMAISI model weights directory | -| `EVAL_WEIGHTS_DIR`, `EVAL_CONFIGS_DIR`, `PINS_ROOT`, `FPRDL_ROOT`, … | — | Optional CADe/CADx externals | -| `ITRIALSPACE_CONDA_ENV`, `SLURM_PARTITION_*` | `itrialspace`, … | HPC/SLURM only | - -Check what resolved: - -```bash -its config -``` - -## YAML interpolation - -Any string in a config YAML may reference these variables with `${VAR}` syntax. The -config loaders expand them (falling back to the documented defaults even when the variable -is not exported): - -```yaml -# configs/paths.yaml -base_dir: ${ITRIALSPACE_DATA_DIR} -``` - -## Config file resolution - -Path-bearing configs ship as `configs/*.example.yaml`. Resolution order -(`settings.find_config`): - -1. `ITRIALSPACE__CONFIG` env override (e.g. `ITRIALSPACE_DATASETS_CONFIG`) -2. `configs/.yaml` (your local copy — gitignored) -3. `configs/.example.yaml` (shipped example) -4. the default bundled inside the package - -To customize, copy the example and edit: - -```bash -cp configs/paths.example.yaml configs/paths.yaml -``` - -| Config | Example file | Used by | -|--------|--------------|---------| -| Dataset registry | `configs/datasets.example.yaml` | `DatasetRegistry.from_yaml()` | -| Data layout | `configs/paths.example.yaml` | `PathResolver` | -| NodMAISI integration | `configs/integration.example.yaml` | synthesis pipeline | -| Mask inserter | `configs/mask_inserter.example.yaml` | mask insertion | -| CADe/CADx externals | `configs/eval.example.yaml` | optional eval | -| Trial templates | `configs/trials.yaml` | trial knowledge base (no paths) | -| Embedding features | `configs/features.yaml` | NoduleMap (no paths) | - -## Using the API directly - -```python -from itrialspace.config import settings -settings.data_dir() # Path to the data root -settings.load_yaml("configs/paths.example.yaml") # loads + expands ${VARS} -settings.find_config("datasets.yaml") # resolves a config path -``` - -## Portability guard - -`tools/check_portability.py` (run by pre-commit and CI) fails the build if any tracked -file reintroduces a hardcoded absolute path. Always resolve paths through `settings` or -env vars. diff --git a/itrialspace/docs/data.md b/itrialspace/docs/data.md deleted file mode 100644 index 51620a961d0b97bfa3fcbc1a75c1cc4796367705..0000000000000000000000000000000000000000 --- a/itrialspace/docs/data.md +++ /dev/null @@ -1,63 +0,0 @@ -# Data preparation - -iTrialSpace ships **code only**. The source CT datasets and trained model weights are not -redistributed (they carry their own licenses and are large). This guide describes the -expected layout and how to obtain the data. - -The repo bundles **no data** — point `ITRIALSPACE_DATA_DIR` at your real data root (set it -once in `.env`; see [configuration.md](configuration.md)). Examples and data-dependent -tests read from there and skip cleanly when it isn't present (e.g. in CI). - -## Unified data layout - -Point `ITRIALSPACE_DATA_DIR` (in `.env`) at a directory with this structure: - -``` -$ITRIALSPACE_DATA_DIR/ -├── raw_ct/{DATASET}/ CT scans (NIfTI, RAS+) -├── masks/{DATASET}/ -│ ├── nodule_seg/ Individual nodule masks -│ ├── combined_seg/ Combined per-patient masks -│ ├── organ_seg/ VISTA3D organ segs (raw, deprecated) -│ └── refined_seg/ Refined organ + body segs (default) -├── profiles/ {DATASET}_nodule_profiles.csv (53-column schema) -├── meta/ Original dataset metadata CSVs -├── manifests/ Generated cohort manifests -├── inserted_masks/ Mask-insertion outputs -└── generated_cts/ NodMAISI synthesis outputs -``` - -`ct_path` values in the profile CSVs are **relative** to `raw_ct/`, e.g. -`DLCS24/DLCS_0001.nii.gz`. Verify resolution with `its config` and the `PathResolver`. - -## The 7 supported datasets - -| Dataset | Source | Notes | -|---------|--------|-------| -| **DLCS24** | Duke Lung Cancer Screening | Binary label, Lung-RADS, demographics | -| **LUNA25** | LUNA25 challenge | Largest; multi-nodule screening | -| **LUNA16** | LUNA16 / LIDC-IDRI | No malignancy label (anatomy only) | -| **LUNGx** | SPIE-AAPM LUNGx | CADx benchmark, ~49% malignant | -| **LNDbv4** | LNDb | Multi-radiologist ratings (float → threshold) | -| **NSCLCR** | NSCLC-Radiomics (TCIA) | 100% malignant, staging/survival | -| **IMDCT** | Internal multi-modal diagnostic CT | PET, spiculation, benign/cancer | - -> `NLST3D` was permanently removed from the core pipeline for data-quality reasons and is -> guarded against at multiple layers. - -Each public dataset must be obtained from its original source under its own license. Once -downloaded, harmonize each into the 53-column `CORE_COLS` schema (see -`itrialspace.core.schema`) as `{DATASET}_nodule_profiles.csv` and place CTs/masks per the -layout above. - -## Adding a new dataset - -1. Produce `{DATASET}_nodule_profiles.csv` matching `CORE_COLS` (incl. the 12 - `reinsertion_*` columns). -2. Add an adapter in `src/itrialspace/io/adapters/adapters.py`. -3. Register it in `core/schema.py` (`DATASET_NAMES`, `DATASET_FLAGS`), `core/label.py`, - and `configs/datasets.example.yaml` + `configs/paths.example.yaml`. -4. Add tests. - -See [reference/04_NODULE_PROFILING.md](reference/04_NODULE_PROFILING.md) for the full -harmonization methodology. diff --git a/itrialspace/docs/evaluation_external_dependencies.md b/itrialspace/docs/evaluation_external_dependencies.md deleted file mode 100644 index d5120cddcf22579f232d543465ec0adaf9546671..0000000000000000000000000000000000000000 --- a/itrialspace/docs/evaluation_external_dependencies.md +++ /dev/null @@ -1,58 +0,0 @@ -# CADe/CADx evaluation — external dependencies - -The optional CADe/CADx evaluation pipelines (`itrialspace.evaluation`, installed via -`pip install -e ".[eval]"`) depend on trained models and helper repositories that are -**not bundled** with iTrialSpace. The core pipeline (index → trials → masks → synthesis → -VLM eval) does **not** need any of these. - -## What you need - -| Env var | Points to | Used for | -|---------|-----------|----------| -| `EVAL_WEIGHTS_DIR` | trained detector/classifier weights (`.pt`) | CADe + CADx inference | -| `EVAL_CONFIGS_DIR` | the models' training/inference JSON configs | model construction | -| `EVAL_SCRIPTS_DIR` | helper scripts (e.g. `generate_transforms.py`) | MONAI transform builders | -| `PINS_ROOT` | PiNS — world-coordinate patch extractor | CADx patch extraction | -| `FPRDL_ROOT` | fprDL — false-positive-reduction inference | FPR-DL stage | -| `NOMAISI_ROOT` | NoMAISI core | synthesis utilities / FID | -| `MAISI_CORE_ROOT` | MAISI core | FID / metrics | -| `LUNGRADS_ROOT` | LungRADS classifier code | CADx meta analysis | - -Set these in `.env`, then copy and fill in `configs/eval.example.yaml`: - -```bash -cp configs/eval.example.yaml configs/eval.yaml -``` - -## Expected model files (example) - -``` -$EVAL_WEIGHTS_DIR/ -├── model_DukeLungRADs_..._fold1.pt # NODet detector -├── model_DukeLungRADs_..._noduleonly_fold1.pt # BaNODet detector -├── DLCS24CADx_Fold1_resnet50SWS.pt # CADx (DLCS24) -├── LUNA25CADx_prct100_resnet50.pt # CADx (LUNA25) -├── ..._FPR_r50SSL_...pt # FPR-DL (SSL) -└── ..._FPR_r50WSPP_...pt # FPR-DL (WSPP) - -$EVAL_CONFIGS_DIR/ -├── tr_config_NODet.json -├── tr_config_BaNODet.json -├── tr_config_DLCS24CADxr50SWS.json -├── tr_config_LUNA25CADx_r50.json -├── tr_config_fprDL_r50SSL.json -└── tr_config_fprDL_r50WSPP.json -``` - -## Why these aren't bundled - -These models and repositories are developed and licensed separately from iTrialSpace. -Bundling them would bloat the repo and conflate licenses. iTrialSpace provides the -evaluation **glue** (candidate CSV building, patch extraction orchestration, result -aggregation); you bring the models. - -## Running - -SLURM scripts live under `infra/slurm/{detection_inference,cade_synthetic_eval, -cadx_synthetic_eval,cadx_meta_analysis}/`. Set the env vars above (or `configs/eval.yaml`) -before submitting. See [infra/slurm/README.md](../infra/slurm/README.md). diff --git a/itrialspace/docs/index.md b/itrialspace/docs/index.md deleted file mode 100644 index 71faa50594c5a7ee0301fd8073626f7a95f95705..0000000000000000000000000000000000000000 --- a/itrialspace/docs/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# iTrialSpace Documentation - -**Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation.** - -iTrialSpace harmonizes 13,140 nodule profiles from 7 public lung CT datasets, builds -virtual clinical-trial cohorts across 13 trial modes, inserts donor nodule masks into -real host anatomy, synthesizes CT volumes with a ControlNet-conditioned diffusion model -(NodMAISI), and evaluates CADe/CADx detectors and vision-language models. - -## Start here - -| Guide | What it covers | -|-------|----------------| -| [Installation](installation.md) | Environments, extras, GPU/torch, Docker | -| [Quickstart](quickstart.md) | First commands; build the index; run a trial | -| [Walkthrough: Mode 1 end-to-end](walkthrough_mode1.md) | 200 cases: plan → insert → generate CTs | -| [Running the pipeline (runbook + smoke test)](running_the_pipeline.md) | All 13 modes via SLURM; copy-paste commands for every step | -| [Configuration](configuration.md) | The env-driven path model (runs anywhere) | -| [Data preparation](data.md) | Laying out the 7 datasets; sample fixtures | -| [Architecture](architecture.md) | Components and how they fit together | -| [Pipeline](pipeline.md) | End-to-end flow: index → trials → masks → CT → eval | -| [Trial modes](trial_modes.md) | The 13 trial modes | -| [NoduleMap](nodulemap.md) | Build + serve the embedding graph explorer (`its-nodulemap`) | -| [NoduleMap similarity design](nodulemap_similarity.md) | Donor-matching metric + optional appearance (radiomics/foundation) roadmap | -| [Reproducibility](reproducibility.md) | Determinism, audit trails, HPC orchestration | -| [Evaluation external dependencies](evaluation_external_dependencies.md) | CADe/CADx extra requirements | - -## Deeper reference - -- [SKILL.md](../SKILL.md) — exhaustive machine-readable reference (every file/class/function). -- [docs/reference/](reference/) — scientific narrative and paper-positioning documents - (`00_PROJECT_OVERVIEW.md` … `12_CLINICAL_DATASET_ANALYSIS.md`). - -> Some paths in the `reference/` documents predate the public-release monorepo layout and -> may show the original component names; the authoritative layout is in -> [architecture.md](architecture.md). diff --git a/itrialspace/docs/installation.md b/itrialspace/docs/installation.md deleted file mode 100644 index 7b158267c552e994c261f29a57be90e66a2f7995..0000000000000000000000000000000000000000 --- a/itrialspace/docs/installation.md +++ /dev/null @@ -1,178 +0,0 @@ -# Installation - -iTrialSpace is a single installable package (`itrialspace`) with **optional-dependency -extras** so you install only what a given task needs. It runs on a workstation or an HPC -cluster — nothing is hardcoded to a specific machine. - -## 1. Get the code - -```bash -git clone -cd itrialspace -``` - -## 2. Create an environment - -**Conda (recommended for the imaging/ML stack)** — versions pinned to the dev env (Python 3.10): - -```bash -conda env create -f environment.yml -conda activate itrialspace -``` - -**Exact clone of the development environment** (Python 3.10.13, -torch 2.4.1+cu121, git-pinned MONAI, full pinned set) — the "give me exactly what worked" -option: - -```bash -conda env create -f environment.lock.yml # one command; uses requirements.lock.txt -conda activate itrialspace -# or into a plain venv: -# python3.10 -m venv .venv && . .venv/bin/activate -# pip install -r requirements.lock.txt && pip install -e . -``` - -> The lock includes torch + MONAI and some packages from the original shared env; it -> targets linux-64 / CUDA 12.1. Trim `requirements.lock.txt` if you only need certain stages. - -**Or a minimal plain venv:** - -```bash -python -m venv .venv && source .venv/bin/activate -pip install --upgrade pip -``` - -## 3. Install with the extras you need - -```bash -pip install -e ".[imaging,web]" # core pipeline + web tools -pip install -e ".[dev]" # + tests/lint/format -pip install -e ".[all]" # imaging + web + vlm + dev -``` - -| Extra | Installs | Enables | -|-------|----------|---------| -| *(base)* | pandas, numpy, pyyaml | Index, query, trial planning | -| `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI I/O | -| `web` | fastapi, streamlit, faiss, umap-learn, pyarrow | NoduleMap + Retriever | -| `synthesis` | monai | NodMAISI synthesis* | -| `vlm` | transformers, open_clip_torch | VLM evaluation* | -| `eval` | monai, scikit-learn | CADe/CADx evaluation** | -| `dev` | pytest, ruff, black, pre-commit | Development | - -\* **PyTorch is not declared as a dependency** — install the build matching your CUDA: - -```bash -# match the dev env: CUDA 12.1 -pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 -pip install -e ".[synthesis,vlm]" -``` - -\*\* The `eval` extra also needs **external** models/repos that are not bundled — see -[evaluation_external_dependencies.md](evaluation_external_dependencies.md). - -## 4. Configure paths - -```bash -cp .env.example .env # then edit ITRIALSPACE_DATA_DIR etc. -its config # prints the resolved paths — verify them -``` - -See [configuration.md](configuration.md) for the full path model. - -## 5. Verify - -```bash -pytest -m "not full_volume" # unit tests (no external data needed) -python tools/check_portability.py # no hardcoded paths -``` - -## Model weights (NodMAISI synthesis) - -Synthesis model weights (`autoencoder.pt`, `diffusion_unet.pt`, the ControlNet -checkpoint) are **not** in the repo. Obtain them (see the NodMAISI release / Hugging Face) -and point to their directory: - -```bash -export NODMAISI_MODELS_DIR=/path/to/nodmaisi/models -``` - -## Containers - -**Mental model:** the image ships **code only**. Data, model weights, and outputs are -**mounted at runtime** (`-v host:container`) and pointed to with env vars — they're never -baked into the image. There are three deployment routes: - -| Target | Use | -|--------|-----| -| New HPC cluster | conda env (`environment.yml`) + SLURM (`infra/slurm/`) — Docker usually unavailable on compute nodes | -| Standalone server / cloud VM (CPU) | **Docker (CPU)** image | -| GPU server / synthesis & VLM | **Docker (GPU)** image, or **Apptainer** on HPC | - -### Docker — CPU image (core + imaging + web) - -```bash -docker build -t itrialspace -f docker/Dockerfile . - -# verify resolved paths -docker run --rm -e ITRIALSPACE_DATA_DIR=/data -v /host/iTrialSpace:/data \ - itrialspace its config - -# generate a manifest (mount data + outputs) -docker run --rm \ - -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out \ - -v /host/iTrialSpace:/data -v /host/outputs:/out \ - itrialspace its-trials --mode controlled_prevalence --n-cases 200 --output-dir /out/manifests/mode1 - -# launch a web tool (publish the port) -docker run --rm -p 8422:8422 -e ITRIALSPACE_DATA_DIR=/data -v /host/iTrialSpace:/data \ - itrialspace its-nodulemap serve --port 8422 -``` -The entrypoint is `its`, so the trailing args are the subcommand. For a shell: -`docker run --rm -it --entrypoint bash itrialspace`. This image has **no PyTorch/CUDA** — -it cannot run synthesis/VLM. - -### Docker — GPU image (synthesis + VLM) - -```bash -docker build -t itrialspace-gpu -f docker/Dockerfile.gpu . - -# Step 3 synthesis — mount data, outputs, AND the NodMAISI weights -docker run --rm --gpus all \ - -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out -e NODMAISI_MODELS_DIR=/models \ - -v /host/iTrialSpace:/data -v /host/outputs:/out -v /host/nodmaisi/models:/models \ - --entrypoint python itrialspace-gpu \ - -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ - --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ - --config src/itrialspace/synthesis/tools/integration_config.yaml \ - --outdir /out/generated_cts/mode1_controlled_prevalence -``` -Built on `nvidia/cuda:12.1.1-cudnn8-runtime` + torch 2.4.1 (cu121). Requires the NVIDIA Container -Toolkit on the host (`--gpus all`). Adjust the CUDA tag in `docker/Dockerfile.gpu` to match -your driver. - -### Apptainer / Singularity (HPC clusters) - -Most clusters disallow Docker but support Apptainer (rootless, no daemon): - -```bash -# build from the recipe (run at repo root), or convert a built Docker image -apptainer build itrialspace.sif docker/itrialspace.def -# apptainer build itrialspace.sif docker-daemon://itrialspace-gpu:latest - -# run the CLI (bind data/outputs/weights; --nv exposes GPUs) -apptainer run --nv \ - --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ - -B /scratch/.../iTrialSpace:/data,/scratch/.../outputs:/out,/path/models:/models \ - itrialspace.sif config - -# synthesis -apptainer exec --nv \ - --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ - -B /host/iTrialSpace:/data,/host/outputs:/out,/host/models:/models \ - itrialspace.sif \ - python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ - --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ - --config /opt/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml \ - --outdir /out/generated_cts/mode1_controlled_prevalence -``` diff --git a/itrialspace/docs/pipeline.md b/itrialspace/docs/pipeline.md deleted file mode 100644 index 1315cc47430d3e53c94b0aab3ad254adc8a352fd..0000000000000000000000000000000000000000 --- a/itrialspace/docs/pipeline.md +++ /dev/null @@ -1,39 +0,0 @@ -# End-to-end pipeline - -The full flow from raw datasets to evaluation results. - -``` -1. INDEX NoduleIndex loads 7 dataset CSVs → unified DataFrame (13,140 × 53 cols) -2. PLAN CohortBuilder applies a TrialSpec (1 of 13 modes) → CohortManifest CSV -3. INSERT mask_inserter pastes donor nodule masks into host organ segs @ label 23 -4. SYNTHESIZE NodMAISI (ControlNet rectified-flow diffusion) → synthetic CT volumes -5. EVALUATE CADe (RetinaNet), CADx (FPR-DL + classifiers), and VLM zero-shot eval -6. EXPLORE NoduleMap (graph) and Retriever (search) over the index -``` - -## Commands per stage - -```bash -# 2. Plan -its-trials --mode controlled_prevalence --n-cases 200 --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1" - -# 3. Insert -its-insert run --manifest --output-dir "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" - -# 4. Synthesize (needs NODMAISI_MODELS_DIR) -python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ - --mask-root "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" \ - --config configs/integration.example.yaml \ - --outdir "$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1" - -# 5. Evaluate (VLM) -python -m itrialspace.evaluation.vlm_eval.build_dataset --profile lung_axial ... -python -m itrialspace.evaluation.vlm_eval.run_all ... -``` - -Each stage also has SLURM scripts under `infra/slurm/`. - -## Full detail - -See [reference/02_PIPELINE_END_TO_END.md](reference/02_PIPELINE_END_TO_END.md) and -[reference/06_INSERTION_AND_DIGITAL_TWINS.md](reference/06_INSERTION_AND_DIGITAL_TWINS.md). diff --git a/itrialspace/docs/quickstart.md b/itrialspace/docs/quickstart.md deleted file mode 100644 index a37bd4e4a45b63eee31ea25371abb51a25486074..0000000000000000000000000000000000000000 --- a/itrialspace/docs/quickstart.md +++ /dev/null @@ -1,72 +0,0 @@ -# Quickstart - -Assumes you've [installed](installation.md) the package and run `cp .env.example .env`. - -## Verify your setup - -```bash -its config # prints resolved data dir, output dir, configs dir -its --help -``` - -## With your datasets - -Point `ITRIALSPACE_DATA_DIR` at your data root (set in `.env`) so the 7 datasets are laid -out under `$ITRIALSPACE_DATA_DIR/profiles/` etc. (see [data.md](data.md)): - -```bash -# Build the unified index and print stats -its index stats - -# List configured datasets -its info -``` - -```python -from itrialspace import NoduleIndex, DatasetRegistry - -idx = NoduleIndex.from_registry(DatasetRegistry.from_yaml()) -malignant_upper = ( - idx.query() - .malignant() - .lobe(["right_upper", "left_upper"]) - .diameter(8, 20) - .fetch() -) -print(len(malignant_upper)) -``` - -## Generate a trial cohort manifest - -```bash -its-trials --mode controlled_prevalence --n-cases 200 --prevalence 0.05 \ - --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1" -``` - -See [trial_modes.md](trial_modes.md) for all 13 modes. - -## Insert nodule masks → synthesize CTs - -```bash -# Insert donor masks into host organ segmentations (label 23) -its-insert run --manifest "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1/.csv" \ - --output-dir "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" - -# Synthesize CTs (needs NODMAISI_MODELS_DIR; see installation.md) -python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ - --mask-root "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" \ - --config configs/integration.example.yaml \ - --outdir "$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1" -``` - -## Explore interactively - -```bash -its-nodulemap serve --port 8422 # graph visualization (needs built artifacts) -its-retriever serve # faceted search API + Streamlit UI -``` - -## On HPC - -Every stage has SLURM scripts under `infra/slurm/` that are cluster-portable via -`infra/slurm/env.sh`. See [infra/slurm/README.md](../infra/slurm/README.md). diff --git a/itrialspace/docs/reproducibility.md b/itrialspace/docs/reproducibility.md deleted file mode 100644 index fda2658b9dc92d80a2bedd7320318b05d7bfe153..0000000000000000000000000000000000000000 --- a/itrialspace/docs/reproducibility.md +++ /dev/null @@ -1,24 +0,0 @@ -# Reproducibility - -iTrialSpace is designed for exact reproduction. - -- **Determinism**: `seed=42` throughout. Per-case placement seeds are derived as - `SHA-256(trial_name + case_id + nodule_idx + global_seed)` — identical inputs produce - identical outputs. -- **Audit trails**: mask insertion writes `audit.json` (24-field provenance per case); - synthesis writes `nodmaisi_audit.json` and a `pipeline_summary.json`. -- **NIfTI orientation**: all volumes are canonicalized to RAS+ (`nib.as_closest_canonical`) - before any voxel operation. -- **Config-pinned paths**: every path comes from `ITRIALSPACE_DATA_DIR` / configs, so a - run is fully described by its `.env` + config + seed. -- **HPC orchestration**: `infra/slurm/` scripts are cluster-portable via `env.sh`. - -## Reproducing a run - -```bash -cp .env.example .env # set ITRIALSPACE_DATA_DIR, seed defaults to 42 -its-trials --mode --seed 42 --output-dir -# inspect /_run_config.json for the exact parameters used -``` - -Full guide: [reference/10_REPRODUCIBILITY_GUIDE.md](reference/10_REPRODUCIBILITY_GUIDE.md). diff --git a/itrialspace/docs/running_the_pipeline.md b/itrialspace/docs/running_the_pipeline.md deleted file mode 100644 index d6baeaf2111ca390f4ee85181466c3d16243b007..0000000000000000000000000000000000000000 --- a/itrialspace/docs/running_the_pipeline.md +++ /dev/null @@ -1,275 +0,0 @@ -# Running the pipeline (runbook + smoke test) - -A self-contained, copy-paste guide to run iTrialSpace end-to-end on an HPC cluster -(SLURM) — for **all 13 trial modes**, from a 5-case smoke test up to full runs. Every -command is here; you should not need to invent any. - -> ⚠️ **The scripts ship as a QUICK DEMO run with deliberately small numbers** (≈5 cases -> per mode) so the whole pipeline finishes in minutes for validation. These are **not** -> the paper/production sizes. To reproduce the real run, change the case counts as shown -> in **[§5](#5-run-size--demo-vs-paperproduction-run)** (which also lists the exact -> paper-run values and the file + line to edit for every mode). - -**Pipeline:** `trials (manifest) → insertion (label-23 masks + audit) → synthesis (CT)` -→ optional evaluation (VLM / CADe / CADx). - ---- - -## 0. One-time setup - -```bash -git clone && cd itrialspace # always run commands from the repo root - -# Create the environment (matches the verified dev versions). One of: -conda env create -f environment.yml # curated, pinned -# or an exact clone: -# conda env create -f environment.lock.yml - -# Configure paths/env for this machine -cp .env.example .env -``` - -Edit `.env` (read automatically by every SLURM job via `infra/slurm/env.sh`): - -```bash -ITRIALSPACE_DATA_DIR=/scratch/.../iTrialSpace # INPUTS: raw_ct/ masks/ profiles/ meta/ -ITRIALSPACE_OUTPUT_DIR=/scratch/.../my_outputs # OUTPUTS: manifests/ inserted_masks/ generated_cts/ -ITRIALSPACE_CONDA_ENV=itrialspace # the conda env to activate -NODMAISI_MODELS_DIR=/path/to/nodmaisi/models # synthesis weights (Step 3 only) -SLURM_PARTITION_GPU=vram48 # your GPU partition -SLURM_PARTITION_CPU=defq # your CPU partition -``` - -Verify resolution: - -```bash -its config # prints the resolved data/output dirs and config locations -``` - -> **Cluster notes baked in** (no action needed): jobs run with `PYTHONNOUSERSITE=1` -> (isolated from `~/.local`) and put the env's CUDA libs on `LD_LIBRARY_PATH` (so cuDNN -> initializes). `#SBATCH --partition/--account/--time` are in each `.sub` — edit them for -> your cluster. **Always `sbatch` from the repo root** so `env.sh` is found. - ---- - -## 1. The easy way — one command per mode - -`infra/slurm/run_pipeline.sh` chains all three stages with SLURM dependencies and builds -the manifest/case lists the array jobs need. - -```bash -# Full pipeline for one mode (trials → insertion → synthesis): -infra/slurm/run_pipeline.sh 1 - -# All 13 modes: -for m in $(seq 1 13); do infra/slurm/run_pipeline.sh $m; done - -# Just one stage: -infra/slurm/run_pipeline.sh 2 trials # manifests only -infra/slurm/run_pipeline.sh 2 insert # insertion (after trials done) -infra/slurm/run_pipeline.sh 2 synth # synthesis (after insertion done) -``` - -Run size comes from each mode's `.sub` (see §5). To understand or customize the stages, -read §2–§4 — they are exactly what the helper runs. - ---- - -## 2. Step 1 — Trials (generate cohort manifests) - -One `sbatch` per mode. Each writes manifest CSV/JSON to -`$ITRIALSPACE_OUTPUT_DIR/manifests/mode_*/`. - -```bash -sbatch infra/slurm/trials/mode1_controlled_prevalence.sub -sbatch infra/slurm/trials/mode2_size_detection_curve.sub -# ... mode3 … mode13 (filenames below) -``` - -| Mode | Script | Produces | -|------|--------|----------| -| 1 | `mode1_controlled_prevalence.sub` | 1 manifest | -| 2 | `mode2_size_detection_curve.sub` | per size bucket | -| 3 | `mode3_location_sensitivity.sub` | per lobe | -| 4 | `mode4_demographic_stratification.sub` | per stratum | -| 5 | `mode5_counterfactual.sub` | per varied value | -| 6 | `mode6_cross_dataset.sub` | per dataset | -| 7 | `mode7_bootstrap_confidence.sub` | per replicate | -| 8 | `mode8_algorithm_comparison.sub` | 1 manifest | -| 9 | `mode9_screening_simulation.sub` | per round | -| 10 | `mode10_multi_nodule_realism.sub` | 2 (single + multi sub-cohorts) | -| 11 | `mode11_digital_twin_isolation.sub` | per dataset | -| 12 | `mode12_digital_twin_complete.sub` | per dataset | -| 13 | `mode13_digital_twin_cross.sub` | per host×donor pair | - -Verify: - -```bash -ls $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/ # NLST_cohort.csv … -``` - ---- - -## 3. Step 2 — Insertion (paste nodule masks) - -Reads a mode's manifests and writes a combined label-23 mask per case plus an -`audit.json` per manifest. Uses the **array** script (one task per manifest): - -```bash -source infra/slurm/env.sh # defines $ITRIALSPACE_OUTPUT_DIR etc. -M=1 # mode number -DIR=$(ls -d $ITRIALSPACE_OUTPUT_DIR/manifests/mode${M}_* | head -1) -ML=$ITRIALSPACE_OUTPUT_DIR/manifest_lists/mode${M}.txt -mkdir -p "$(dirname "$ML")"; ls "$DIR"/*.csv | sort > "$ML" - -sbatch --array=0-$(( $(wc -l < "$ML") - 1 )) \ - --export=ALL,MANIFEST_LIST="$ML" \ - infra/slurm/mask_inserter/mode${M}_insert_masks_array.sub -``` - -Preview without writing files: append `,DRY_RUN=true` to `--export`. - -Verify: - -```bash -find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name audit.json -find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name '*_mask.nii.gz' | wc -l -``` - ---- - -## 4. Step 3 — Synthesis (generate CTs) — **GPU + model weights** - -Needs `NODMAISI_MODELS_DIR` set and the `synthesis` extra installed. One array job per -manifest's `audit.json`, one task per case. Case IDs must be the **mask-filename stems** -(`infra/slurm/_gen_caselist.py` does this): - -```bash -source infra/slurm/env.sh -M=1 -audit=$(find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name audit.json | sort | head -1) -cl=$ITRIALSPACE_OUTPUT_DIR/nodmaisi_case_lists/mode${M}.txt -n=$(python infra/slurm/_gen_caselist.py "$audit" "$cl") # prints N cases - -sbatch --array=0-$((n-1)) \ - --export=ALL,AUDIT_PATH="$audit",CASE_LIST="$cl",OUT_DIR="$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M}" \ - infra/slurm/synthesis/mode1_nodmaisi_array.sub -``` - -(`mode1_nodmaisi_array.sub` is generic — driven by the `AUDIT_PATH`/`CASE_LIST`/`OUT_DIR` -env vars, so it works for any mode. For modes with multiple manifests, repeat per -`audit.json`.) Validate inputs without a GPU first by running the bridge with `--dry-run` -(see [walkthrough_mode1.md](walkthrough_mode1.md)). - -Verify, per case directory: - -```bash -ls $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M}/*/ -# synthetic_ct.nii.gz input_mask.nii.gz host_ct.nii.gz qc/*.png nodmaisi_audit.json -find $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M} -name synthetic_ct.nii.gz | wc -l -``` - ---- - -## 5. Run size — demo vs paper/production run - -**What ships is a quick demo (small numbers), not the paper run.** Run size lives in each -mode's **trials `.sub`** (`infra/slurm/trials/mode_*.sub`). The paper value is commented -right above the active demo value, e.g.: - -```bash -# infra/slurm/trials/mode1_controlled_prevalence.sub -# N_CASES=1000 # paper run (commented for 5-case demo) ← restore this -N_CASES=5 # demo -``` - -### Demo vs paper values, and exactly what to edit - -For modes 1–10, edit the variable in the named file. The "paper run" column is the -original production configuration. - -| Mode | File (`infra/slurm/trials/…`) | Variable(s) | Demo | **Paper run** | -|------|------------------------------|-------------|------|---------------| -| 1 Controlled prevalence | `mode1_controlled_prevalence.sub` | `N_CASES` | 5 | **1000** | -| 2 Size detection curve | `mode2_size_detection_curve.sub` | `N_PER_BUCKET` | 5 | **100** (×6 buckets) | -| 3 Location sensitivity | `mode3_location_sensitivity.sub` | `N_PER_LOBE` | 5 | **100** (×5 lobes) | -| 4 Demographic strat. | `mode4_demographic_stratification.sub` | `N_PER_STRATUM` | 5 | **200** (×~4 strata) | -| 5 Counterfactual | `mode5_counterfactual.sub` | `N_CASES` (per variant) | 5 | **500** | -| 6 Cross-dataset | `mode6_cross_dataset.sub` | `N_CASES` (per dataset) | 5 | **300** | -| 7 Bootstrap confidence | `mode7_bootstrap_confidence.sub` | `N_CASES`, `N_BOOTSTRAP` | 5, 3 | **200, 20** | -| 8 Algorithm comparison | `mode8_algorithm_comparison.sub` | `N_CASES` | 5 | **500** | -| 9 Screening simulation | `mode9_screening_simulation.sub` | `N_CASES_PER_ROUND` (`N_ROUNDS`=3) | 5 | **500** | -| 10 Multi-nodule realism | `mode10_multi_nodule_realism.sub` | `N_CASES` (`MULTI_NODULE_FRACTION`=0.25) | 5 | **500** | - -For the digital-twin modes 11–13, the demo restricts datasets and caps patients/nodules; -the paper run enumerates **all 7 datasets** with no caps: - -| Mode | File | Demo | **Paper run** (restore) | -|------|------|------|--------------------------| -| 11 Isolation | `mode11_digital_twin_isolation.sub` | `DATASETS=("DLCS24")`; `--max-patients 5 --max-nodules-per-patient 1` | `DATASETS=(all 7)`; `--all-patients` (≈13k cases) | -| 12 Complete | `mode12_digital_twin_complete.sub` | `DATASETS=("DLCS24")`; `--max-patients 5` | `DATASETS=(all 7)`; `--all-patients` (≈8k cases) | -| 13 Cross | `mode13_digital_twin_cross.sub` | `HOST=("DLCS24") DONOR=("LUNA25")`; `--max-host-patients 5`; `MAX_DONOR_NODULES=5` | `HOST/DONOR=(all 7)`; `--all-host-patients --all-donor-patients`; `MAX_DONOR_NODULES=250` (≈79k cases) | - -In each `.sub` the paper values are present as commented lines (`# … # paper run`) / -the full `DATASETS=(…)` arrays — uncomment them and comment out the demo lines. - -### Quicker: override without editing files (optional) - -If the count variables are exposed as `${VAR:-default}` (ask the maintainers / see the -`.sub`), you can override per submission instead of editing: - -```bash -N_CASES=1000 infra/slurm/run_pipeline.sh 1 trials -N_PER_BUCKET=100 infra/slurm/run_pipeline.sh 2 trials -MAX_DONOR_NODULES=250 infra/slurm/run_pipeline.sh 13 trials -``` - -> **Heads-up:** the paper run is large (mode 13 alone ≈ 79k cases) and the synthesis stage -> is GPU-bound (~1.5–3 min/case). Scale up deliberately and use the array/chunking in the -> SLURM scripts. - ---- - -## 6. Monitoring - -```bash -squeue -u $USER # queue -sacct -u $USER -S today --format=JobID,JobName%22,State,Elapsed,ExitCode -tail -f logs/_.out # live log -``` -Logs are written to `logs/` in the repo (gitignored; kept via `.gitkeep`). - ---- - -## 7. Verified smoke-test result (reference) - -All 13 modes were run end-to-end at the smoke size in the `itrialspace` env on an A6000: - -| Stage | Modes 1–10 | Modes 11/12/13 | -|-------|-----------|----------------| -| Trials | 10/10 manifests | 5 / 7 / 5 rows | -| Insertion | 35/35 tasks, masks + audits | 5 masks each | -| Synthesis | 50 synthetic CTs (5/mode) | 5 CTs each | - -> **Mode 10 note:** it is the only mode that creates **two sub-cohorts** (75% -> single-nodule + 25% multi-nodule). At 5 cases that's 4 single + 1 multi, so it has two -> `audit.json` files; synthesize **both** to get all 5 CTs (the helper in §1 and the loop -> in §4 do this automatically). - ---- - -## 8. Troubleshooting - -| Symptom | Cause / fix | -|---------|-------------| -| Job "COMPLETED" in 0s but no output | Submitted from outside the repo root, or `logs/` missing → `env.sh` not found. Submit from repo root. | -| `env.sh: No such file or directory` | SLURM copies the script to a spool dir; the scripts locate `env.sh` by walking up from `$SLURM_SUBMIT_DIR` — submit from the repo (or a subdir of it). | -| `ModuleNotFoundError` (torch/pytest/…) | The env is shadowed by `~/.local`. Jobs set `PYTHONNOUSERSITE=1` automatically; for manual runs, prefix `PYTHONNOUSERSITE=1`. | -| `CUDNN_STATUS_NOT_INITIALIZED` / `libcudnn.so.9 not found` | torch's pip CUDA libs not on the loader path → handled by `env.sh`. If you rebuilt the env, ensure only the `*-cu12` nvidia packages are installed (no stray `*-cu13`). | -| Synthesis: "No cases found" | The case list must contain **mask-filename stems**, not the audit's integer `case_id`. Use `infra/slurm/_gen_caselist.py`. | -| Wrong env activated | Set `ITRIALSPACE_CONDA_ENV` in `.env`. | - -See also: [walkthrough_mode1.md](walkthrough_mode1.md) (narrated single-mode walkthrough), -[configuration.md](configuration.md), [installation.md](installation.md), -[infra/slurm/README.md](../infra/slurm/README.md). diff --git a/itrialspace/docs/trial_modes.md b/itrialspace/docs/trial_modes.md deleted file mode 100644 index f237c99d9df5e3b249251a55ae0b207644fc9446..0000000000000000000000000000000000000000 --- a/itrialspace/docs/trial_modes.md +++ /dev/null @@ -1,31 +0,0 @@ -# Trial modes - -`its-trials --mode ` generates cohort manifests. The 13 modes: - -| # | Mode name | Purpose | -|---|-----------|---------| -| 1 | `controlled_prevalence` | Vary cancer prevalence | -| 2 | `size_detection_curve` | Detection sensitivity by nodule size (FROC) | -| 3 | `location_sensitivity` | Detection by anatomical location (lobe) | -| 4 | `demographic_stratification` | Performance across demographics | -| 5 | `counterfactual` | Same patient ± nodule | -| 6 | `cross_dataset` | Cross-dataset generalization | -| 7 | `bootstrap_confidence` | Statistical confidence intervals | -| 8 | `algorithm_comparison` | Standardized CADx evaluation | -| 9 | `screening_simulation` | Multi-round with prevalence decay | -| 10 | `multi_nodule` | Multi-nodule context impact (companions) | -| 11 | `digital_twin_isolation` | Per-nodule isolation within host anatomy | -| 12 | `digital_twin_complete` | All native nodules per CT scan | -| 13 | `digital_twin_cross` | Cross-patient host anatomy + donor nodules | - -Modes 11–13 (digital twins) match at the **CT-scan level** (`host_ct_path == -donor_ct_path`), enabling task-level fidelity comparison of AI on real vs. synthetic -versions of the same anatomy. - -```bash -its-trials --mode size_detection_curve --n-per-bucket 100 \ - --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode2" -its-trials --help # all per-mode options -``` - -Full specification: [reference/03_TRIAL_MODES.md](reference/03_TRIAL_MODES.md). diff --git a/itrialspace/docs/walkthrough_mode1.md b/itrialspace/docs/walkthrough_mode1.md deleted file mode 100644 index b48bd8427cce41f895a7622340b33615cc7ff083..0000000000000000000000000000000000000000 --- a/itrialspace/docs/walkthrough_mode1.md +++ /dev/null @@ -1,168 +0,0 @@ -# Walkthrough: 200 cases through Mode 1 (end-to-end) - -This tutorial takes **Mode 1 (`controlled_prevalence`)** from a cohort specification all -the way to synthetic CT volumes, for **200 cases**: - -``` -its-trials ──▶ manifest CSV ──▶ its-insert ──▶ inserted masks + audit.json ──▶ synthesis ──▶ synthetic CTs - (1) plan (cohort) (2) insert (label-23 combined masks) (3) generate (+ QC) -``` - -## 0. One-time setup - -```bash -cd /path/to/itrialspace -conda activate itrialspace # or your env with the deps installed -pip install -e ".[imaging]" # core + NIfTI/scipy/SimpleITK - -# Tell iTrialSpace where the data lives (the 7 datasets, host CTs, organ segs) -export ITRIALSPACE_DATA_DIR=/scratch/railabs/ft42/VLST_Project/Data/iTrialSpace -# Where outputs go (defaults to ITRIALSPACE_DATA_DIR if unset) -export ITRIALSPACE_OUTPUT_DIR=$ITRIALSPACE_DATA_DIR - -its config # sanity-check the resolved paths -``` - -> Tip: put these in a `.env` (copy `.env.example`); the SLURM scripts and config -> loaders pick it up automatically. - ---- - -## Step 1 — Plan the cohort (itrialspace → manifest) - -`its-trials` runs the trial-mode factory, builds the cohort with `CohortBuilder`, and -writes a manifest (CSV + JSON). - -```bash -its-trials \ - --mode controlled_prevalence \ - --n-cases 200 \ - --prevalence 0.05 \ - --template NLST \ - --seed 42 \ - --output-dir $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence -``` - -**Produces** (filename derives from the template, e.g. `NLST_cohort.csv`): - -``` -$ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/ -├── NLST_cohort.csv # 200 rows — one per case (host CT + donor nodule + placement) -├── NLST_cohort.json # same content, structured -└── _run_config.json # exact parameters used (reproducibility) -``` - -Each manifest row carries the host CT path, host organ segmentation, the donor nodule, and -the target placement (lobe / percentile / scale). Verify: - -```bash -python -c "import pandas as pd; d=pd.read_csv('$ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/NLST_cohort.csv'); print(len(d),'cases'); print(d['host_dataset'].value_counts())" -``` - -Useful options: `--no-verify-paths` (skip on-disk path checks for a quick dry plan), -`--n-cases`, `--prevalence`. See `its-trials --help`. - ---- - -## Step 2 — Insert nodule masks (manifest → inserted masks) - -`its-insert run` reads the manifest, resolves host organ-segmentation volumes, and pastes -each donor nodule mask at **VISTA3D label 23** using the 5-stage placement pipeline (lobe -targeting → percentile→voxel → snap-to-mask → pleural safety → collision avoidance). -**Mask-only — no CT intensities are touched here.** - -```bash -its-insert run \ - --manifest $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/NLST_cohort.csv \ - --output-dir $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence \ - --trial-name mode1_controlled_prevalence \ - --seed 42 \ - --n-jobs 8 -``` - -**Produces:** - -``` -$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence/ -├── iTS--mode1...--C0000--host-...--src-...--nod-..._mask.nii.gz # combined label map per case -├── ... (200 masks) -└── audit.json # per-case provenance (placement, snap, pleural dist, overlap) — KEY for step 3 -``` - -- **Dry run first** (placement decisions only, nothing written): - `its-insert run --manifest ... --output-dir ... --dry-run` -- Verify a finished run: `its-insert verify --output-dir $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence` - ---- - -## Step 3 — Generate CTs (inserted masks → synthetic CT) - -This runs **NodMAISI** (ControlNet-conditioned rectified-flow diffusion). It **needs a -GPU**, the `synthesis` extra, and the model weights. - -```bash -pip install -e ".[synthesis]" -# torch matching your CUDA (example: cu124) — see docs/installation.md -pip install torch --index-url https://download.pytorch.org/whl/cu124 - -# Point at the NodMAISI weights (autoencoder.pt, diffusion_unet.pt, controlnet *.pt) -export NODMAISI_MODELS_DIR=/path/to/nodmaisi/models -``` - -Run the integration bridge. The `audit.json` from Step 2 is the preferred input (it links -each mask back to its host CT for the QC overlay): - -```bash -python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ - --audit $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence/audit.json \ - --config configs/integration.example.yaml \ - --outdir $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1_controlled_prevalence \ - --jobs 1 -``` - -(If you don't have the audit, use `--mask-root $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence` instead.) - -**Produces, per case:** - -``` -$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1_controlled_prevalence// -├── synthetic_ct.nii.gz # generated CT volume -├── input_mask.nii.gz # mask fed to the model (snapped to a valid grid) -├── host_ct.nii.gz # symlink to host CT (for comparison) -├── qc/qc_slice_*.png # 3-panel QC (host | synthetic+overlay | synthetic) -└── nodmaisi_audit.json # params, geometry, sanity checks, timing -``` - -Validate without a GPU first: add `--dry-run` (checks inputs/geometry, skips inference). - ---- - -## Running it on HPC (recommended for 200 cases) - -Each stage has SLURM scripts under `infra/slurm/`, cluster-portable via `infra/slurm/env.sh` -(set `ITRIALSPACE_DATA_DIR`, `ITRIALSPACE_CONDA_ENV`, partitions in your `.env`): - -```bash -# 1. plan -sbatch infra/slurm/trials/mode1_controlled_prevalence.sub -# 2. insert (CPU array job) -sbatch infra/slurm/mask_inserter/mode1_insert_masks.sub -# 3. synthesize (GPU array job; chunks automatically if >1000 cases) -infra/slurm/synthesis/submit_array_jobs.sh 1 -``` - -> Edit the `#SBATCH --partition/--account` lines for your cluster (see -> [infra/slurm/README.md](../infra/slurm/README.md)). - ---- - -## What "200 cases" means at each stage - -| Stage | Input | Output | Needs | -|-------|-------|--------|-------| -| 1. Plan | dataset index | 200-row manifest CSV/JSON | CPU, profile CSVs | -| 2. Insert | manifest + host organ segs | 200 label-23 masks + `audit.json` | CPU, host CTs/segs | -| 3. Generate | masks (+ audit) | 200 synthetic CTs + QC | **GPU + NodMAISI weights** | - -After Step 3 you can feed the synthetic CTs into evaluation — VLM -(`itrialspace.evaluation.vlm_eval`) or the optional CADe/CADx extras. diff --git a/itrialspace/environment.lock.yml b/itrialspace/environment.lock.yml deleted file mode 100644 index a9f299d0bdb607280159cc5a0397563acac066c8..0000000000000000000000000000000000000000 --- a/itrialspace/environment.lock.yml +++ /dev/null @@ -1,18 +0,0 @@ -# Exact clone of the original development environment. -# Reproduces Python 3.10.13 + the full pinned package set (linux-64, CUDA 12.1), -# including torch 2.4.1+cu121 and the git-pinned MONAI build. -# -# conda env create -f environment.lock.yml -# conda activate itrialspace -# -# This is the "give me exactly what worked" option. For a lighter, less pinned -# setup use environment.yml instead. See docs/installation.md. -name: itrialspace -channels: - - conda-forge -dependencies: - - python=3.10.13 - - pip - - pip: - - -r requirements.lock.txt - - -e . diff --git a/itrialspace/environment.yml b/itrialspace/environment.yml deleted file mode 100644 index 5cb9c5816323fe45994faee367618f4718ab756b..0000000000000000000000000000000000000000 --- a/itrialspace/environment.yml +++ /dev/null @@ -1,30 +0,0 @@ -# Conda environment for iTrialSpace — matches the development environment versions. -# -# conda env create -f environment.yml -# conda activate itrialspace -# -# IMPORTANT: install everything in ONE pip resolution (this file does). Do NOT follow -# up with extra unpinned `pip install`s — the `>=` extras would drift to latest and -# bump torch/transformers/monai. For an exact freeze, see requirements.lock.txt. -# -# Verified versions: Python 3.10, torch 2.4.1+cu121, torchvision 0.19.1+cu121, -# transformers 4.51.3, open_clip 2.32.0, MONAI (git dev commit), numpy 1.26.4. -# CUDA 12.1 build of torch — adjust the index URL to match your driver if needed. -name: itrialspace -channels: - - conda-forge -dependencies: - - python=3.10 - - pip>=23 - - pip: - - --extra-index-url https://download.pytorch.org/whl/cu121 - # Behavior-critical pins (match the dev env exactly) - - numpy==1.26.4 - - torch==2.4.1 - - torchvision==0.19.1 - - transformers==4.51.3 - - open_clip_torch==2.32.0 - - seaborn>=0.12 - - monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a - # The package with all in-repo extras (deps resolve around the pins above) - - -e .[imaging,apps,synthesis,vlm,dev] diff --git a/itrialspace/infra/slurm/README.md b/itrialspace/infra/slurm/README.md deleted file mode 100644 index 208e0b35c85dc41b933867ae1b6222cd117d1173..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# SLURM job scripts - -HPC submission scripts for every stage of the iTrialSpace pipeline. They are -**cluster-portable**: paths, the conda environment, and partitions come from -environment variables (with sane defaults) rather than being hardcoded. - -## How portability works - -Every script sources [`env.sh`](env.sh) near the top: - -```bash -source "$(dirname "$0")/../env.sh" # sets PROJ_DIR, ITRIALSPACE_DATA_DIR, CONDA_ENV, ... -itrialspace_activate_conda # activates the conda env portably -``` - -`env.sh` resolves (overridable via your shell or a repo-root `.env`): - -| Variable | Default | Meaning | -|----------|---------|---------| -| `PROJ_DIR` | auto (repo root) | iTrialSpace checkout | -| `ITRIALSPACE_DATA_DIR` | `~/.itrialspace/data` | unified data layout | -| `ITRIALSPACE_OUTPUT_DIR` | `=DATA_DIR` | generated artifacts | -| `ITRIALSPACE_CONDA_ENV` | `itrialspace` | conda env name | -| `CONDA_PROFILE` | auto-detected | path to `conda.sh` | -| `SLURM_PARTITION_GPU` / `SLURM_PARTITION_CPU` | `gpu` / `cpu` | partitions | - -## Adapting to a new cluster - -1. Set the variables above in your `.env` (copy `.env.example`) or shell profile. -2. **Edit the `#SBATCH` directives** in the scripts you use — partition names - (`--partition`), account (`--account`), GPU type, walltime, and memory are - cluster-specific and cannot be set from environment variables (SLURM parses - `#SBATCH` lines before the shell runs). Search-and-replace the partition names - for your site. -3. Submit from the repo root, e.g. `sbatch infra/slurm/nodulemap/nodulemap.sub`. - -## Layout - -| Directory | Stage | -|-----------|-------| -| `trials/` | Generate cohort manifests (13 modes) | -| `mask_inserter/` | Insert nodule masks into host CTs | -| `synthesis/` | NodMAISI CT synthesis (needs model weights — see docs) | -| `nodulemap/` · `retriever/` | Launch interactive web tools | -| `vlm_eval/` | Vision-language model evaluation | -| `detection_inference/` · `cade_synthetic_eval/` · `cadx_*` | **Optional** CADe/CADx eval — require external models (see `docs/evaluation_external_dependencies.md`) | - -> Logs are written to `logs/` (gitignored). Create it first or let the scripts `mkdir -p logs`. diff --git a/itrialspace/infra/slurm/_gen_caselist.py b/itrialspace/infra/slurm/_gen_caselist.py deleted file mode 100644 index 7c9ea2d1301d96b4f246b5efde0057ee7b5c3e32..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/_gen_caselist.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python3 -"""Write a synthesis case list (mask-filename stems) from an insertion audit.json. - -The synthesis runner matches --case-ids against the mask-filename stem (NOT the -audit's integer case_id), so the case list must contain those stems. - -Usage: python _gen_caselist.py # prints N cases -""" -import json -import os -import sys - - -def stem(path: str) -> str: - name = os.path.basename(path) - for suffix in ("_mask.nii.gz", ".nii.gz"): - if name.endswith(suffix): - return name[: -len(suffix)] - return name - - -def main() -> None: - audit, out = sys.argv[1], sys.argv[2] - data = json.load(open(audit)) - recs = data.get("records", data.get("cases", [])) - cases = sorted( - {stem(r["output_combined_path"]) for r in recs - if r.get("status") == "success" and r.get("output_combined_path")} - ) - os.makedirs(os.path.dirname(out) or ".", exist_ok=True) - with open(out, "w") as f: - f.write("\n".join(cases) + "\n") - print(len(cases)) - - -if __name__ == "__main__": - main() diff --git a/itrialspace/infra/slurm/env.sh b/itrialspace/infra/slurm/env.sh deleted file mode 100644 index 536dc61899f7893808aec6664344d8e46b29ac6e..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/env.sh +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env bash -# Shared environment for all iTrialSpace SLURM scripts. -# -# Every .sub script sources this file instead of hardcoding paths or the conda env: -# -# source "$(dirname "${BASH_SOURCE[0]}")/../env.sh" -# -# Override any value by exporting it before submitting, or by editing this file / -# a local copy. Nothing here is host-specific by default — set the variables for -# your cluster in your shell profile or a `.env` next to the repo. - -# ── Repo root (auto-detected: this file lives at /infra/slurm/env.sh) ── -_ENV_SH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -export PROJ_DIR="${PROJ_DIR:-$(cd "${_ENV_SH_DIR}/../.." && pwd)}" - -# Load a repo-local .env for defaults. Precedence: variables already set in the -# environment (shell export, or `VAR=x sbatch ...`) WIN over .env, which in turn -# wins over the built-in defaults below. So a per-job override works: -# ITRIALSPACE_OUTPUT_DIR=/somewhere sbatch infra/slurm/trials/mode1_*.sub -if [[ -f "${PROJ_DIR}/.env" ]]; then - while IFS= read -r _line || [[ -n "${_line}" ]]; do - case "${_line}" in ''|\#*) continue ;; esac # skip blanks/comments - _key="${_line%%=*}" - [[ "${_key}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue - if [[ -z "${!_key+x}" ]]; then # only if not already set - export "${_key}=$(eval "printf '%s' \"${_line#*=}\"")" - fi - done < "${PROJ_DIR}/.env" - unset _line _key -fi - -# ── Data root (unified layout: raw_ct/ masks/ profiles/ ...) ──────────────── -export ITRIALSPACE_DATA_DIR="${ITRIALSPACE_DATA_DIR:-${HOME}/.itrialspace/data}" -export DATA_BASE="${DATA_BASE:-${ITRIALSPACE_DATA_DIR}}" -# Output root defaults to the data root — computed AFTER .env so it follows it. -export ITRIALSPACE_OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR:-${ITRIALSPACE_DATA_DIR}}" - -# ── Conda environment ─────────────────────────────────────────────────────── -export ITRIALSPACE_CONDA_ENV="${ITRIALSPACE_CONDA_ENV:-itrialspace}" -# Isolate from ~/.local user-site packages so the conda env is authoritative -# (avoids shadowing the env's torch/pytest/etc. with stale user-site copies). -export PYTHONNOUSERSITE="${PYTHONNOUSERSITE:-1}" -# Path to your conda profile script (cluster-specific). Common locations tried below. -export CONDA_PROFILE="${CONDA_PROFILE:-}" - -# ── SLURM partitions / account (override per cluster) ─────────────────────── -export SLURM_PARTITION_GPU="${SLURM_PARTITION_GPU:-gpu}" -export SLURM_PARTITION_CPU="${SLURM_PARTITION_CPU:-cpu}" -export SLURM_ACCOUNT="${SLURM_ACCOUNT:-}" - -# ── Make the package importable ───────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}/src:${PYTHONPATH:-}" - -# ── Helper: activate the conda env portably ───────────────────────────────── -itrialspace_activate_conda() { - local profile="${CONDA_PROFILE}" - if [[ -z "${profile}" ]]; then - for cand in \ - "/cm/shared/apps/miniconda/etc/profile.d/conda.sh" \ - "${HOME}/miniconda3/etc/profile.d/conda.sh" \ - "${HOME}/anaconda3/etc/profile.d/conda.sh" \ - "/opt/conda/etc/profile.d/conda.sh"; do - [[ -f "${cand}" ]] && profile="${cand}" && break - done - fi - if [[ -n "${profile}" && -f "${profile}" ]]; then - # shellcheck disable=SC1090 - source "${profile}" - conda activate "${ITRIALSPACE_CONDA_ENV}" - else - echo "WARNING: conda profile not found; set CONDA_PROFILE. Continuing without activation." >&2 - fi - # torch's pip-installed CUDA libs (cuDNN etc.) aren't auto-found in a clean env → - # put every nvidia/*/lib on LD_LIBRARY_PATH (otherwise: "libcudnn.so.9 not found" / - # CUDNN_STATUS_NOT_INITIALIZED). - if [[ -n "${CONDA_PREFIX:-}" ]]; then - local _d - for _d in "${CONDA_PREFIX}"/lib/python*/site-packages/nvidia/*/lib; do - [[ -d "${_d}" ]] && export LD_LIBRARY_PATH="${_d}:${LD_LIBRARY_PATH:-}" - done - fi -} - -# Run from the repo root and ensure the log directory exists. (The `#SBATCH -# --output=logs/...` path is opened by SLURM *before* this runs, so also keep a -# committed logs/ dir and submit from the repo root — see infra/slurm/README.md.) -cd "${PROJ_DIR}" 2>/dev/null || true -mkdir -p "${PROJ_DIR}/logs" diff --git a/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub deleted file mode 100644 index 8571e131eba2e021fc6c090299c100af6be4aea0..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 10: Multi-Nodule Realism Study — Mask Insertion -# -# Inserts donor nodule masks for multi-nodule realism study manifests. -# Mode 10 produces 2 manifests (single-nodule and multi-nodule sub-cohorts). -# Consider the array variant for batch processing across sub-cohorts. -# -# Usage: -# MANIFEST_PATH=.../multi_nodule_study_single.csv sbatch mode10_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M10_MultiNod -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode10_multi_nodule_realism_%j.out -#SBATCH --error=logs/insert_mode10_multi_nodule_realism_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode10_multi_nodule_realism" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/multi_nodule_study_single.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 10: Multi-Nodule Realism Study" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub deleted file mode 100644 index 0ecb9947dc532db9827953e55b137bb9c486add5..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub +++ /dev/null @@ -1,101 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 10: Multi-Nodule Realism Study — Array Job (one per sub-cohort) -# -# Mode 10 produces 2 manifests (single-nodule and multi-nodule sub-cohorts). -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode10_multi_nodule_realism \ -# --output manifests_mode10.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode10.txt) - 1 )) \ -# mode10_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M10_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode10_multi_nodule_realism_%A_%a.out -#SBATCH --error=logs/insert_mode10_multi_nodule_realism_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode10_multi_nodule_realism" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode10.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 10: Multi-Nodule Realism (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub deleted file mode 100644 index 34785a6f34052fb43556ec99fc8ac80cd1cf2681..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 11: Digital Twin Isolation — Mask Insertion -# -# Inserts one native nodule mask per isolation case. Each row in the manifest -# represents a single nodule placed into the host patient's own anatomy. -# Because each case is a single nodule insertion the per-row cost is low, -# but the total number of rows can be large (one per nodule per patient). -# -# Usage: -# MANIFEST_PATH=.../digital_twin_isolation_DLCS24.csv sbatch mode11_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M11_DTiso -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode11_digital_twin_isolation_%j.out -#SBATCH --error=logs/insert_mode11_digital_twin_isolation_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode11_digital_twin_isolation" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_isolation_DLCS24.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 11: Digital Twin Isolation" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub deleted file mode 100644 index c61350ede463769460e061a68d1ca0e509616bc1..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub +++ /dev/null @@ -1,103 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 11: Digital Twin Isolation — Array Job (one per manifest chunk) -# -# When all_patients=True the isolation manifest can be large (one row per -# nodule per patient). Use the list_manifests tool to split into chunks, -# then submit an array job so each chunk runs on a separate SLURM task. -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode11_digital_twin_isolation \ -# --output manifests_mode11.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode11.txt) - 1 )) \ -# mode11_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M11_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode11_digital_twin_isolation_%A_%a.out -#SBATCH --error=logs/insert_mode11_digital_twin_isolation_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode11_digital_twin_isolation" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode11.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 11: Digital Twin Isolation (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub deleted file mode 100644 index b32c8f735cc5b177626f62deeaaf5490f4dd8b07..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 12: Digital Twin Complete — Mask Insertion -# -# Inserts ALL native nodule masks per patient into one combined conditioning -# mask. Each case has multiple manifest rows sharing a case_id; the inserter -# processes them sequentially and merges with label value 23. -# -# Usage: -# MANIFEST_PATH=.../digital_twin_complete_DLCS24.csv sbatch mode12_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M12_DTcomp -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode12_digital_twin_complete_%j.out -#SBATCH --error=logs/insert_mode12_digital_twin_complete_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode12_digital_twin_complete" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_complete_DLCS24.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 12: Digital Twin Complete" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub deleted file mode 100644 index 8d42abce9c08ebb815a4f718b9cc8706fe4b5abc..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub +++ /dev/null @@ -1,102 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 12: Digital Twin Complete — Array Job (one per manifest chunk) -# -# When all_patients=True the complete manifest can be large. -# Use the list_manifests tool to split into chunks, then submit an array job. -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode12_digital_twin_complete \ -# --output manifests_mode12.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode12.txt) - 1 )) \ -# mode12_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M12_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode12_digital_twin_complete_%A_%a.out -#SBATCH --error=logs/insert_mode12_digital_twin_complete_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode12_digital_twin_complete" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode12.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 12: Digital Twin Complete (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub deleted file mode 100644 index fb8e317b1c9303808b486c310d5f8bf97cb81e05..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 13: Digital Twin Cross — Mask Insertion -# -# Inserts donor nodule masks from a DIFFERENT patient (possibly a different -# dataset) into the host patient anatomy. The manifest contains separate -# host and donor paths; the inserter reads them directly. -# -# Usage: -# MANIFEST_PATH=.../digital_twin_cross_DLCS24_x_LUNA25.csv sbatch mode13_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M13_DTcross -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode13_digital_twin_cross_%j.out -#SBATCH --error=logs/insert_mode13_digital_twin_cross_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode13_digital_twin_cross" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_cross_DLCS24_x_LUNA25.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 13: Digital Twin Cross" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub deleted file mode 100644 index c0497691f487eb9e717a7fbb2cd7e3184c78534a..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub +++ /dev/null @@ -1,103 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 13: Digital Twin Cross — Array Job (one per manifest chunk) -# -# Cross-patient insertion may produce many manifests (one per host×donor -# dataset combination). Use the list_manifests tool to split into chunks, -# then submit an array job. -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode13_digital_twin_cross \ -# --output manifests_mode13.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode13.txt) - 1 )) \ -# mode13_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M13_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=2-00:00:00 -#SBATCH --output=logs/insert_mode13_digital_twin_cross_%A_%a.out -#SBATCH --error=logs/insert_mode13_digital_twin_cross_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode13_digital_twin_cross" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode13.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 13: Digital Twin Cross (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub deleted file mode 100644 index 2dffd2e8bc29d728898309dee77fb417d784ba2d..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 1: Controlled Prevalence — Mask Insertion -# -# Inserts donor nodule masks into host CTs for the controlled-prevalence -# cohort manifest (single manifest with fixed malignancy prevalence). -# -# Usage: -# sbatch mode1_insert_masks.sub -# sbatch --mem=64G --time=08:00:00 mode1_insert_masks.sub # override -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M1_Prev -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=08:00:00 -#SBATCH --output=logs/insert_mode1_controlled_prevalence_%j.out -#SBATCH --error=logs/insert_mode1_controlled_prevalence_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -# ── Site-specific paths (edit these) ───────────────────────────────────────── -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -# ── Mode configuration ─────────────────────────────────────────────────────── -TRIAL_MODE="mode1_controlled_prevalence" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/NLST_cohort.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -# ── Banner ──────────────────────────────────────────────────────────────────── -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 1: Controlled Prevalence" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " CONFIG_PATH : ${CONFIG_PATH}" -echo " N_JOBS : ${N_JOBS}" -echo " DRY_RUN : ${DRY_RUN}" -echo "" - -# ── Environment ────────────────────────────────────────────────────────────── -cd "${PROJECT_DIR}" - -# ── Validate ───────────────────────────────────────────────────────────────── -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -# Resolve config path (falls back to the package's bundled defaults.yaml if unset) -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -# ── Run ────────────────────────────────────────────────────────────────────── -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? - -echo "" -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub deleted file mode 100644 index 9b60c0a65230c3e4dd79e792d59616478c185203..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub +++ /dev/null @@ -1,108 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 1: Controlled Prevalence — Array Job (multiple manifests) -# -# Reads a manifest list file and processes one manifest per array task. -# -# Usage: -# # 1. Generate the manifest list: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode1_controlled_prevalence \ -# --output manifests_mode1.txt -# -# # 2. Submit array job (N = number of manifests - 1): -# sbatch --array=0-$(( $(wc -l < manifests_mode1.txt) - 1 )) \ -# mode1_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M1_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode1_controlled_prevalence_%A_%a.out -#SBATCH --error=logs/insert_mode1_controlled_prevalence_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -# ── Site-specific paths ────────────────────────────────────────────────────── -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode1_controlled_prevalence" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode1.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -# ── Resolve manifest for this array task ───────────────────────────────────── -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -# Derive a unique output subdirectory from the manifest filename -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 1: Controlled Prevalence (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks.sub deleted file mode 100644 index bf586aeeeb074b4a6bf1929844a8e6d02e6c8a5e..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks.sub +++ /dev/null @@ -1,87 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 2: Size Detection Curve — Mask Insertion -# -# Inserts donor nodule masks for the size-stratified FROC cohorts. -# Mode 2 produces multiple manifests (one per size bucket), so consider -# using the array job variant (mode2_insert_masks_array.sub) instead. -# -# This script processes a single manifest. Override MANIFEST_PATH to select -# the specific size bucket manifest. -# -# Usage: -# MANIFEST_PATH=.../size_5_10mm.csv sbatch mode2_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M2_Size -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=1-00:00:00 -#SBATCH --output=logs/insert_mode2_size_detection_curve_%j.out -#SBATCH --error=logs/insert_mode2_size_detection_curve_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode2_size_detection_curve" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/size_curve_5-10mm.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 2: Size Detection Curve" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks_array.sub deleted file mode 100644 index b4c9f8162b276472306a6a4e90e861298c67fc3b..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks_array.sub +++ /dev/null @@ -1,102 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 2: Size Detection Curve — Array Job (one manifest per size bucket) -# -# Reads a manifest list file and processes one manifest per array task. -# Ideal for Mode 2 which produces ~6 size-bucket manifests. -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode2_size_detection_curve \ -# --output manifests_mode2.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode2.txt) - 1 )) \ -# mode2_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M2_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=1-00:00:00 -#SBATCH --output=logs/insert_mode2_size_detection_curve_%A_%a.out -#SBATCH --error=logs/insert_mode2_size_detection_curve_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode2_size_detection_curve" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode2.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 2: Size Detection Curve (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks.sub deleted file mode 100644 index 763944e56760a9d738f82b17d2b258ece8fcbb90..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 3: Location Sensitivity — Mask Insertion -# -# Inserts donor nodule masks for lobe-stratified cohorts. -# Mode 3 produces one manifest per lobe (5 lobes), so consider the -# array job variant (mode3_insert_masks_array.sub) for batch processing. -# -# Usage: -# MANIFEST_PATH=.../lobe_RUL.csv sbatch mode3_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M3_Loc -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=1-00:00:00 -#SBATCH --output=logs/insert_mode3_location_sensitivity_%j.out -#SBATCH --error=logs/insert_mode3_location_sensitivity_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode3_location_sensitivity" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/lobe_right_lung_upper_lobe.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 3: Location Sensitivity" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks_array.sub deleted file mode 100644 index 2169dccc8819d56fc895a2cc4560d37db72cb449..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks_array.sub +++ /dev/null @@ -1,101 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 3: Location Sensitivity — Array Job (one manifest per lobe) -# -# Ideal for Mode 3 which produces ~5 lobe-stratified manifests. -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode3_location_sensitivity \ -# --output manifests_mode3.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode3.txt) - 1 )) \ -# mode3_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M3_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=1-00:00:00 -#SBATCH --output=logs/insert_mode3_location_sensitivity_%A_%a.out -#SBATCH --error=logs/insert_mode3_location_sensitivity_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode3_location_sensitivity" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode3.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 3: Location Sensitivity (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks.sub deleted file mode 100644 index 15a9bdd059c74e8023919b4f0b0cd93c49bcac82..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 4: Demographic Stratification — Mask Insertion -# -# Inserts donor nodule masks for demographic-stratified cohorts. -# Mode 4 may produce multiple manifests (one per demographic stratum). -# Consider the array variant for batch processing. -# -# Usage: -# sbatch mode4_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M4_Demo -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode4_demographic_stratification_%j.out -#SBATCH --error=logs/insert_mode4_demographic_stratification_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode4_demographic_stratification" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/demo_stratum_0.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 4: Demographic Stratification" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks_array.sub deleted file mode 100644 index 74ed0c10894ca3d2d55a47e147d739f4459f4e28..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks_array.sub +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 4: Demographic Stratification — Array Job (one per stratum) -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode4_demographic_stratification \ -# --output manifests_mode4.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode4.txt) - 1 )) \ -# mode4_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M4_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode4_demographic_stratification_%A_%a.out -#SBATCH --error=logs/insert_mode4_demographic_stratification_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode4_demographic_stratification" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode4.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 4: Demographic Strat (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks.sub deleted file mode 100644 index 34e3555b0e79e815cd090400a5d8d65157b49998..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 5: Counterfactual — Mask Insertion -# -# Inserts donor nodule masks for counterfactual cohorts (same cohort, -# one parameter varied). Multiple manifests may exist (one per -# counterfactual condition). Consider the array variant for batch. -# -# Usage: -# sbatch mode5_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M5_CF -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=08:00:00 -#SBATCH --output=logs/insert_mode5_counterfactual_%j.out -#SBATCH --error=logs/insert_mode5_counterfactual_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode5_counterfactual" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/counterfactual_malignancy_prevalence=0.05.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 5: Counterfactual" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks_array.sub deleted file mode 100644 index a0e073e521b481d4baa87c9238784eb63461705d..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks_array.sub +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 5: Counterfactual — Array Job (one per counterfactual condition) -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode5_counterfactual \ -# --output manifests_mode5.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode5.txt) - 1 )) \ -# mode5_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M5_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode5_counterfactual_%A_%a.out -#SBATCH --error=logs/insert_mode5_counterfactual_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode5_counterfactual" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode5.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 5: Counterfactual (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks.sub deleted file mode 100644 index 114642641ef8fd109a51c5c3e254132f78a10828..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 6: Cross-Dataset — Mask Insertion -# -# Inserts donor nodule masks for cross-dataset cohorts (one cohort per -# dataset as sole donor source). Multiple manifests — consider the array -# variant for batch processing. -# -# Usage: -# sbatch mode6_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M6_XDS -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=08:00:00 -#SBATCH --output=logs/insert_mode6_cross_dataset_%j.out -#SBATCH --error=logs/insert_mode6_cross_dataset_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode6_cross_dataset" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/cross_ds_LUNA25.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 6: Cross-Dataset" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks_array.sub deleted file mode 100644 index 7298bfbc05c83fba494f532a888abf5a04396329..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks_array.sub +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 6: Cross-Dataset — Array Job (one manifest per donor dataset) -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode6_cross_dataset \ -# --output manifests_mode6.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode6.txt) - 1 )) \ -# mode6_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M6_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode6_cross_dataset_%A_%a.out -#SBATCH --error=logs/insert_mode6_cross_dataset_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode6_cross_dataset" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode6.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 6: Cross-Dataset (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks.sub deleted file mode 100644 index 08594832d93b8fe1e69821f6847b50424d9baaa4..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks.sub +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 7: Bootstrap Confidence — Mask Insertion -# -# Inserts donor nodule masks for bootstrap replicates. Mode 7 produces -# N manifests (e.g., 100 bootstrap replicates). The array job variant -# (mode7_insert_masks_array.sub) is STRONGLY recommended for this mode. -# -# This script processes a single manifest. -# -# Usage: -# MANIFEST_PATH=.../bootstrap_boot042.csv sbatch mode7_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M7_Boot -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=08:00:00 -#SBATCH --output=logs/insert_mode7_bootstrap_confidence_%j.out -#SBATCH --error=logs/insert_mode7_bootstrap_confidence_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode7_bootstrap_confidence" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/NLST_cohort_boot000.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 7: Bootstrap Confidence" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks_array.sub deleted file mode 100644 index 93e564c1f4adac7e439f617f97710f0322f2ba52..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks_array.sub +++ /dev/null @@ -1,100 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 7: Bootstrap Confidence — Array Job (one per bootstrap replicate) -# -# STRONGLY recommended for Mode 7 which typically produces 100+ replicates. -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode7_bootstrap_confidence \ -# --output manifests_mode7.txt -# sbatch --array=0-99 mode7_insert_masks_array.sub # for 100 bootstraps -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M7_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode7_bootstrap_confidence_%A_%a.out -#SBATCH --error=logs/insert_mode7_bootstrap_confidence_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode7_bootstrap_confidence" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode7.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 7: Bootstrap Confidence (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks.sub deleted file mode 100644 index 06995572fa21c94194a31c5f650ccca90ff11413..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks.sub +++ /dev/null @@ -1,83 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 8: Algorithm Comparison — Mask Insertion -# -# Inserts donor nodule masks for the standardised algorithm comparison cohort. -# Typically a single large manifest shared across multiple detection algorithms. -# -# Usage: -# sbatch mode8_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M8_Algo -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=06:00:00 -#SBATCH --output=logs/insert_mode8_algorithm_comparison_%j.out -#SBATCH --error=logs/insert_mode8_algorithm_comparison_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode8_algorithm_comparison" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/algo_comparison_NLST_500.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-16}" # More workers for the large standardised cohort -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 8: Algorithm Comparison" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks_array.sub deleted file mode 100644 index aa59beace1201d4ddc75dd46772182be7ef1f0dc..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks_array.sub +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 8: Algorithm Comparison — Array Job (multiple manifests) -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode8_algorithm_comparison \ -# --output manifests_mode8.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode8.txt) - 1 )) \ -# mode8_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M8_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=48G -#SBATCH --time=06:00:00 -#SBATCH --output=logs/insert_mode8_algorithm_comparison_%A_%a.out -#SBATCH --error=logs/insert_mode8_algorithm_comparison_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode8_algorithm_comparison" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode8.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-16}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 8: Algorithm Comparison (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks.sub deleted file mode 100644 index b5b73b63a1c06d86b4febf80abe3ec8120fa0508..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks.sub +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 9: Screening Simulation — Mask Insertion -# -# Inserts donor nodule masks for multi-round screening protocol manifests. -# Mode 9 produces one manifest per screening round (e.g., 3 rounds). -# Consider the array variant for batch processing across rounds. -# -# Usage: -# MANIFEST_PATH=.../round_1.csv sbatch mode9_insert_masks.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M9_Screen -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=08:00:00 -#SBATCH --output=logs/insert_mode9_screening_simulation_%j.out -#SBATCH --error=logs/insert_mode9_screening_simulation_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode9_screening_simulation" -MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/screening_round_1_prev=0.040.csv}" -OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 9: Screening Simulation" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " N_JOBS : ${N_JOBS}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks_array.sub deleted file mode 100644 index 5eb2702c57d4a7fff46e01403a1781fb672dad9b..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks_array.sub +++ /dev/null @@ -1,101 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Mode 9: Screening Simulation — Array Job (one per screening round) -# -# Mode 9 produces one manifest per screening round (e.g., 3 rounds). -# -# Usage: -# python itrialspace_mask_inserter/tools/list_manifests.py \ -# --dir /scratch/.../manifests/mode9_screening_simulation \ -# --output manifests_mode9.txt -# sbatch --array=0-$(( $(wc -l < manifests_mode9.txt) - 1 )) \ -# mode9_insert_masks_array.sub -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=ins_M9_arr -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_mode9_screening_simulation_%A_%a.out -#SBATCH --error=logs/insert_mode9_screening_simulation_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" -PROJECT_DIR="${PROJ_DIR}" - -TRIAL_MODE="mode9_screening_simulation" -MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode9.txt}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -DRY_RUN="${DRY_RUN:-false}" -SEED="${SEED:-42}" - -if [ ! -f "${MANIFEST_LIST}" ]; then - echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" - exit 1 -fi - -TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" -MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") - -if [ -z "${MANIFEST_PATH}" ]; then - echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" - exit 1 -fi - -MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" -MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" -OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Mode 9: Screening Simulation (Array)" -echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -cd "${PROJECT_DIR}" - -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found: ${MANIFEST_PATH}" - exit 1 -fi -mkdir -p "${OUT_DIR}" - -CFG_ARG="" -if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" -elif [ -f "${CONFIG_PATH}" ]; then - CFG_ARG="--config ${CONFIG_PATH}" -fi - -EXTRA_ARGS="" -[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" - -echo "Running: python3 -m itrialspace.mask_inserter run ..." -echo " manifest: ${MANIFEST_PATH}" -echo " output: ${OUT_DIR}" - -python3 -m itrialspace.mask_inserter run \ - --manifest "${MANIFEST_PATH}" \ - --output-dir "${OUT_DIR}" \ - ${CFG_ARG} \ - --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ - --seed ${SEED} \ - --n-jobs ${N_JOBS} \ - ${EXTRA_ARGS} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/run_integration_full_volume.sub b/itrialspace/infra/slurm/mask_inserter/run_integration_full_volume.sub deleted file mode 100644 index 1efe1e8b0d713e275fdba026787ac743ed46b330..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/run_integration_full_volume.sub +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=inserter_fullvol -#SBATCH --partition=common -#SBATCH --mem=32G -#SBATCH --cpus-per-task=4 -#SBATCH --time=02:00:00 -#SBATCH --output=full_volume_%j.out -#SBATCH --error=full_volume_%j.err - -# ────────────────────────────────────────────────────────────────────────── -# iTrialSpace Mask Inserter — Full-Volume Integration Tests on HPC -# -# Before submitting, generate a test manifest: -# python itrialspace_mask_inserter/tools/make_test_manifest.py \ -# --output ${ITRIALSPACE_DATA_DIR}/test_manifest.csv -# -# Then submit: -# export ITRIALSPACE_TEST_MANIFEST=${ITRIALSPACE_DATA_DIR}/test_manifest.csv -# export ITRIALSPACE_TEST_BASEDIR=${ITRIALSPACE_DATA_DIR} -# sbatch run_integration_full_volume.sub -# ────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -echo "=== iTrialSpace Mask Inserter: Full-Volume Integration Tests ===" -echo "Job ID: ${SLURM_JOB_ID:-local}" -echo "Node: $(hostname)" -echo "Date: $(date)" -echo "" - -# Activate environment -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# Navigate to project root -cd ${PROJ_DIR} - -# ── Test data paths (edit these or set env vars before sbatch) ─────────── -export ITRIALSPACE_TEST_MANIFEST="${ITRIALSPACE_TEST_MANIFEST:-${ITRIALSPACE_DATA_DIR}/test_manifest.csv}" -export ITRIALSPACE_TEST_BASEDIR="${ITRIALSPACE_TEST_BASEDIR:-${ITRIALSPACE_DATA_DIR}}" - -echo "Test manifest: ${ITRIALSPACE_TEST_MANIFEST}" -echo "Base dir: ${ITRIALSPACE_TEST_BASEDIR}" -echo "Python: $(which python)" -echo "" - -# Verify data exists before running tests -if [ ! -f "${ITRIALSPACE_TEST_MANIFEST}" ]; then - echo "ERROR: Test manifest not found at ${ITRIALSPACE_TEST_MANIFEST}" - echo "Generate it with: python itrialspace_mask_inserter/tools/make_test_manifest.py" - exit 1 -fi - -# Run full-volume integration tests -python -m pytest \ - itrialspace_mask_inserter/tests/test_full_volume.py \ - -v --tb=long -s \ - -m "full_volume" \ - 2>&1 - -echo "" -echo "=== Full-volume tests complete: $(date) ===" diff --git a/itrialspace/infra/slurm/mask_inserter/run_unit_tests.sub b/itrialspace/infra/slurm/mask_inserter/run_unit_tests.sub deleted file mode 100644 index f69869c622b206dc0af6a6805fb0ee28cb5f8b65..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/run_unit_tests.sub +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=inserter_unit_tests -#SBATCH --partition=common -#SBATCH --mem=16G -#SBATCH --cpus-per-task=4 -#SBATCH --time=01:00:00 -#SBATCH --output=unit_tests_%j.out -#SBATCH --error=unit_tests_%j.err - -# ────────────────────────────────────────────────────────────────────────── -# iTrialSpace Mask Inserter — Unit Tests on HPC -# -# Submit: sbatch run_unit_tests.sub -# ────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -echo "=== iTrialSpace Mask Inserter: Unit Tests ===" -echo "Job ID: ${SLURM_JOB_ID:-local}" -echo "Node: $(hostname)" -echo "Date: $(date)" -echo "" - -# Activate environment -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# Navigate to project root -cd ${PROJ_DIR} - -echo "Python: $(which python)" -echo "NumPy: $(python -c 'import numpy; print(numpy.__version__)')" -echo "" - -# Run unit tests (excludes full_volume marker) -python -m pytest \ - itrialspace_mask_inserter/tests/test_placement.py \ - itrialspace_mask_inserter/tests/test_resample.py \ - itrialspace_mask_inserter/tests/test_inserter.py \ - -v --tb=short \ - -m "not full_volume" \ - 2>&1 - -echo "" -echo "=== Unit tests complete: $(date) ===" diff --git a/itrialspace/infra/slurm/mask_inserter/submit_all_arrays.sh b/itrialspace/infra/slurm/mask_inserter/submit_all_arrays.sh deleted file mode 100644 index 5c01523bec96c193f4fcf84cc8f1319570f579a6..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/submit_all_arrays.sh +++ /dev/null @@ -1,203 +0,0 @@ -#!/bin/bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ────────────────────────────────────────────────────────────────────────────── -# Submit mask insertion ARRAY jobs for all 13 iTrialSpace trial modes. -# -# For each mode this script: -# 1. Generates the manifest list file (manifests_modeN.txt) -# 2. Counts how many manifests exist -# 3. Submits sbatch --array=0-(N-1) modeN_insert_masks_array.sub -# -# Modes with exactly 1 manifest fall back to the single (non-array) .sub. -# Modes with 0 manifests are skipped. -# -# Usage: -# ./submit_all_arrays.sh # submit all 13 modes -# ./submit_all_arrays.sh 2 3 7 # submit only modes 2, 3, 7 -# ./submit_all_arrays.sh --dry-run # submit all with dry-run enabled -# ./submit_all_arrays.sh --list-only # generate manifest lists, don't submit -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)" -cd "$SCRIPT_DIR" - -# Ensure logs directory exists -mkdir -p logs - -BASE_DIR="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" -LIST_MANIFESTS="${PROJECT_DIR}/itrialspace_mask_inserter/tools/list_manifests.py" - -MODES=( - "mode1_insert_masks" # Controlled Prevalence - "mode2_insert_masks" # Size Detection Curve - "mode3_insert_masks" # Location Sensitivity - "mode4_insert_masks" # Demographic Stratification - "mode5_insert_masks" # Counterfactual - "mode6_insert_masks" # Cross-Dataset - "mode7_insert_masks" # Bootstrap Confidence - "mode8_insert_masks" # Algorithm Comparison - "mode9_insert_masks" # Screening Simulation - "mode10_insert_masks" # Multi-Nodule Realism - "mode11_insert_masks" # Digital Twin Isolation - "mode12_insert_masks" # Digital Twin Complete - "mode13_insert_masks" # Digital Twin Cross -) - -MODE_DIRS=( - "mode1_controlled_prevalence" - "mode2_size_detection_curve" - "mode3_location_sensitivity" - "mode4_demographic_stratification" - "mode5_counterfactual" - "mode6_cross_dataset" - "mode7_bootstrap_confidence" - "mode8_algorithm_comparison" - "mode9_screening_simulation" - "mode10_multi_nodule_realism" - "mode11_digital_twin_isolation" - "mode12_digital_twin_complete" - "mode13_digital_twin_cross" -) - -MODE_NAMES=( - "Controlled Prevalence" - "Size Detection Curve" - "Location Sensitivity" - "Demographic Stratification" - "Counterfactual" - "Cross-Dataset" - "Bootstrap Confidence" - "Algorithm Comparison" - "Screening Simulation" - "Multi-Nodule Realism" - "Digital Twin Isolation" - "Digital Twin Complete" - "Digital Twin Cross" -) - -# ── Parse flags ─────────────────────────────────────────────────────────────── -DRY_RUN_FLAG="" -LIST_ONLY=false -POSITIONAL=() -for arg in "$@"; do - case "$arg" in - --dry-run) DRY_RUN_FLAG="--export=DRY_RUN=true" ;; - --list-only) LIST_ONLY=true ;; - *) POSITIONAL+=("$arg") ;; - esac -done -set -- "${POSITIONAL[@]+"${POSITIONAL[@]}"}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Array Batch Submission" -echo " Date: $(date)" -if [ -n "$DRY_RUN_FLAG" ]; then - echo " *** DRY RUN MODE ***" -fi -if $LIST_ONLY; then - echo " *** LIST-ONLY MODE (no sbatch) ***" -fi -echo "==================================================================" -echo "" - -# ── Determine which modes to process ───────────────────────────────────────── -if [ $# -eq 0 ]; then - INDICES=($(seq 0 $((${#MODES[@]} - 1)))) -else - INDICES=() - for num in "$@"; do - idx=$((num - 1)) - if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then - INDICES+=($idx) - else - echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" - fi - done -fi - -SUBMITTED=0 -SKIPPED=0 - -for idx in "${INDICES[@]}"; do - num=$((idx + 1)) - mode="${MODES[$idx]}" - dir="${MODE_DIRS[$idx]}" - name="${MODE_NAMES[$idx]}" - manifest_dir="${MANIFEST_ROOT}/${dir}" - list_file="${SCRIPT_DIR}/manifests_mode${num}.txt" - - echo -n " Mode ${num}: ${name} ... " - - # ── Check if manifest directory exists ──────────────────────────────── - if [ ! -d "${manifest_dir}" ]; then - echo "SKIPPED (no directory: ${dir}/)" - SKIPPED=$((SKIPPED + 1)) - continue - fi - - # ── Generate manifest list file ─────────────────────────────────────── - python3 "${LIST_MANIFESTS}" \ - --dir "${manifest_dir}" \ - --output "${list_file}" \ - --quiet 2>/dev/null || true - - if [ ! -f "${list_file}" ]; then - echo "SKIPPED (list_manifests.py failed)" - SKIPPED=$((SKIPPED + 1)) - continue - fi - - N=$(wc -l < "${list_file}" | tr -d ' ') - - if [ "$N" -eq 0 ]; then - echo "SKIPPED (0 manifests)" - rm -f "${list_file}" - SKIPPED=$((SKIPPED + 1)) - continue - fi - - if $LIST_ONLY; then - echo "${N} manifest(s) → ${list_file}" - continue - fi - - # ── Decide: single job vs array job ───────────────────────────────── - if [ "$N" -eq 1 ]; then - # Single manifest → prefer the non-array .sub (simpler logs) - sub_file="${mode}.sub" - if [ -f "$sub_file" ]; then - sbatch $DRY_RUN_FLAG "${sub_file}" - SUBMITTED=$((SUBMITTED + 1)) - else - echo "SKIPPED (${sub_file} not found)" - SKIPPED=$((SKIPPED + 1)) - fi - else - # Multiple manifests → array job - sub_file="${mode}_array.sub" - if [ -f "$sub_file" ]; then - ARRAY_RANGE="0-$((N - 1))" - sbatch $DRY_RUN_FLAG --array="${ARRAY_RANGE}" "${sub_file}" - SUBMITTED=$((SUBMITTED + 1)) - else - echo "SKIPPED (${sub_file} not found)" - SKIPPED=$((SKIPPED + 1)) - fi - fi -done - -echo "" -echo "──────────────────────────────────────────────────────────────────" -echo " Submitted: ${SUBMITTED} Skipped: ${SKIPPED}" -echo "" -echo " Check status: squeue -u $USER" -echo " Cancel all: scancel -u $USER --name='ins_M*'" -echo " Logs: ${SCRIPT_DIR}/logs/" -echo "──────────────────────────────────────────────────────────────────" diff --git a/itrialspace/infra/slurm/mask_inserter/submit_all_inserts.sh b/itrialspace/infra/slurm/mask_inserter/submit_all_inserts.sh deleted file mode 100644 index e1eaf485fa240302e72c53cafaf8be0f3629a41e..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/submit_all_inserts.sh +++ /dev/null @@ -1,115 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# Submit mask insertion jobs for all 13 iTrialSpace trial modes. -# -# Usage: -# ./submit_all_inserts.sh # submit all 13 modes (single-manifest) -# ./submit_all_inserts.sh 1 3 8 # submit only modes 1, 3, 8 -# ./submit_all_inserts.sh --dry-run # submit all with dry-run enabled -# -# For array jobs (modes with multiple manifests), use the array sub files -# directly — see README.md for details. -# ────────────────────────────────────────────────────────────────────────────── - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -cd "$SCRIPT_DIR" - -# Ensure logs directory exists -mkdir -p logs - -MODES=( - "mode1_insert_masks" # Controlled Prevalence - "mode2_insert_masks" # Size Detection Curve - "mode3_insert_masks" # Location Sensitivity - "mode4_insert_masks" # Demographic Stratification - "mode5_insert_masks" # Counterfactual - "mode6_insert_masks" # Cross-Dataset - "mode7_insert_masks" # Bootstrap Confidence - "mode8_insert_masks" # Algorithm Comparison - "mode9_insert_masks" # Screening Simulation - "mode10_insert_masks" # Multi-Nodule Realism - "mode11_insert_masks" # Digital Twin Isolation - "mode12_insert_masks" # Digital Twin Complete - "mode13_insert_masks" # Digital Twin Cross -) - -MODE_NAMES=( - "Controlled Prevalence" - "Size Detection Curve" - "Location Sensitivity" - "Demographic Stratification" - "Counterfactual" - "Cross-Dataset" - "Bootstrap Confidence" - "Algorithm Comparison" - "Screening Simulation" - "Multi-Nodule Realism" - "Digital Twin Isolation" - "Digital Twin Complete" - "Digital Twin Cross" -) - -# Parse --dry-run flag -DRY_RUN_FLAG="" -POSITIONAL=() -for arg in "$@"; do - if [ "$arg" = "--dry-run" ]; then - DRY_RUN_FLAG="--export=DRY_RUN=true" - else - POSITIONAL+=("$arg") - fi -done -set -- "${POSITIONAL[@]}" - -echo "==================================================================" -echo " iTrialSpace Mask Insertion — Batch Submission" -echo " Date: $(date)" -if [ -n "$DRY_RUN_FLAG" ]; then - echo " *** DRY RUN MODE ***" -fi -echo "==================================================================" -echo "" - -if [ $# -eq 0 ]; then - # Submit all - echo "Submitting all ${#MODES[@]} trial modes..." - echo "" - for i in "${!MODES[@]}"; do - mode="${MODES[$i]}" - name="${MODE_NAMES[$i]}" - sub_file="${mode}.sub" - if [ -f "$sub_file" ]; then - echo -n " Mode $((i+1)): ${name} ... " - sbatch $DRY_RUN_FLAG "${sub_file}" - else - echo " Mode $((i+1)): ${name} — SKIPPED (${sub_file} not found)" - fi - done -else - # Submit selected modes - echo "Submitting selected trial modes..." - echo "" - for num in "$@"; do - idx=$((num - 1)) - if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then - mode="${MODES[$idx]}" - name="${MODE_NAMES[$idx]}" - sub_file="${mode}.sub" - if [ -f "$sub_file" ]; then - echo -n " Mode ${num}: ${name} ... " - sbatch $DRY_RUN_FLAG "${sub_file}" - else - echo " Mode ${num}: ${name} — SKIPPED (${sub_file} not found)" - fi - else - echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" - fi - done -fi - -echo "" -echo "──────────────────────────────────────────────────────────────────" -echo "Check status: squeue -u $USER" -echo "Cancel all: scancel -u $USER --name='ins_M*'" -echo "Logs: ${SCRIPT_DIR}/logs/" -echo "──────────────────────────────────────────────────────────────────" diff --git a/itrialspace/infra/slurm/mask_inserter/template_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/template_insert_masks.sub deleted file mode 100644 index f50e1a353dff59ce8f4d0fe1d182b9cc02916688..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/mask_inserter/template_insert_masks.sub +++ /dev/null @@ -1,120 +0,0 @@ -#!/bin/bash -# ────────────────────────────────────────────────────────────────────────────── -# iTrialSpace Mask Insertion Engine — Generic SLURM Template -# -# Reusable template that accepts all parameters via environment variables. -# Set the required variables before calling sbatch: -# -# export TRIAL_MODE=mode1_controlled_prevalence -# export MANIFEST_PATH=/scratch/.../manifest.csv -# export OUT_DIR=/scratch/.../inserted_masks/mode1_controlled_prevalence -# sbatch template_insert_masks.sub -# -# Optional overrides (with defaults shown): -# export CONFIG_PATH=config/defaults.yaml -# export N_JOBS=8 -# export VERIFY_PATHS=true -# export DRY_RUN=false -# export SLURM_MEM=32G -# export SLURM_TIME=04:00:00 -# export SLURM_CPUS=8 -# ────────────────────────────────────────────────────────────────────────────── - -#SBATCH --job-name=iTS_insert -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=04:00:00 -#SBATCH --output=logs/insert_%j.out -#SBATCH --error=logs/insert_%j.err - -set -euo pipefail - -# ── Defaults ────────────────────────────────────────────────────────────────── -TRIAL_MODE="${TRIAL_MODE:-unnamed}" -MANIFEST_PATH="${MANIFEST_PATH:?ERROR: MANIFEST_PATH must be set}" -OUT_DIR="${OUT_DIR:?ERROR: OUT_DIR must be set}" -CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" -N_JOBS="${N_JOBS:-8}" -VERIFY_PATHS="${VERIFY_PATHS:-true}" -DRY_RUN="${DRY_RUN:-false}" -TRIAL_NAME="${TRIAL_NAME:-${TRIAL_MODE}}" -SEED="${SEED:-42}" - -# ── Banner ──────────────────────────────────────────────────────────────────── -echo "==================================================================" -echo " iTrialSpace Mask Insertion Engine" -echo " Mode: ${TRIAL_MODE}" -echo " Job ID: ${SLURM_JOB_ID:-local}" -echo " Node: $(hostname)" -echo " Date: $(date)" -echo "==================================================================" -echo "" -echo " MANIFEST_PATH : ${MANIFEST_PATH}" -echo " OUT_DIR : ${OUT_DIR}" -echo " CONFIG_PATH : ${CONFIG_PATH}" -echo " N_JOBS : ${N_JOBS}" -echo " VERIFY_PATHS : ${VERIFY_PATHS}" -echo " DRY_RUN : ${DRY_RUN}" -echo " TRIAL_NAME : ${TRIAL_NAME}" -echo " SEED : ${SEED}" -echo "" - -# ── Environment ────────────────────────────────────────────────────────────── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - -cd ${PROJ_DIR} -echo "Python: $(which python3)" -echo "Working dir: $(pwd)" -echo "" - -# ── Validate inputs ───────────────────────────────────────────────────────── -if [ ! -f "${MANIFEST_PATH}" ]; then - echo "FATAL: Manifest not found at ${MANIFEST_PATH}" - exit 1 -fi - -if [ ! -f "${CONFIG_PATH}" ] && [ ! -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - echo "WARNING: Config not found at ${CONFIG_PATH}, falling back to built-in defaults" - CONFIG_ARG="" -else - # Resolve relative path under the inserter package if needed - if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then - CONFIG_PATH="src/itrialspace/mask_inserter/${CONFIG_PATH}" - fi - CONFIG_ARG="--config ${CONFIG_PATH}" -fi - -# Create output directory -mkdir -p "${OUT_DIR}" - -# ── Build command ──────────────────────────────────────────────────────────── -CMD="python3 -m itrialspace.mask_inserter run" -CMD+=" --manifest ${MANIFEST_PATH}" -CMD+=" --output-dir ${OUT_DIR}" -CMD+=" ${CONFIG_ARG}" -CMD+=" --trial-name ${TRIAL_NAME}" -CMD+=" --seed ${SEED}" -CMD+=" --n-jobs ${N_JOBS}" - -if [ "${DRY_RUN}" = "true" ]; then - CMD+=" --dry-run" -fi - -echo "Command: ${CMD}" -echo "" - -# ── Execute ────────────────────────────────────────────────────────────────── -eval ${CMD} -EXIT_CODE=$? - -echo "" -echo "==================================================================" -echo " Finished: $(date)" -echo " Exit code: ${EXIT_CODE}" -echo "==================================================================" - -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/nodulemap/nodulemap.sub b/itrialspace/infra/slurm/nodulemap/nodulemap.sub deleted file mode 100644 index 218751c99e9bcce78b2612eb7634294f76646975..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/nodulemap/nodulemap.sub +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=NoduleMap -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --time=7-00:00:00 -#SBATCH --output=logs/nodulemap-%j.out -#SBATCH --error=logs/nodulemap-%j.err - -# =========================================================================== -# iTrialSpace NoduleMap — Server (serve only) -# -# Serves the FastAPI + sigma.js web app on port 8422 from pre-built -# artifacts. It does NOT build anything — build once with -# `sbatch rebuild_nodulemap.sub` (or `its-nodulemap build/edges`) first. -# -# Submit: sbatch nodulemap.sub -# Check: squeue -u $USER · tail -f logs/nodulemap-.out -# Stop: scancel -# -# SSH tunnel (from your laptop): -# ssh -L 8422::8422 @ -# Then open: http://localhost:8422 -# =========================================================================== - -echo "======================================" -echo " iTrialSpace NoduleMap (serve)" -echo " Node: $(hostname)" -echo " Date: $(date)" -echo " Job ID: ${SLURM_JOB_ID:-local}" -echo "======================================" - -# ── Environment ────────────────────────────────────────────────────────── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - -APP_DIR="${PROJ_DIR}" -ARTIFACT_DIR="${NODULEMAP_ARTIFACTS:-${ITRIALSPACE_OUTPUT_DIR:-$APP_DIR}/nodulemap_artifacts}" -PORT="${NODULEMAP_PORT:-8422}" - -cd "$APP_DIR" -mkdir -p logs - -# ── Guard: artifacts must already exist ───────────────────────────────── -if ! ls "$ARTIFACT_DIR"/embeddings_*.npy >/dev/null 2>&1; then - echo "ERROR: no embeddings found in $ARTIFACT_DIR" - echo "Build them first: sbatch infra/slurm/nodulemap/rebuild_nodulemap.sub" - echo "(or: its-nodulemap build --all-2d --outdir \"$ARTIFACT_DIR\" && its-nodulemap edges ...)" - exit 1 -fi - -# ── Artifact summary ──────────────────────────────────────────────────── -echo "" -echo "[$(date +%T)] ═══ Artifact summary ═══" -python -m itrialspace.apps.nodulemap info --artifact-dir "$ARTIFACT_DIR" - -# ── Start server (blocks until the job is cancelled) ──────────────────── -echo "" -echo "[$(date +%T)] ═══ Starting NoduleMap server ═══" -export NODULEMAP_ARTIFACTS="$ARTIFACT_DIR" - -echo "======================================" -echo " NoduleMap running on $(hostname):$PORT" -echo "" -echo " SSH tunnel (from your laptop):" -echo " ssh -L $PORT:$(hostname):$PORT \$USER@" -echo "" -echo " Open: http://localhost:$PORT" -echo "======================================" - -python -m itrialspace.apps.nodulemap serve --artifact-dir "$ARTIFACT_DIR" --port "$PORT" - -echo "[$(date +%T)] Done." diff --git a/itrialspace/infra/slurm/nodulemap/rebuild_nodulemap.sub b/itrialspace/infra/slurm/nodulemap/rebuild_nodulemap.sub deleted file mode 100644 index f27dcf1e693e33a400619981d34801cfc9011995..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/nodulemap/rebuild_nodulemap.sub +++ /dev/null @@ -1,93 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=NMap-Rebuild -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --time=4:00:00 -#SBATCH --output=logs/rebuild_nodulemap-%j.out -#SBATCH --error=logs/rebuild_nodulemap-%j.err - -# =========================================================================== -# NoduleMap Artifact Rebuild — Purge NLST3D -# -# Deletes ALL existing NoduleMap artifacts and rebuilds from scratch. -# After the rebuild, NLST3D rows will be absent (it was removed from -# datasets.yaml). -# -# Runs: -# 1) Clean artifacts directory -# 2) Rebuild 6 embedding models (PCA_2D, PCA_32, UMAP_2D, UMAP_16, -# UMAP_32, TSNE_2D) -# 3) Compute edge lists for all models (k=3,5,10,25) -# 4) Verify NLST3D is absent from every rebuilt artifact -# 5) Run pytest regression tests -# -# Submit: sbatch rebuild_nodulemap.sub -# Check: tail -f logs/rebuild_nodulemap-.out -# =========================================================================== - -set -euo pipefail - -echo "======================================================" -echo " NoduleMap Artifact Rebuild (Purge NLST3D)" -echo " Node: $(hostname)" -echo " Date: $(date)" -echo " Job ID: ${SLURM_JOB_ID:-local}" -echo "======================================================" - -# ── Environment ────────────────────────────────────────────────────────── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda -echo "[$(date +%T)] Python: $(which python3)" -echo "[$(date +%T)] conda env: $CONDA_DEFAULT_ENV" - -APP_DIR="${PROJ_DIR}" -ARTIFACT_DIR="${NODULEMAP_ARTIFACTS:-${ITRIALSPACE_OUTPUT_DIR:-$APP_DIR}/nodulemap_artifacts}" -cd "$APP_DIR" -mkdir -p logs "$ARTIFACT_DIR" - -# ── Step 1: Verify NLST3D is absent from the resolved dataset registry ── -echo "" -echo "[$(date +%T)] ═══ Pre-flight: Checking the dataset registry ═══" -python3 -c " -from itrialspace.io.registry import DatasetRegistry -reg = DatasetRegistry.from_yaml() -assert reg.get('NLST3D') is None, 'NLST3D is active in the dataset registry — remove it before rebuilding.' -print('OK — NLST3D is not in the resolved registry') -" - -# ── Step 2: Clean + Rebuild all artifacts ─────────────────────────────── -echo "" -echo "[$(date +%T)] ═══ Rebuilding all artifacts (clean) ═══" -python3 -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --outdir "$ARTIFACT_DIR" -echo "" -echo "[$(date +%T)] ═══ Artifact rebuild complete ═══" - -# ── Step 3: Post-rebuild verification ─────────────────────────────────── -echo "" -echo "[$(date +%T)] ═══ Running NLST3D purge verification ═══" -python3 -m itrialspace.apps.nodulemap.tools.verify_purge --artifact-dir "$ARTIFACT_DIR" -VERIFY_RC=$? - -if [ $VERIFY_RC -ne 0 ]; then - echo "" - echo "FATAL: Verification FAILED — NLST3D still present in artifacts!" - exit 1 -fi - -# ── Step 4: Run regression tests ──────────────────────────────────────── -echo "" -echo "[$(date +%T)] ═══ Running pytest regression tests ═══" -python3 -m pytest tests/nodulemap/test_models.py -v --tb=short 2>&1 || true -echo "" -echo "[$(date +%T)] ═══ Running pytest purge tests ═══" -python3 -m pytest tests/nodulemap/test_nlst3d_purge.py -v --tb=short 2>&1 - -echo "" -echo "======================================================" -echo " Rebuild complete." -echo " Artifacts: $ARTIFACT_DIR" -echo " $(date)" -echo "======================================================" diff --git a/itrialspace/infra/slurm/run_pipeline.sh b/itrialspace/infra/slurm/run_pipeline.sh deleted file mode 100644 index adf3cac3651a75186ee4fb8b4849658a47b1f9c0..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/run_pipeline.sh +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================ -# run_pipeline.sh — drive the iTrialSpace pipeline end-to-end for one trial mode -# trials (manifest) -> insertion (label-23 masks + audit) -> synthesis (CT) -# -# Stages are chained with SLURM dependencies that wait for the *array* jobs to -# finish (not just their submitters), so synthesis only runs after every mask + -# audit exists. Manifests are discovered recursively (modes 11-13 nest them under -# a dataset subdirectory). Run from the repo root. -# -# Usage: -# infra/slurm/run_pipeline.sh [stage] -# 1..13 -# [stage] all (default) | trials | insert | synth -# (_insert_chain / _synth_chain are internal dependency steps) -# -# Examples: -# infra/slurm/run_pipeline.sh 1 -# for m in $(seq 1 13); do infra/slurm/run_pipeline.sh $m; done -# -# Run size comes from the mode .sub files (edit those / see docs §5). -# Paths/conda-env come from your .env via infra/slurm/env.sh. -# ============================================================================ -set -euo pipefail - -MODE="${1:?usage: run_pipeline.sh [all|trials|insert|synth]}" -STAGE="${2:-all}" - -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -source "${HERE}/env.sh" -cd "${PROJ_DIR}" - -TRIALS_SUB=$(ls "${HERE}"/trials/mode${MODE}_*.sub 2>/dev/null | head -1) -INSERT_SUB="${HERE}/mask_inserter/mode${MODE}_insert_masks_array.sub" -SYNTH_SUB="${HERE}/synthesis/mode1_nodmaisi_array.sub" # generic; driven by env overrides -SELF="${HERE}/run_pipeline.sh" -G="${ITRIALSPACE_OUTPUT_DIR}" -ML="${G}/manifest_lists/mode${MODE}.txt" -mkdir -p "${G}/manifest_lists" "${G}/nodmaisi_case_lists" logs - -# Recursively find a mode's manifest CSVs (handles the modes 11-13 dataset subdirs). -list_manifests() { find "${G}/manifests/mode${MODE}_"*/ -name '*.csv' 2>/dev/null | sort; } - -case "${STAGE}" in - - trials|all) - [ -f "${TRIALS_SUB}" ] || { echo "No trials .sub for mode ${MODE}"; exit 1; } - TJOB=$(sbatch --parsable "${TRIALS_SUB}") - echo "[mode ${MODE}] trials -> job ${TJOB}" - [ "${STAGE}" = "trials" ] && exit 0 - # After trials finish, build the manifest list and submit insertion (+ chain synth). - sbatch --parsable --dependency=afterok:${TJOB} \ - --job-name=drv_ins_M${MODE} --partition="${SLURM_PARTITION_CPU}" --time=00:15:00 \ - --output=logs/drv_ins_M${MODE}_%j.out --error=logs/drv_ins_M${MODE}_%j.err \ - --wrap="bash '${SELF}' ${MODE} _insert_chain" - echo "[mode ${MODE}] insertion+synthesis chained after trials" - ;; - - insert) - # trials already done — submit insertion array now (no synth chain) - list_manifests > "${ML}"; N=$(wc -l < "${ML}") - [ "${N}" -gt 0 ] || { echo "No manifests for mode ${MODE} (run trials first)"; exit 1; } - sbatch --array=0-$((N-1)) --export=ALL,MANIFEST_LIST="${ML}" "${INSERT_SUB}" - echo "[mode ${MODE}] insertion -> ${N} manifest task(s)" - ;; - - _insert_chain) - # runs as a dependency job AFTER trials: submit the insert array, then chain - # the synth driver on that ARRAY (so it waits for all masks/audits). - list_manifests > "${ML}"; N=$(wc -l < "${ML}") - [ "${N}" -gt 0 ] || { echo "No manifests for mode ${MODE}"; exit 1; } - IARR=$(sbatch --parsable --array=0-$((N-1)) --export=ALL,MANIFEST_LIST="${ML}" "${INSERT_SUB}") - echo "[mode ${MODE}] insertion array -> ${IARR} (${N} task(s))" - sbatch --parsable --dependency=afterok:${IARR} \ - --job-name=drv_syn_M${MODE} --partition="${SLURM_PARTITION_CPU}" --time=00:15:00 \ - --output=logs/drv_syn_M${MODE}_%j.out --error=logs/drv_syn_M${MODE}_%j.err \ - --wrap="bash '${SELF}' ${MODE} synth" - ;; - - synth) - # one synthesis array per audit.json (one task per case). Audits exist now. - nsub=0 - while IFS= read -r audit; do - [ -z "${audit}" ] && continue - sub=$(basename "$(dirname "${audit}")") - cl="${G}/nodmaisi_case_lists/mode${MODE}_${sub}.txt" - n=$(python "${HERE}/_gen_caselist.py" "${audit}" "${cl}") - [ "${n}" -gt 0 ] || continue - sbatch --array=0-$((n-1)) \ - --export=ALL,AUDIT_PATH="${audit}",CASE_LIST="${cl}",OUT_DIR="${G}/generated_cts/mode${MODE}/${sub}" \ - "${SYNTH_SUB}" - nsub=$((nsub+1)) - done < <(find "${G}/inserted_masks/mode${MODE}_"*/ -name audit.json 2>/dev/null | sort) - echo "[mode ${MODE}] synthesis -> ${nsub} array job(s)" - [ "${nsub}" -gt 0 ] || { echo "[mode ${MODE}] no audits found — insertion incomplete?"; exit 1; } - ;; - - *) echo "unknown stage: ${STAGE}"; exit 1 ;; -esac diff --git a/itrialspace/infra/slurm/synthesis/audit_mode.py b/itrialspace/infra/slurm/synthesis/audit_mode.py deleted file mode 100644 index 3356c54a1e0b0fef8bccf217182c6df3012cdfe2..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/audit_mode.py +++ /dev/null @@ -1,308 +0,0 @@ -#!/usr/bin/env python3 -"""Post-run audit for a NodMAISI mode output directory. - -Scans all case directories, checks completeness (synthetic_ct, audit, QC), -aggregates per-case results, and writes a mode-level pipeline_summary.json. - -Usage: - python3 audit_mode.py [--mask-dir ] - -Example: - python3 audit_mode.py /scratch/.../generated_cts/mode1_controlled_prevalence \ - --mask-dir /scratch/.../inserted_masks/mode1_controlled_prevalence -""" - -import argparse -import glob -import json -import os -import sys -from datetime import datetime - - -def discover_case_dirs(out_dir): - """Find all case directories (flat and sub-bin layouts).""" - case_dirs = {} - for entry in sorted(os.listdir(out_dir)): - fp = os.path.join(out_dir, entry) - if not os.path.isdir(fp): - continue - if entry.startswith("iTS--"): - case_dirs[entry] = fp - else: - # Sub-bin directory (e.g. size_curve_<5mm/) - for sub in sorted(os.listdir(fp)): - sfp = os.path.join(fp, sub) - if os.path.isdir(sfp) and sub.startswith("iTS--"): - case_dirs[sub] = sfp - return case_dirs - - -def discover_expected_cases(mask_dir): - """Discover all expected case IDs from the mask directory.""" - case_ids = set() - if not mask_dir or not os.path.isdir(mask_dir): - return case_ids - - # Pass 1: audit.json files - audited_dirs = set() - for af in sorted(glob.glob(os.path.join(mask_dir, "**", "audit.json"), recursive=True)): - audited_dirs.add(os.path.dirname(af)) - try: - audit = json.load(open(af)) - except Exception: - continue - for r in audit.get("records", []): - if r.get("status") != "success": - continue - cp = r.get("output_combined_path", "") - if not cp or not os.path.isfile(cp): - continue - name = os.path.basename(cp) - for sfx in ("_mask.nii.gz", ".nii.gz"): - if name.endswith(sfx): - name = name[: -len(sfx)] - break - case_ids.add(name) - - # Pass 2: file-scan for dirs without audit.json - for root, dirs, files in os.walk(mask_dir): - if root in audited_dirs: - continue - for f in files: - if not f.endswith(".nii.gz"): - continue - name = f - for sfx in ("_mask.nii.gz", ".nii.gz"): - if name.endswith(sfx): - name = name[: -len(sfx)] - break - case_ids.add(name) - - return case_ids - - -def audit_case(case_id, case_dir): - """Audit a single case directory for completeness.""" - result = { - "case_id": case_id, - "status": "unknown", - "has_synthetic_ct": False, - "has_nodmaisi_audit": False, - "has_qc_slices": False, - "qc_slice_count": 0, - "has_failure_json": False, - "has_dataset_json": False, - "has_input_mask": False, - "synthetic_ct_path": "", - "reason": "", - "total_sec": 0.0, - } - - if not os.path.isdir(case_dir): - result["status"] = "missing" - result["reason"] = "No output directory" - return result - - ct_path = os.path.join(case_dir, "synthetic_ct.nii.gz") - result["has_synthetic_ct"] = os.path.isfile(ct_path) - if result["has_synthetic_ct"]: - result["synthetic_ct_path"] = ct_path - - result["has_nodmaisi_audit"] = os.path.isfile( - os.path.join(case_dir, "nodmaisi_audit.json") - ) - result["has_dataset_json"] = os.path.isfile( - os.path.join(case_dir, "dataset.json") - ) - result["has_input_mask"] = os.path.isfile( - os.path.join(case_dir, "input_mask.nii.gz") - ) - - qc_slices = glob.glob(os.path.join(case_dir, "qc", "qc_slice_*.png")) - result["has_qc_slices"] = len(qc_slices) > 0 - result["qc_slice_count"] = len(qc_slices) - - fail_path = os.path.join(case_dir, "nodmaisi_failure.json") - result["has_failure_json"] = os.path.isfile(fail_path) - - # Read failure reason - if result["has_failure_json"]: - try: - fdata = json.load(open(fail_path)) - result["reason"] = fdata.get("error", fdata.get("reason", "")) - except Exception: - result["reason"] = "unreadable failure json" - - # Read audit for timing / extra info - audit_path = os.path.join(case_dir, "nodmaisi_audit.json") - if os.path.isfile(audit_path): - try: - adata = json.load(open(audit_path)) - result["total_sec"] = adata.get("elapsed_sec", 0.0) - if not result["reason"] and adata.get("status") == "failed": - result["reason"] = adata.get("reason", "") - except Exception: - pass - - # Read per-case pipeline_summary for timing if audit didn't have it - ps_path = os.path.join(case_dir, "pipeline_summary.json") - if os.path.isfile(ps_path) and result["total_sec"] == 0.0: - try: - ps = json.load(open(ps_path)) - cases = ps.get("cases", []) - if cases: - result["total_sec"] = cases[0].get("total_sec", 0.0) - if not result["reason"]: - result["reason"] = cases[0].get("reason", "") - except Exception: - pass - - # Determine overall status - if result["has_synthetic_ct"] and result["has_nodmaisi_audit"] and result["has_qc_slices"]: - result["status"] = "success" - elif result["has_failure_json"]: - result["status"] = "failed" - elif result["has_synthetic_ct"] and not result["has_qc_slices"]: - result["status"] = "incomplete" - if not result["reason"]: - result["reason"] = "synthetic_ct exists but QC slices missing" - elif result["has_nodmaisi_audit"] and not result["has_synthetic_ct"]: - result["status"] = "failed" - if not result["reason"]: - result["reason"] = "audit exists but no synthetic_ct produced" - else: - result["status"] = "incomplete" - if not result["reason"]: - missing = [] - if not result["has_synthetic_ct"]: - missing.append("synthetic_ct") - if not result["has_nodmaisi_audit"]: - missing.append("nodmaisi_audit") - if not result["has_qc_slices"]: - missing.append("qc_slices") - result["reason"] = f"Missing: {', '.join(missing)}" - - return result - - -def main(): - parser = argparse.ArgumentParser(description="Audit NodMAISI mode output") - parser.add_argument("out_dir", help="Mode output directory (generated_cts/modeN_*)") - parser.add_argument("--mask-dir", default="", help="Mask directory for expected case count") - parser.add_argument("--output", default="", help="Output path for pipeline_summary.json (default: /pipeline_summary.json)") - args = parser.parse_args() - - out_dir = args.out_dir - if not os.path.isdir(out_dir): - print(f"ERROR: Output directory not found: {out_dir}", file=sys.stderr) - return 1 - - mode_name = os.path.basename(out_dir) - print(f"Auditing: {mode_name}") - print(f" Output dir: {out_dir}") - - # Discover case dirs - case_dirs = discover_case_dirs(out_dir) - print(f" Case directories found: {len(case_dirs)}") - - # Discover expected cases from masks - expected = discover_expected_cases(args.mask_dir) - if expected: - print(f" Expected cases (from masks): {len(expected)}") - - # Identify cases that have no output dir at all - missing_cases = sorted(expected - set(case_dirs.keys())) if expected else [] - - # Audit each case dir - results = [] - for cid, cdir in sorted(case_dirs.items()): - results.append(audit_case(cid, cdir)) - - # Add missing cases (no output dir) - for cid in missing_cases: - results.append({ - "case_id": cid, - "status": "missing", - "has_synthetic_ct": False, - "has_nodmaisi_audit": False, - "has_qc_slices": False, - "qc_slice_count": 0, - "has_failure_json": False, - "has_dataset_json": False, - "has_input_mask": False, - "synthetic_ct_path": "", - "reason": "No output directory", - "total_sec": 0.0, - }) - - # Tally - n_success = sum(1 for r in results if r["status"] == "success") - n_failed = sum(1 for r in results if r["status"] == "failed") - n_incomplete = sum(1 for r in results if r["status"] == "incomplete") - n_missing = sum(1 for r in results if r["status"] == "missing") - total = len(results) - total_sec = sum(r["total_sec"] for r in results) - - # Failure reason breakdown - failure_reasons = {} - for r in results: - if r["status"] in ("failed", "incomplete", "missing"): - reason = r["reason"] or "unknown" - failure_reasons.setdefault(reason, []).append(r["case_id"]) - - # Print summary - print(f"\n{'='*60}") - print(f" AUDIT SUMMARY: {mode_name}") - print(f"{'='*60}") - print(f" Total cases: {total}") - if expected: - print(f" Expected: {len(expected)}") - print(f" Success: {n_success} ({100*n_success/total:.1f}%)" if total else "") - print(f" Failed: {n_failed}") - print(f" Incomplete: {n_incomplete}") - print(f" Missing: {n_missing}") - print(f" Total GPU time: {total_sec/3600:.1f} hours") - - if failure_reasons: - print(f"\n Failure/issue breakdown:") - for reason, cases in sorted(failure_reasons.items(), key=lambda x: -len(x[1])): - print(f" [{len(cases):4d}] {reason[:100]}") - - # Build pipeline_summary.json - summary = { - "pipeline": "itrialspace_to_nodmaisi", - "mode": mode_name, - "timestamp": datetime.now().isoformat(), - "audit_type": "post_run_aggregate", - "total_cases": total, - "expected_cases": len(expected) if expected else None, - "n_success": n_success, - "n_failed": n_failed, - "n_incomplete": n_incomplete, - "n_missing": n_missing, - "success_rate": round(n_success / total, 4) if total else 0, - "total_gpu_hours": round(total_sec / 3600, 2), - "failure_breakdown": { - reason: { - "count": len(cases), - "examples": cases[:5], - } - for reason, cases in sorted( - failure_reasons.items(), key=lambda x: -len(x[1]) - ) - }, - "cases": results, - } - - output_path = args.output or os.path.join(out_dir, "pipeline_summary.json") - with open(output_path, "w") as f: - json.dump(summary, f, indent=2, default=str) - print(f"\n Written: {output_path}") - print(f"{'='*60}") - - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/itrialspace/infra/slurm/synthesis/audit_mode.sub b/itrialspace/infra/slurm/synthesis/audit_mode.sub deleted file mode 100644 index 4ec4dacd8440937b01e9a4e9fa1befd9a743dc76..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/audit_mode.sub +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=1 -#SBATCH --mem=4G -#SBATCH --time=00:30:00 -#SBATCH --output=${PROJ_DIR}/src/itrialspace/synthesis/slurm_nodmaisi/logs/audit_%x_%j.out -#SBATCH --error=${PROJ_DIR}/src/itrialspace/synthesis/slurm_nodmaisi/logs/audit_%x_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# Post-run audit job — runs after all NodMAISI array tasks finish. -# Scans the mode output directory and writes pipeline_summary.json. -# -# Required exports: TRIAL_MODE, OUT_DIR, MASK_DIR - -set -euo pipefail - -SCRIPT_DIR="${PROJ_DIR}/src/itrialspace/synthesis/slurm_nodmaisi" - -echo "========================================" -echo " Post-run Audit: ${TRIAL_MODE}" -echo " Output dir: ${OUT_DIR}" -echo " Mask dir: ${MASK_DIR}" -echo " Time: $(date)" -echo "========================================" - -python3 "${SCRIPT_DIR}/audit_mode.py" "${OUT_DIR}" --mask-dir "${MASK_DIR}" - -echo "" -echo "Audit complete at $(date)" diff --git a/itrialspace/infra/slurm/synthesis/mode1_nodmaisi_array.sub b/itrialspace/infra/slurm/synthesis/mode1_nodmaisi_array.sub deleted file mode 100644 index 7b4d24f46c62e8d7397c070b52b4ddbd8a64cc5e..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/mode1_nodmaisi_array.sub +++ /dev/null @@ -1,94 +0,0 @@ -#!/bin/bash -# ============================================================================ -# Mode 1: Controlled Prevalence — NodMAISI CT synthesis (array job) -# -# Processes each case as a separate SLURM array task for maximum parallelism. -# Reads case IDs from the audit.json and distributes one case per task. -# -# Usage: -# # First, generate the case list: -# python -c " -# import json -# audit = json.load(open('$AUDIT_PATH')) -# cases = sorted({__import__('os').path.basename(r['output_combined_path']).replace('_mask.nii.gz','') for r in audit['records'] if r['status']=='success'}) -# open('/tmp/mode1_cases.txt','w').write('\n'.join(cases)) -# print(f'{len(cases)} cases') -# " -# # Then submit: -# sbatch --array=0-$(( $(wc -l < /tmp/mode1_cases.txt) - 1 )) mode1_nodmaisi_array.sub -# ============================================================================ - -#SBATCH --job-name=NM_M1_arr -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=64G -#SBATCH --time=02:00:00 -#SBATCH --output=logs/NM_M1_arr_%A_%a.out -#SBATCH --error=logs/NM_M1_arr_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" -ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" -TRIAL_MODE="mode1_controlled_prevalence" - -AUDIT_PATH="${AUDIT_PATH:-${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}/audit.json}" -OUT_DIR="${OUT_DIR:-${ITRIALSPACE_BASE}/generated_cts/${TRIAL_MODE}}" -CASE_LIST="${CASE_LIST:-${ITRIALSPACE_OUTPUT_DIR}/nodmaisi_case_lists/${TRIAL_MODE}_cases.txt}" -CONFIG_PATH="${CONFIG_PATH:-${NOMAISI_DIR}/tools/integration_config.yaml}" - -# Auto-generate the case list from the audit if missing. Case IDs MUST be the -# mask-filename stems (what the runner matches against --case-ids), NOT the audit's -# integer case_id field. -if [ ! -s "${CASE_LIST}" ]; then - mkdir -p "$(dirname "${CASE_LIST}")" - python3 - "${AUDIT_PATH}" "${CASE_LIST}" <<'PYGEN' -import json, os, sys -def stem(p): - b = os.path.basename(p) - for s in ("_mask.nii.gz", ".nii.gz"): - if b.endswith(s): - return b[: -len(s)] - return b -audit = json.load(open(sys.argv[1])) -recs = audit.get("records", audit.get("cases", [])) -cases = sorted({stem(r["output_combined_path"]) for r in recs - if r.get("status") == "success" and r.get("output_combined_path")}) -open(sys.argv[2], "w").write("\n".join(cases) + "\n") -print(f"Generated {len(cases)} case IDs -> {sys.argv[2]}") -PYGEN -fi - -# Read case ID for this array task -CASE_ID=$(sed -n "$((SLURM_ARRAY_TASK_ID + 1))p" "${CASE_LIST}") -if [ -z "${CASE_ID}" ]; then - echo "FATAL: No case ID at array index ${SLURM_ARRAY_TASK_ID}" - exit 1 -fi - -echo "==================================================================" -echo " NodMAISI CT Synthesis — ${TRIAL_MODE} — Case ${CASE_ID}" -echo " Array Job: ${SLURM_ARRAY_JOB_ID} Task: ${SLURM_ARRAY_TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" - -export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" -export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" - -python "${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" \ - --audit "${AUDIT_PATH}" \ - --config "${CONFIG_PATH}" \ - --outdir "${OUT_DIR}" \ - --case-ids "${CASE_ID}" \ - -v - -EXIT_CODE=$? -echo "Finished case ${CASE_ID}: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/synthesis/nodmaisi_array.sub b/itrialspace/infra/slurm/synthesis/nodmaisi_array.sub deleted file mode 100644 index ed4b2e961eff05e3501d5e3fe5f0ee0bfd5e198a..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/nodmaisi_array.sub +++ /dev/null @@ -1,114 +0,0 @@ -#!/bin/bash -# ============================================================================ -# iTrialSpace -> NodMAISI CT Synthesis — SLURM Array Job (any mode) -# -# Processes each case as a separate SLURM array task (one case per GPU). -# Works with both audit.json and --mask-root discovery. -# -# Required env vars: -# TRIAL_MODE - e.g., mode1_controlled_prevalence -# CASE_LIST - path to a text file with one case ID per line -# -# Optional env vars (with defaults): -# AUDIT_PATH - path to iTrialSpace audit.json (preferred) -# MASK_ROOT - directory of inserted mask NIfTIs (fallback) -# OUT_DIR - output directory for generated CTs -# CONFIG_PATH - integration config YAML -# -# Usage: -# # Step 1: Generate case list -# python3 scripts/gen_case_list.py --mode mode1_controlled_prevalence -# # Step 2: Submit array job -# N=$(wc -l < /tmp/mode1_controlled_prevalence_cases.txt) -# sbatch --array=0-$((N-1))%10 \ -# --export=ALL,TRIAL_MODE=mode1_controlled_prevalence \ -# nodmaisi_array.sub -# ============================================================================ - -#SBATCH --job-name=NM_arr -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=64G -#SBATCH --time=02:00:00 -#SBATCH --output=logs/NM_%x_%A_%a.out -#SBATCH --error=logs/NM_%x_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -# ── Configurable paths ─────────────────────────────────────────────────────── -NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" -ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" - -TRIAL_MODE="${TRIAL_MODE:?ERROR: TRIAL_MODE must be set}" -CASE_LIST="${CASE_LIST:-${ITRIALSPACE_BASE}/nodmaisi_case_lists/${TRIAL_MODE}_cases.txt}" - -AUDIT_PATH="${AUDIT_PATH:-${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}/audit.json}" -MASK_ROOT="${MASK_ROOT:-${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}}" -OUT_DIR="${OUT_DIR:-${ITRIALSPACE_BASE}/generated_cts/${TRIAL_MODE}}" -CONFIG_PATH="${CONFIG_PATH:-${NOMAISI_DIR}/tools/integration_config.yaml}" - -# ── Read case ID for this array task ───────────────────────────────────────── -if [ ! -f "${CASE_LIST}" ]; then - echo "FATAL: Case list not found: ${CASE_LIST}" - echo "Generate it first with: python3 scripts/gen_case_list.py --mode ${TRIAL_MODE}" - exit 1 -fi - -# CASE_OFFSET allows chunked array jobs (default 0 for backward compat) -CASE_OFFSET=${CASE_OFFSET:-0} -LINE_NUM=$(( SLURM_ARRAY_TASK_ID + CASE_OFFSET + 1 )) - -CASE_ID=$(sed -n "${LINE_NUM}p" "${CASE_LIST}") -if [ -z "${CASE_ID}" ]; then - echo "FATAL: No case ID at line ${LINE_NUM} (array_idx=${SLURM_ARRAY_TASK_ID}, offset=${CASE_OFFSET}) in ${CASE_LIST}" - exit 1 -fi - -# ── Banner ─────────────────────────────────────────────────────────────────── -echo "==================================================================" -echo " NodMAISI CT Synthesis — ${TRIAL_MODE} — Case ${CASE_ID}" -echo " Array Job: ${SLURM_ARRAY_JOB_ID} Task: ${SLURM_ARRAY_TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " CASE_LIST : ${CASE_LIST}" -echo " AUDIT_PATH : ${AUDIT_PATH}" -echo " MASK_ROOT : ${MASK_ROOT}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -# ── Environment ────────────────────────────────────────────────────────────── -export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" -export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -mkdir -p "${OUT_DIR}" - -# ── Build command — prefer audit.json, fallback to mask-root ───────────────── -CMD=( - python "${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" - --config "${CONFIG_PATH}" - --outdir "${OUT_DIR}" - --case-ids "${CASE_ID}" - -v -) - -if [ -f "${AUDIT_PATH}" ]; then - CMD+=(--audit "${AUDIT_PATH}") -else - CMD+=(--mask-root "${MASK_ROOT}") -fi - -echo "Command: ${CMD[*]}" -"${CMD[@]}" -EXIT_CODE=$? - -echo "" -echo "Finished case ${CASE_ID}: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/synthesis/nodmaisi_combined_rerun.sub b/itrialspace/infra/slurm/synthesis/nodmaisi_combined_rerun.sub deleted file mode 100644 index 458d14065fbd6031a256c8e9d42809ac41551e9d..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/nodmaisi_combined_rerun.sub +++ /dev/null @@ -1,107 +0,0 @@ -#!/bin/bash -# ============================================================================ -# Combined multi-mode NodMAISI CT rerun — single SLURM array job -# -# Reads from a combined case list where each line is: -# MODE_NAMECASE_ID -# -# This allows a single array job with a single throttle to control -# total GPU usage across all modes. -# -# Usage: -# N=$(wc -l < /path/to/all_modes_rerun_combined.txt) -# sbatch --array=0-$((N-1))%4 nodmaisi_combined_rerun.sub -# ============================================================================ - -#SBATCH --job-name=NM_rerun -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --time=02:00:00 -#SBATCH --output=logs/NM_%x_%A_%a.out -#SBATCH --error=logs/NM_%x_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -# ── Configurable paths ─────────────────────────────────────────────────────── -NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" -ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" - -COMBINED_LIST="${COMBINED_LIST:-${ITRIALSPACE_BASE}/nodmaisi_case_lists/all_modes_rerun_combined.txt}" - -# ── Read mode + case ID for this array task ────────────────────────────────── -if [ ! -f "${COMBINED_LIST}" ]; then - echo "FATAL: Combined case list not found: ${COMBINED_LIST}" - exit 1 -fi - -LINE_NUM=$(( SLURM_ARRAY_TASK_ID + 1 )) -LINE=$(sed -n "${LINE_NUM}p" "${COMBINED_LIST}") - -if [ -z "${LINE}" ]; then - echo "FATAL: No entry at line ${LINE_NUM} (task_id=${SLURM_ARRAY_TASK_ID}) in ${COMBINED_LIST}" - exit 1 -fi - -TRIAL_MODE=$(echo "${LINE}" | cut -f1) -CASE_ID=$(echo "${LINE}" | cut -f2) - -if [ -z "${TRIAL_MODE}" ] || [ -z "${CASE_ID}" ]; then - echo "FATAL: Could not parse mode/case from line ${LINE_NUM}: '${LINE}'" - exit 1 -fi - -# ── Derive paths from mode ─────────────────────────────────────────────────── -AUDIT_PATH="${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}/audit.json" -MASK_ROOT="${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}" -OUT_DIR="${ITRIALSPACE_BASE}/generated_cts/${TRIAL_MODE}" -CONFIG_PATH="${NOMAISI_DIR}/tools/integration_config.yaml" - -# ── Banner ─────────────────────────────────────────────────────────────────── -echo "==================================================================" -echo " NodMAISI CT Rerun — ${TRIAL_MODE} — Case ${CASE_ID}" -echo " Array Job: ${SLURM_ARRAY_JOB_ID} Task: ${SLURM_ARRAY_TASK_ID}" -echo " Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " COMBINED_LIST: ${COMBINED_LIST}" -echo " AUDIT_PATH : ${AUDIT_PATH}" -echo " MASK_ROOT : ${MASK_ROOT}" -echo " OUT_DIR : ${OUT_DIR}" -echo "" - -# ── Environment ────────────────────────────────────────────────────────────── -export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" -export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -mkdir -p "${OUT_DIR}" - -# ── Build command — prefer audit.json, fallback to mask-root ───────────────── -CMD=( - python "${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" - --config "${CONFIG_PATH}" - --outdir "${OUT_DIR}" - --case-ids "${CASE_ID}" - -v -) - -if [ -f "${AUDIT_PATH}" ]; then - CMD+=(--audit "${AUDIT_PATH}") -else - CMD+=(--mask-root "${MASK_ROOT}") -fi - -echo "Command: ${CMD[*]}" -"${CMD[@]}" -EXIT_CODE=$? - -echo "" -echo "Finished case ${CASE_ID} (${TRIAL_MODE}): $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/synthesis/submit_all_nodmaisi.sh b/itrialspace/infra/slurm/synthesis/submit_all_nodmaisi.sh deleted file mode 100644 index 2a149341924efdc5e5602f3073cd383a7d2019ec..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/submit_all_nodmaisi.sh +++ /dev/null @@ -1,134 +0,0 @@ -#!/bin/bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ============================================================================ -# Submit NodMAISI CT synthesis jobs for all 9 iTrialSpace trial modes. -# -# Reads audit.json from each mode's inserted_masks directory. -# -# Usage: -# ./submit_all_nodmaisi.sh # submit all 9 modes -# ./submit_all_nodmaisi.sh 1 3 8 # submit only modes 1, 3, 8 -# ./submit_all_nodmaisi.sh --dry-run # all modes, dry-run -# ============================================================================ - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -cd "$SCRIPT_DIR" - -NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" -ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" -MASK_BASE="${ITRIALSPACE_BASE}/inserted_masks" -CT_BASE="${ITRIALSPACE_BASE}/generated_cts" - -mkdir -p logs - -MODES=( - "mode1_controlled_prevalence" - "mode2_size_detection_curve" - "mode3_location_sensitivity" - "mode4_demographic_stratification" - "mode5_counterfactual" - "mode6_cross_dataset" - "mode7_bootstrap_confidence" - "mode8_algorithm_comparison" - "mode9_screening_simulation" -) - -MODE_NAMES=( - "Controlled Prevalence" - "Size Detection Curve" - "Location Sensitivity" - "Demographic Stratification" - "Counterfactual" - "Cross-Dataset" - "Bootstrap Confidence" - "Algorithm Comparison" - "Screening Simulation" -) - -# Parse --dry-run flag -DRY_RUN_EXPORT="" -POSITIONAL=() -for arg in "$@"; do - if [ "$arg" = "--dry-run" ]; then - DRY_RUN_EXPORT="--export=ALL,DRY_RUN=true" - else - POSITIONAL+=("$arg") - fi -done -set -- "${POSITIONAL[@]}" - -echo "==================================================================" -echo " iTrialSpace -> NodMAISI CT Synthesis — Batch Submission" -echo " Date: $(date)" -if [ -n "$DRY_RUN_EXPORT" ]; then - echo " *** DRY RUN MODE ***" -fi -echo "==================================================================" -echo "" - -submit_mode() { - local idx=$1 - local mode="${MODES[$idx]}" - local name="${MODE_NAMES[$idx]}" - local mask_dir="${MASK_BASE}/${mode}" - local audit_path="${mask_dir}/audit.json" - local out_dir="${CT_BASE}/${mode}" - - echo -n " Mode $((idx+1)): ${name} ... " - - # Check for audit.json at root or in any subdirectory - local audit_path="${mask_dir}/audit.json" - local has_sub_audits - has_sub_audits=$(find "${mask_dir}" -mindepth 2 -name "audit.json" 2>/dev/null | head -1) - - if [ -f "${audit_path}" ]; then - sbatch $DRY_RUN_EXPORT \ - --export=ALL,AUDIT_PATH="${audit_path}",OUT_DIR="${out_dir}" \ - --job-name="NM_M$((idx+1))" \ - template_nodmaisi_from_masks.sub - elif [ -n "${has_sub_audits}" ]; then - echo -n "(subdirectory audits found, using --mask-root) " - sbatch $DRY_RUN_EXPORT \ - --export=ALL,MASK_ROOT="${mask_dir}",OUT_DIR="${out_dir}" \ - --job-name="NM_M$((idx+1))" \ - template_nodmaisi_from_masks.sub - elif [ -d "${mask_dir}" ] && find "${mask_dir}" -name "*.nii.gz" -print -quit | grep -q .; then - echo -n "(no audit.json, using --mask-root) " - sbatch $DRY_RUN_EXPORT \ - --export=ALL,MASK_ROOT="${mask_dir}",OUT_DIR="${out_dir}" \ - --job-name="NM_M$((idx+1))" \ - template_nodmaisi_from_masks.sub - else - echo "SKIPPED (no audit.json and no masks in ${mask_dir})" - return - fi -} - -if [ $# -eq 0 ]; then - echo "Submitting all 9 trial modes..." - echo "" - for i in "${!MODES[@]}"; do - submit_mode "$i" - done -else - echo "Submitting selected trial modes..." - echo "" - for num in "$@"; do - idx=$((num - 1)) - if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then - submit_mode "$idx" - else - echo " Invalid mode number: $num (valid: 1-9)" - fi - done -fi - -echo "" -echo "--------------------------------------------------------------" -echo "Check status: squeue -u $USER" -echo "Cancel all: scancel -u $USER --name='NM_M*'" -echo "Logs: ${SCRIPT_DIR}/logs/" -echo "--------------------------------------------------------------" diff --git a/itrialspace/infra/slurm/synthesis/submit_array_jobs.sh b/itrialspace/infra/slurm/synthesis/submit_array_jobs.sh deleted file mode 100644 index 9b3a396f3ef201ebe761a8bf9c24e866cf2e1cec..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/submit_array_jobs.sh +++ /dev/null @@ -1,326 +0,0 @@ -#!/bin/bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ============================================================================ -# Submit NodMAISI CT synthesis ARRAY jobs for iTrialSpace trial modes. -# -# For each mode: generates a case list, then submits a SLURM array job -# (one case per GPU task) for maximum parallelism. -# -# Usage: -# ./submit_array_jobs.sh # all 13 modes -# ./submit_array_jobs.sh 1 3 8 # selected modes -# ./submit_array_jobs.sh --dry-run # all modes, dry-run -# ./submit_array_jobs.sh --max-concurrent 20 # limit concurrent GPU tasks -# ./submit_array_jobs.sh --time 04:00:00 # override walltime per task -# ./submit_array_jobs.sh --skip-existing # skip cases with synthetic_ct -# ./submit_array_jobs.sh --nodelist node001 # pin jobs to specific node -# ============================================================================ - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -cd "$SCRIPT_DIR" - -ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" -MASK_BASE="${ITRIALSPACE_BASE}/inserted_masks" -CT_BASE="${ITRIALSPACE_BASE}/generated_cts" -CASE_LIST_DIR="${ITRIALSPACE_BASE}/nodmaisi_case_lists" - -MAX_CONCURRENT="${MAX_CONCURRENT:-10}" -TIME_OVERRIDE="" -DRY_RUN="" -SKIP_EXISTING="" -NODELIST="" - -MODES=( - "mode1_controlled_prevalence" - "mode2_size_detection_curve" - "mode3_location_sensitivity" - "mode4_demographic_stratification" - "mode5_counterfactual" - "mode6_cross_dataset" - "mode7_bootstrap_confidence" - "mode8_algorithm_comparison" - "mode9_screening_simulation" - "mode10_multi_nodule_realism" - "mode11_digital_twin_isolation" - "mode12_digital_twin_complete" - "mode13_digital_twin_cross" -) - -MODE_NAMES=( - "Controlled Prevalence" - "Size Detection Curve" - "Location Sensitivity" - "Demographic Stratification" - "Counterfactual" - "Cross-Dataset" - "Bootstrap Confidence" - "Algorithm Comparison" - "Screening Simulation" - "Multi-Nodule Realism" - "Digital Twin Isolation" - "Digital Twin Complete" - "Digital Twin Cross" -) - -# ── Parse arguments ────────────────────────────────────────────────────────── -POSITIONAL=() -while [[ $# -gt 0 ]]; do - case "$1" in - --dry-run) DRY_RUN="true"; shift ;; - --skip-existing) SKIP_EXISTING="true"; shift ;; - --max-concurrent) MAX_CONCURRENT="$2"; shift 2 ;; - --time) TIME_OVERRIDE="$2"; shift 2 ;; - --nodelist) NODELIST="$2"; shift 2 ;; - *) POSITIONAL+=("$1"); shift ;; - esac -done -set -- "${POSITIONAL[@]+"${POSITIONAL[@]}"}" - -mkdir -p logs "${CASE_LIST_DIR}" - -echo "==================================================================" -echo " iTrialSpace -> NodMAISI — Array Job Submission" -echo " Date: $(date)" -echo " Max concurrent tasks per mode: ${MAX_CONCURRENT}" -[ -n "$DRY_RUN" ] && echo " *** DRY RUN MODE ***" -[ -n "$SKIP_EXISTING" ] && echo " Skip existing: YES (requires synthetic_ct + audit + QC slices)" -[ -n "$NODELIST" ] && echo " Node constraint: ${NODELIST}" -echo "==================================================================" -echo "" - -# ── Generate case list from audit.json or mask directory ───────────────────── -generate_case_list() { - local mode="$1" - local mask_dir="${MASK_BASE}/${mode}" - local case_list="${CASE_LIST_DIR}/${mode}_cases.txt" - - if [ -d "${mask_dir}" ]; then - # Hybrid discovery: use audit.json where available, fall back to - # file-scan for subdirectories that lack one (e.g. timed-out jobs). - python3 -c " -import json, os, glob - -mask_dir = '${mask_dir}' -case_ids = set() - -# --- Pass 1: extract from audit.json files --- -audited_dirs = set() -all_audits = sorted(glob.glob(os.path.join(mask_dir, '**', 'audit.json'), recursive=True)) -for af in all_audits: - audited_dirs.add(os.path.dirname(af)) - try: - audit = json.load(open(af)) - except Exception: - continue - for r in audit.get('records', []): - if r.get('status') != 'success': - continue - cp = r.get('output_combined_path', '') - if not cp or not os.path.isfile(cp): - continue - name = os.path.basename(cp) - for sfx in ('_mask.nii.gz', '.nii.gz'): - if name.endswith(sfx): - name = name[:-len(sfx)] - break - case_ids.add(name) - -# --- Pass 2: file-scan for dirs WITHOUT audit.json --- -for root, dirs, files in os.walk(mask_dir): - if root in audited_dirs: - continue # already covered by audit - for f in files: - if not f.endswith('.nii.gz'): - continue - name = f - for sfx in ('_mask.nii.gz', '.nii.gz'): - if name.endswith(sfx): - name = name[:-len(sfx)] - break - case_ids.add(name) - -cases = sorted(case_ids) -if cases: - open('${case_list}', 'w').write('\n'.join(cases) + '\n') -print(len(cases)) -" - else - echo "0" - return 1 - fi -} - -# ── Submit a single mode ──────────────────────────────────────────────────── -submit_mode() { - local idx=$1 - local mode="${MODES[$idx]}" - local name="${MODE_NAMES[$idx]}" - local mask_dir="${MASK_BASE}/${mode}" - local out_dir="${CT_BASE}/${mode}" - local case_list="${CASE_LIST_DIR}/${mode}_cases.txt" - - printf " Mode %d: %-30s " "$((idx+1))" "${name}" - - # Generate case list - local n_cases - n_cases=$(generate_case_list "$mode" 2>/dev/null) - if [ -z "$n_cases" ] || [ "$n_cases" -eq 0 ]; then - echo "SKIPPED (no cases found in ${mask_dir})" - return - fi - - # Optionally filter out already-completed cases - if [ -n "$SKIP_EXISTING" ] && [ -d "${out_dir}" ]; then - local orig_count=$n_cases - python3 -c " -import os, glob -case_list = '${case_list}' -out_dir = '${out_dir}' -cases = open(case_list).read().strip().split('\n') - -def is_complete(case_dir): - \"\"\"A case is complete only if it has synthetic_ct, audit, and QC slices.\"\"\" - if not os.path.isdir(case_dir): - return False - has_ct = os.path.isfile(os.path.join(case_dir, 'synthetic_ct.nii.gz')) - has_audit = os.path.isfile(os.path.join(case_dir, 'nodmaisi_audit.json')) - has_qc = len(glob.glob(os.path.join(case_dir, 'qc', 'qc_slice_*.png'))) > 0 - return has_ct and has_audit and has_qc - -pending = [] -for c in cases: - # Check both flat and sub-directory layouts - case_dir = os.path.join(out_dir, c) - found = is_complete(case_dir) - if not found: - for entry in (os.listdir(out_dir) if os.path.isdir(out_dir) else []): - sub_dir = os.path.join(out_dir, entry, c) - if is_complete(sub_dir): - found = True - break - if not found: - pending.append(c) -open(case_list, 'w').write('\n'.join(pending) + '\n' if pending else '') -print(len(pending)) -" - n_cases=$(wc -l < "${case_list}" | tr -d ' ') - local skipped=$((orig_count - n_cases)) - if [ "$skipped" -gt 0 ]; then - printf "(%d cases, skipped %d existing) " "$n_cases" "$skipped" - else - printf "(%4d cases) " "$n_cases" - fi - if [ "$n_cases" -eq 0 ]; then - echo "ALL DONE" - return - fi - else - printf "(%4d cases) " "$n_cases" - fi - - # SLURM MaxArraySize is typically 1001; chunk large case lists - local MAX_ARRAY_SIZE=1000 - local offset=0 - local chunk_idx=0 - local job_ids=() - - while [ $offset -lt $n_cases ]; do - local remaining=$((n_cases - offset)) - local chunk_size=$remaining - if [ $chunk_size -gt $MAX_ARRAY_SIZE ]; then - chunk_size=$MAX_ARRAY_SIZE - fi - - local sbatch_args="--array=0-$((chunk_size - 1))%${MAX_CONCURRENT}" - sbatch_args+=" --job-name=NM_M$((idx+1))_arr" - - if [ -n "$TIME_OVERRIDE" ]; then - sbatch_args+=" --time=${TIME_OVERRIDE}" - fi - - if [ -n "$NODELIST" ]; then - sbatch_args+=" --nodelist=${NODELIST}" - fi - - local export_vars="ALL,TRIAL_MODE=${mode},CASE_LIST=${case_list},OUT_DIR=${out_dir},CASE_OFFSET=${offset}" - sbatch_args+=" --export=${export_vars}" - - if [ -n "$DRY_RUN" ]; then - echo "Submitted batch job DRY-RUN (chunk $chunk_idx, ${chunk_size} tasks)" - else - # Wait for SLURM queue capacity (MaxJobCount=10000) - while true; do - local qcount - qcount=$(squeue -u "$USER" -r --noheader 2>/dev/null | wc -l) - local avail=$((10000 - qcount)) - if [ "$avail" -ge "$((chunk_size + 200))" ]; then - break - fi - printf "\n [waiting] Queue %d/10000, need %d free slots..." "$qcount" "$((chunk_size + 200))" - sleep 120 - done - - local sbatch_out - sbatch_out=$(sbatch ${sbatch_args} nodmaisi_array.sub) - echo "$sbatch_out" - local jid - jid=$(echo "$sbatch_out" | grep -oP '\d+') - if [ -n "$jid" ]; then - job_ids+=("$jid") - fi - fi - - offset=$((offset + chunk_size)) - chunk_idx=$((chunk_idx + 1)) - done - - # Submit post-run audit job (runs after all array chunks finish) - if [ ${#job_ids[@]} -gt 0 ]; then - local dep_str - dep_str=$(IFS=:; echo "${job_ids[*]}") - local audit_export="ALL,TRIAL_MODE=${mode},OUT_DIR=${out_dir},MASK_DIR=${mask_dir}" - local audit_out - audit_out=$(sbatch --dependency=afterany:${dep_str} \ - --job-name="audit_M$((idx+1))" \ - --export="${audit_export}" \ - audit_mode.sub 2>&1) - local audit_jid - audit_jid=$(echo "$audit_out" | grep -oP '\d+') - printf "\n -> Audit job %s (after %s)\n" "${audit_jid:-??}" "${dep_str}" - elif [ -n "$DRY_RUN" ]; then - printf "\n -> Audit job DRY-RUN (after all chunks)\n" - fi -} - -# ── Main ───────────────────────────────────────────────────────────────────── -if [ ${#POSITIONAL[@]} -eq 0 ] 2>/dev/null || [ $# -eq 0 ]; then - echo "Submitting all ${#MODES[@]} trial modes (1-${#MODES[@]})..." - echo "" - for i in "${!MODES[@]}"; do - submit_mode "$i" - done -else - echo "Submitting selected trial modes..." - echo "" - for num in "$@"; do - idx=$((num - 1)) - if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then - submit_mode "$idx" - else - echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" - fi - done -fi - -echo "" -echo "--------------------------------------------------------------" -echo "Case lists: ${CASE_LIST_DIR}/" -echo "Check status: squeue -u $USER" -echo "Cancel all: scancel -u $USER --name='NM_M*'" -echo "Logs: ${SCRIPT_DIR}/logs/" -echo "--------------------------------------------------------------" diff --git a/itrialspace/infra/slurm/synthesis/template_nodmaisi_from_masks.sub b/itrialspace/infra/slurm/synthesis/template_nodmaisi_from_masks.sub deleted file mode 100644 index d7c3e4251a9e3c1c6c882d06ad88d3a1c8a3f0ec..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/synthesis/template_nodmaisi_from_masks.sub +++ /dev/null @@ -1,79 +0,0 @@ -#!/bin/bash -# ============================================================================ -# Template: iTrialSpace masks -> NodMAISI CT synthesis -# -# Generic SLURM template for running the integration pipeline. -# All parameters are configurable via environment variables. -# -# Usage: -# AUDIT_PATH=/path/to/audit.json OUT_DIR=/scratch/.../out sbatch template_nodmaisi_from_masks.sub -# MASK_ROOT=/path/to/masks OUT_DIR=/scratch/.../out sbatch template_nodmaisi_from_masks.sub -# ============================================================================ - -#SBATCH --job-name=iTS_NodMAISI -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=64G -#SBATCH --time=24:00:00 -#SBATCH --output=logs/iTS_NodMAISI_%j.out -#SBATCH --error=logs/iTS_NodMAISI_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -set -euo pipefail - -# -- Configurable paths (override via environment) -- -NOMAISI_DIR="${NOMAISI_DIR:-${PROJ_DIR}/src/itrialspace/synthesis}" -CONFIG_PATH="${CONFIG_PATH:-${NOMAISI_DIR}/tools/integration_config.yaml}" -AUDIT_PATH="${AUDIT_PATH:-}" -MASK_ROOT="${MASK_ROOT:-}" -OUT_DIR="${OUT_DIR:-${ITRIALSPACE_OUTPUT_DIR}/generated_cts/default}" -DRY_RUN="${DRY_RUN:-false}" -CASE_IDS="${CASE_IDS:-}" -VERBOSE="${VERBOSE:--v}" - -echo "==================================================================" -echo " iTrialSpace -> NodMAISI CT Synthesis Pipeline" -echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" -echo "==================================================================" -echo " AUDIT_PATH : ${AUDIT_PATH:-}" -echo " MASK_ROOT : ${MASK_ROOT:-}" -echo " OUT_DIR : ${OUT_DIR}" -echo " CONFIG_PATH : ${CONFIG_PATH}" -echo " DRY_RUN : ${DRY_RUN}" -echo "" - -# -- Environment setup -- -export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" -export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" - -mkdir -p "${OUT_DIR}" - -# -- Build command -- -CMD="python ${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" -CMD+=" --config ${CONFIG_PATH}" -CMD+=" --outdir ${OUT_DIR}" -CMD+=" ${VERBOSE}" - -if [ -n "${AUDIT_PATH}" ]; then - CMD+=" --audit ${AUDIT_PATH}" -elif [ -n "${MASK_ROOT}" ]; then - CMD+=" --mask-root ${MASK_ROOT}" -else - echo "FATAL: Set either AUDIT_PATH or MASK_ROOT" - exit 1 -fi - -[ "${DRY_RUN}" = "true" ] && CMD+=" --dry-run" -[ -n "${CASE_IDS}" ] && CMD+=" --case-ids ${CASE_IDS}" - -echo "Command: ${CMD}" -eval ${CMD} -EXIT_CODE=$? -echo "Finished: $(date) Exit: ${EXIT_CODE}" -exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/trials/mode10_multi_nodule_realism.sub b/itrialspace/infra/slurm/trials/mode10_multi_nodule_realism.sub deleted file mode 100644 index 2fcd771f3b18c4a4bd38a84d23e57fdadc4fdd94..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode10_multi_nodule_realism.sub +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M10_MultiNod -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode10_multi_nodule_realism.out -#SBATCH --error=logs/mode10_multi_nodule_realism.err - -echo "=== iTrialSpace Trial Mode 10: Multi-Nodule Realism Study ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode10_multi_nodule_realism" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Multi-nodule realism study — creates two sub-cohorts: -# 1. Single-nodule cases (75%) -# 2. Multi-nodule cases with companions (25%) -# -# In NLST, ~25% of screened patients have multiple nodules. -# N_CASES=500 # real run (commented for 5-case smoke test) -N_CASES=5 -MULTI_NODULE_FRACTION=0.25 -COMPANION_STRATEGY="all_companions" -TEMPLATE="NLST" -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode multi_nodule \ - --output-dir "$OUTPUT_DIR" \ - --n-cases $N_CASES \ - --multi-nodule-fraction $MULTI_NODULE_FRACTION \ - --companion-strategy "$COMPANION_STRATEGY" \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode11_digital_twin_isolation.sub b/itrialspace/infra/slurm/trials/mode11_digital_twin_isolation.sub deleted file mode 100644 index 0873069ea9ed10652f671ac5588da7bc6aad6f60..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode11_digital_twin_isolation.sub +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M11_DTiso -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode11_digital_twin_isolation.out -#SBATCH --error=logs/mode11_digital_twin_isolation.err - -echo "=== iTrialSpace Trial Mode 11: Digital Twin Isolation ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_BASE="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode11_digital_twin_isolation" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Digital twin isolation — one isolation case per native nodule per CT scan. -# Matching is at the CT-scan level: each nodule is paired only with its own CT. -# Patients with multiple CT scans (e.g. LUNA25) produce separate cases per CT. -# Runs --all-patients for every dataset so every profiled nodule is covered. -SEED=42 - -# DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run -DATASETS=("DLCS24") # sample - -# ── Run ──────────────────────────────────────────────────────────────────── -for DS in "${DATASETS[@]}"; do - echo "" - echo "──────────────────────────────────────────────────────────────" - echo " Dataset: ${DS}" - echo "──────────────────────────────────────────────────────────────" - - python3 "$RUNNER" \ - --mode digital_twin_isolation \ - --output-dir "${OUTPUT_BASE}/${DS}" \ - --dataset "$DS" \ - --max-patients 5 \ - --max-nodules-per-patient 1 \ - --seed $SEED - - echo " ${DS} done: $(date)" -done - -echo "" -echo "All datasets finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode12_digital_twin_complete.sub b/itrialspace/infra/slurm/trials/mode12_digital_twin_complete.sub deleted file mode 100644 index 55f02738972a2d34063b19ab966a1a3576425c04..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode12_digital_twin_complete.sub +++ /dev/null @@ -1,51 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M12_DTcomp -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode12_digital_twin_complete.out -#SBATCH --error=logs/mode12_digital_twin_complete.err - -echo "=== iTrialSpace Trial Mode 12: Digital Twin Complete ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_BASE="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode12_digital_twin_complete" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Digital twin complete — one case per CT scan containing ALL native nodules -# from that CT. Matching is at the CT-scan level: patients with multiple CT -# scans (e.g. LUNA25) produce one case per CT, not one case per patient. -# Runs --all-patients for every dataset. -SEED=42 - -# DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run -DATASETS=("DLCS24") # sample - -# ── Run ──────────────────────────────────────────────────────────────────── -for DS in "${DATASETS[@]}"; do - echo "" - echo "──────────────────────────────────────────────────────────────" - echo " Dataset: ${DS}" - echo "──────────────────────────────────────────────────────────────" - - python3 "$RUNNER" \ - --mode digital_twin_complete \ - --output-dir "${OUTPUT_BASE}/${DS}" \ - --dataset "$DS" \ - --max-patients 5 \ - --seed $SEED - - echo " ${DS} done: $(date)" -done - -echo "" -echo "All datasets finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode13_digital_twin_cross.sub b/itrialspace/infra/slurm/trials/mode13_digital_twin_cross.sub deleted file mode 100644 index 8d01b9ace25309684512cc5c44deb75adfbc14f4..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode13_digital_twin_cross.sub +++ /dev/null @@ -1,76 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M13_DTcross -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode13_digital_twin_cross.out -#SBATCH --error=logs/mode13_digital_twin_cross.err - -echo "=== iTrialSpace Trial Mode 13: Digital Twin Cross ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_BASE="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode13_digital_twin_cross" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Digital twin cross — donor nodules from one patient inserted into a -# different patient's anatomy. Each host×donor dataset pair produces a -# separate manifest. -SEED=42 - -# Host datasets provide anatomy; donor datasets provide nodules. -# Adjust these arrays for your experimental design. -# HOST_DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run -HOST_DATASETS=("DLCS24") # sample -# DONOR_DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run -DONOR_DATASETS=("LUNA25") # sample - -# Pairing configuration (override with env vars if needed) -DONOR_TRANSFER_MODE="${DONOR_TRANSFER_MODE:-single}" -PAIRING_POLICY="${PAIRING_POLICY:-one_to_one}" -PLACEMENT_STRATEGY="${PLACEMENT_STRATEGY:-profile_faithful_transfer}" - -# Cap donor nodules per cross-pair to ~250 for a ~10k total budget. -# LUNGx has only 83 donors so it uses all of them; others cap at 250. -MAX_DONOR_NODULES="${MAX_DONOR_NODULES:-5}" # sample (real: 250) - -# ── Run ──────────────────────────────────────────────────────────────────── -for HOST_DS in "${HOST_DATASETS[@]}"; do - for DONOR_DS in "${DONOR_DATASETS[@]}"; do - # Skip same-dataset pairs (that's what modes 11/12 are for) - if [ "$HOST_DS" = "$DONOR_DS" ]; then - echo " Skipping same-dataset pair: ${HOST_DS} × ${DONOR_DS}" - continue - fi - - echo "" - echo "──────────────────────────────────────────────────────────────" - echo " Host: ${HOST_DS} × Donor: ${DONOR_DS}" - echo "──────────────────────────────────────────────────────────────" - - python3 "$RUNNER" \ - --mode digital_twin_cross \ - --output-dir "${OUTPUT_BASE}/${HOST_DS}_x_${DONOR_DS}" \ - --host-dataset "$HOST_DS" \ - --donor-dataset "$DONOR_DS" \ - --max-host-patients 5 \ - --max-donor-nodules "$MAX_DONOR_NODULES" \ - --donor-transfer-mode "$DONOR_TRANSFER_MODE" \ - --pairing-policy "$PAIRING_POLICY" \ - --placement-strategy "$PLACEMENT_STRATEGY" \ - --seed $SEED - - echo " ${HOST_DS} × ${DONOR_DS} done: $(date)" - done -done - -echo "" -echo "All dataset pairs finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode1_controlled_prevalence.sub b/itrialspace/infra/slurm/trials/mode1_controlled_prevalence.sub deleted file mode 100644 index 0ad5fa2f309cc7635fead3a6d1f7e72e2f7ad4e9..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode1_controlled_prevalence.sub +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M1_Prevalence -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode1_controlled_prevalence.out -#SBATCH --error=logs/mode1_controlled_prevalence.err - -echo "=== iTrialSpace Trial Mode 1: Controlled Prevalence Study ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode1_controlled_prevalence" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# N_CASES=1000 # paper run (commented for 5-case demo) -N_CASES=5 # Total cases in the cohort -PREVALENCE=0.05 # 5% malignancy prevalence (typical NLST-like) -TEMPLATE="NLST" # Trial template for demographics/size distribution -SEED=42 # Random seed for reproducibility - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode controlled_prevalence \ - --output-dir "$OUTPUT_DIR" \ - --n-cases $N_CASES \ - --prevalence $PREVALENCE \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode2_size_detection_curve.sub b/itrialspace/infra/slurm/trials/mode2_size_detection_curve.sub deleted file mode 100644 index 9be10bfd735f8a34636d10bbbadfdedd5c432582..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode2_size_detection_curve.sub +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M2_SizeCurve -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode2_size_detection_curve.out -#SBATCH --error=logs/mode2_size_detection_curve.err - -echo "=== iTrialSpace Trial Mode 2: Size Detection Curve ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode2_size_detection_curve" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Produces 6 manifests (one per size bucket: <5mm, 5-10mm, 10-15mm, 15-20mm, 20-30mm, >30mm) -# N_PER_BUCKET=100 # Cases per size bucket # real run (commented for 5-case smoke test) -N_PER_BUCKET=5 # Cases per size bucket -LABEL=1 # 1=malignant nodules (for FROC detection curves) -TEMPLATE="NLST" # Trial template -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode size_detection_curve \ - --output-dir "$OUTPUT_DIR" \ - --n-per-bucket $N_PER_BUCKET \ - --label $LABEL \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode3_location_sensitivity.sub b/itrialspace/infra/slurm/trials/mode3_location_sensitivity.sub deleted file mode 100644 index 8f6c9ff34db686ab15c6cd263168d61476e516eb..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode3_location_sensitivity.sub +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M3_Location -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode3_location_sensitivity.out -#SBATCH --error=logs/mode3_location_sensitivity.err - -echo "=== iTrialSpace Trial Mode 3: Location Sensitivity ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode3_location_sensitivity" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Produces 5 manifests (one per lobe: RUL, RML, RLL, LUL, LLL) -# Same nodule size range, varies only anatomical location -# N_PER_LOBE=100 # Cases per lobe # real run (commented for 5-case smoke test) -N_PER_LOBE=5 # Cases per lobe -LABEL=1 # 1=malignant -DIAM_MIN=6.0 # Minimum diameter (mm) -DIAM_MAX=15.0 # Maximum diameter (mm) -TEMPLATE="NLST" -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode location_sensitivity \ - --output-dir "$OUTPUT_DIR" \ - --n-per-lobe $N_PER_LOBE \ - --label $LABEL \ - --diam-min $DIAM_MIN \ - --diam-max $DIAM_MAX \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode4_demographic_stratification.sub b/itrialspace/infra/slurm/trials/mode4_demographic_stratification.sub deleted file mode 100644 index ac203e42935cbfefb2988f11e58e0007a80dece6..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode4_demographic_stratification.sub +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M4_DemoStrat -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode4_demographic_stratification.out -#SBATCH --error=logs/mode4_demographic_stratification.err - -echo "=== iTrialSpace Trial Mode 4: Demographic Stratification ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode4_demographic_stratification" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Produces 4 manifests (default strata): -# Stratum 0: Male, 55-65 -# Stratum 1: Male, 65-75 -# Stratum 2: Female, 55-65 -# Stratum 3: Female, 65-75 -# N_PER_STRATUM=200 # Cases per demographic stratum # real run (commented for 5-case smoke test) -N_PER_STRATUM=5 # Cases per demographic stratum -TEMPLATE="NLST" # Trial template for base parameters -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode demographic_strat \ - --output-dir "$OUTPUT_DIR" \ - --n-per-stratum $N_PER_STRATUM \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode5_counterfactual.sub b/itrialspace/infra/slurm/trials/mode5_counterfactual.sub deleted file mode 100644 index 28484e342eeed968030285469fd15e6d4d780cb3..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode5_counterfactual.sub +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M5_Counterfact -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode5_counterfactual.out -#SBATCH --error=logs/mode5_counterfactual.err - -echo "=== iTrialSpace Trial Mode 5: Counterfactual Cohort ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode5_counterfactual" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Same base cohort with one parameter varied across values -# Measures the effect of a single variable on algorithm performance -# N_CASES=500 # Cases per variant # real run (commented for 5-case smoke test) -N_CASES=5 # Cases per variant -TEMPLATE="NLST" -VARY_PARAM="malignancy_prevalence" -VALUES="0.01,0.02,0.05,0.10,0.20" # 5 variants -SEED=42 # Same seed → same base cohort structure - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode counterfactual \ - --output-dir "$OUTPUT_DIR" \ - --n-cases $N_CASES \ - --template "$TEMPLATE" \ - --vary-param "$VARY_PARAM" \ - --values "$VALUES" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode6_cross_dataset.sub b/itrialspace/infra/slurm/trials/mode6_cross_dataset.sub deleted file mode 100644 index 9ffc4943ae483f13f1c00655108e1c39bf2d8ffb..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode6_cross_dataset.sub +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M6_CrossDS -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode6_cross_dataset.out -#SBATCH --error=logs/mode6_cross_dataset.err - -echo "=== iTrialSpace Trial Mode 6: Cross-Dataset Generalization ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode6_cross_dataset" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# One manifest per dataset as sole nodule donor -# Tests whether algorithm performance varies by data source -# N_CASES=300 # real run (commented for 5-case smoke test) -N_CASES=5 -DATASETS="DLCS24,LUNA25,LNDbv4,IMDCT,LUNGx" # 5 datasets -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode cross_dataset \ - --output-dir "$OUTPUT_DIR" \ - --n-cases $N_CASES \ - --datasets "$DATASETS" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode7_bootstrap_confidence.sub b/itrialspace/infra/slurm/trials/mode7_bootstrap_confidence.sub deleted file mode 100644 index fab3a95c289afa1047e00c4e93c00e19332f3d84..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode7_bootstrap_confidence.sub +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M7_Bootstrap -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode7_bootstrap_confidence.out -#SBATCH --error=logs/mode7_bootstrap_confidence.err - -echo "=== iTrialSpace Trial Mode 7: Bootstrap Confidence Intervals ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode7_bootstrap_confidence" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# N independent bootstrap replicates of a base cohort -# Use to compute confidence intervals on algorithm performance metrics -# N_CASES=200 # Cases per replicate # real run (commented for 5-case smoke test) -N_CASES=5 # Cases per replicate -PREVALENCE=0.05 # Base prevalence -# N_BOOTSTRAP=20 # Number of bootstrap replicates # real run (commented for 5-case smoke test) -N_BOOTSTRAP=3 # Number of bootstrap replicates -TEMPLATE="NLST" -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode bootstrap_confidence \ - --output-dir "$OUTPUT_DIR" \ - --n-cases $N_CASES \ - --prevalence $PREVALENCE \ - --n-bootstrap $N_BOOTSTRAP \ - --template "$TEMPLATE" \ - --seed $SEED \ - --no-verify-paths # Skip path check for 100 replicates (too slow) - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode8_algorithm_comparison.sub b/itrialspace/infra/slurm/trials/mode8_algorithm_comparison.sub deleted file mode 100644 index 2f84fc082db3cc8fac47d1f68fcf9c4b491ee009..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode8_algorithm_comparison.sub +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M8_AlgoComp -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode8_algorithm_comparison.out -#SBATCH --error=logs/mode8_algorithm_comparison.err - -echo "=== iTrialSpace Trial Mode 8: Algorithm Comparison ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode8_algorithm_comparison" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Single standardised cohort for head-to-head algorithm comparison -# Fixed seed ensures identical manifest on every run -# Use the same manifest to evaluate multiple CADe/CADx models -# N_CASES=500 # real run (commented for 5-case smoke test) -N_CASES=5 -TEMPLATE="NLST" -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode algorithm_comparison \ - --output-dir "$OUTPUT_DIR" \ - --n-cases $N_CASES \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode9_screening_simulation.sub b/itrialspace/infra/slurm/trials/mode9_screening_simulation.sub deleted file mode 100644 index 3592848d006e5726f7b12502924dffdc65037320..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/mode9_screening_simulation.sub +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTS_M9_Screening -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/mode9_screening_simulation.out -#SBATCH --error=logs/mode9_screening_simulation.err - -echo "=== iTrialSpace Trial Mode 9: Screening Protocol Simulation ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda - -# ── Configuration ────────────────────────────────────────────────────────── -RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" -OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode9_screening_simulation" - -# ── Trial Parameters ────────────────────────────────────────────────────── -# Multi-round screening protocol simulation -# Each round has decreasing malignancy prevalence (cancers caught in -# earlier rounds are removed from later rounds) -# -# With NLST baseline prevalence=0.04 and decay=0.7: -# Round 1: prev=0.040 -# Round 2: prev=0.028 -# Round 3: prev=0.020 -N_ROUNDS=3 -# N_CASES_PER_ROUND=500 # real run (commented for 5-case smoke test) -N_CASES_PER_ROUND=5 -PREVALENCE_DECAY=0.7 # Multiplicative decay per round -TEMPLATE="NLST" -SEED=42 - -# ── Run ──────────────────────────────────────────────────────────────────── -python3 "$RUNNER" \ - --mode screening_simulation \ - --output-dir "$OUTPUT_DIR" \ - --n-rounds $N_ROUNDS \ - --n-cases-per-round $N_CASES_PER_ROUND \ - --prevalence-decay $PREVALENCE_DECAY \ - --template "$TEMPLATE" \ - --seed $SEED - -echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/move_data.sub b/itrialspace/infra/slurm/trials/move_data.sub deleted file mode 100644 index 8c4c46b9faae6a10de78c94318a619518c369be3..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/move_data.sub +++ /dev/null @@ -1,224 +0,0 @@ -#!/bin/bash - -#SBATCH --job-name=iTrialSpace_DataMove -#SBATCH --mail-type=END,FAIL -#SBATCH -p defq -#SBATCH --ntasks=1 -#SBATCH --gpus=0 -#SBATCH --cpus-per-task=4 -#SBATCH --output=logs/move_data.out -#SBATCH --error=logs/move_data.err -#SBATCH --time=24:00:00 - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -echo "=== iTrialSpace Data Reorganisation ===" -echo "Job ID: $SLURM_JOB_ID" -echo "Started: $(date)" - -set -e # Exit on error - -# ── Paths ────────────────────────────────────────────────────────────────── -DATA_ROOT="${ITRIALSPACE_DATA_DIR%/*}" -OLD_SYNLST="$DATA_ROOT/SynLST" -NEW_ROOT="$DATA_ROOT/iTrialSpace" - -# ── Create directory structure ───────────────────────────────────────────── -echo "" -echo ">>> Creating iTrialSpace directory structure..." -mkdir -p "$NEW_ROOT"/{raw_ct,masks,profiles,meta,manifests} - -for DS in DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT; do - mkdir -p "$NEW_ROOT/masks/$DS"/{nodule_seg,combined_seg,organ_seg,refined_seg} -done - -echo "Directory structure created." - -# ══════════════════════════════════════════════════════════════════════════ -# RAW CT SCANS → raw_ct/{DATASET}/ -# ══════════════════════════════════════════════════════════════════════════ -echo "" -echo ">>> Moving raw CT scans..." - -# DLCS24: All_Detection_data/nifti/DLCS24_resampled/ → raw_ct/DLCS24/ -echo " DLCS24..." -mv "$DATA_ROOT/All_Detection_data/nifti/DLCS24_resampled" "$NEW_ROOT/raw_ct/DLCS24" - -# LUNA25: All_Detection_data/nifti/luna25_images_resampled/ → raw_ct/LUNA25/ -echo " LUNA25..." -mv "$DATA_ROOT/All_Detection_data/nifti/luna25_images_resampled" "$NEW_ROOT/raw_ct/LUNA25" - -# LUNA16: Data/LUNA16_resampled/ → raw_ct/LUNA16/ -echo " LUNA16..." -mv "$DATA_ROOT/LUNA16_resampled" "$NEW_ROOT/raw_ct/LUNA16" - -# LUNGx: Data/LUNGx_nifti_resampled/ → raw_ct/LUNGx/ -echo " LUNGx..." -mv "$DATA_ROOT/LUNGx_nifti_resampled" "$NEW_ROOT/raw_ct/LUNGx" - -# LNDbv4: Data/LNDbv4_cts_nifti_resampled/ → raw_ct/LNDbv4/ -echo " LNDbv4..." -mv "$DATA_ROOT/LNDbv4_cts_nifti_resampled" "$NEW_ROOT/raw_ct/LNDbv4" - -# NSCLCR: All_Detection_data/nifti/NSCLC_Radiomics_NIFTI_resampled/ → raw_ct/NSCLCR/ -echo " NSCLCR..." -mv "$DATA_ROOT/All_Detection_data/nifti/NSCLC_Radiomics_NIFTI_resampled" "$NEW_ROOT/raw_ct/NSCLCR" - -# NLST3D: removed due to data quality issues (internal). - -# IMDCT: All_Detection_data/nifti/Intgmultiomics_ct_nifti_resampled/ → raw_ct/IMDCT/ -echo " IMDCT..." -mv "$DATA_ROOT/All_Detection_data/nifti/Intgmultiomics_ct_nifti_resampled" "$NEW_ROOT/raw_ct/IMDCT" - -echo "Raw CT scans moved." - -# ══════════════════════════════════════════════════════════════════════════ -# MASKS → masks/{DATASET}/{type}/ -# ══════════════════════════════════════════════════════════════════════════ -echo "" -echo ">>> Moving masks and segmentations..." - -# --- DLCS24 --- -echo " DLCS24 masks..." -mv "$OLD_SYNLST/DLCS24_v1/DLCS24_KNN_2mm_Extend_RadiomicsSeg" "$NEW_ROOT/masks/DLCS24/nodule_seg" -mv "$OLD_SYNLST/DLCS24_v1/DLCS24_KNN_2mm_Extend_Seg" "$NEW_ROOT/masks/DLCS24/combined_seg" -mv "$OLD_SYNLST/DLCS24_v1/DLCS24_vista3Dauto_organseg" "$NEW_ROOT/masks/DLCS24/organ_seg" -mv "$OLD_SYNLST/DLCS24_v1/DLCS24_refined_seg" "$NEW_ROOT/masks/DLCS24/refined_seg" - -# --- LUNA25 --- -echo " LUNA25 masks..." -mv "$OLD_SYNLST/LUNA25_v1/LUNA25_KNN_2mm_Extend_RadiomicsSeg" "$NEW_ROOT/masks/LUNA25/nodule_seg" -mv "$OLD_SYNLST/LUNA25_v1/LUNA25_KNN_2mm_Extend_Seg" "$NEW_ROOT/masks/LUNA25/combined_seg" -mv "$OLD_SYNLST/LUNA25_v1/LUNA25_vista3Dauto_organseg" "$NEW_ROOT/masks/LUNA25/organ_seg" -mv "$OLD_SYNLST/LUNA25_v1/LUNA25_refined_seg" "$NEW_ROOT/masks/LUNA25/refined_seg" - -# --- LUNA16 --- -echo " LUNA16 masks..." -mv "$OLD_SYNLST/LUNA16_v1/LUNA16_KNN_2mm_Extend_RadiomicsSeg" "$NEW_ROOT/masks/LUNA16/nodule_seg" -mv "$OLD_SYNLST/LUNA16_v1/LUNA16_KNN_2mm_Extend_Seg" "$NEW_ROOT/masks/LUNA16/combined_seg" -mv "$OLD_SYNLST/LUNA16_v1/LUNA16_vista3Dauto_organseg" "$NEW_ROOT/masks/LUNA16/organ_seg" -mv "$OLD_SYNLST/LUNA16_v1/LUNA16_refined_seg" "$NEW_ROOT/masks/LUNA16/refined_seg" - -# --- LUNGx --- -echo " LUNGx masks..." -mv "$OLD_SYNLST/LUNGx_v1/LUNGx_KNN_2mm_Extend_RadiomicsSeg" "$NEW_ROOT/masks/LUNGx/nodule_seg" -mv "$OLD_SYNLST/LUNGx_v1/LUNGx_KNN_2mm_Extend_Seg" "$NEW_ROOT/masks/LUNGx/combined_seg" -mv "$OLD_SYNLST/LUNGx_v1/LUNGx_vista3Dauto_organseg" "$NEW_ROOT/masks/LUNGx/organ_seg" -mv "$OLD_SYNLST/LUNGx_v1/LUNGx_refined_seg" "$NEW_ROOT/masks/LUNGx/refined_seg" - -# --- LNDbv4 --- -echo " LNDbv4 masks..." -mv "$OLD_SYNLST/LNDbv4_v1/LNDbv4_KNN_2mm_Extend_RadiomicsSeg" "$NEW_ROOT/masks/LNDbv4/nodule_seg" -mv "$OLD_SYNLST/LNDbv4_v1/LNDbv4_KNN_2mm_Extend_Seg" "$NEW_ROOT/masks/LNDbv4/combined_seg" -mv "$OLD_SYNLST/LNDbv4_v1/LNDbv4_vista3Dauto_organseg" "$NEW_ROOT/masks/LNDbv4/organ_seg" -mv "$OLD_SYNLST/LNDbv4_v1/LNDbv4_refined_seg" "$NEW_ROOT/masks/LNDbv4/refined_seg" - -# --- NSCLCR --- -echo " NSCLCR masks..." -mv "$OLD_SYNLST/NSCLCR_v1/NSCLCR_org_noduleseg" "$NEW_ROOT/masks/NSCLCR/nodule_seg" -# NSCLCR has no KNN_2mm_Extend_Seg — use org_noduleseg as combined too (symlink) -ln -s "$NEW_ROOT/masks/NSCLCR/nodule_seg" "$NEW_ROOT/masks/NSCLCR/combined_seg_link" 2>/dev/null || true -mv "$OLD_SYNLST/NSCLCR_v1/NSCLCR_vista3Dauto_organseg" "$NEW_ROOT/masks/NSCLCR/organ_seg" -mv "$OLD_SYNLST/NSCLCR_v1/NSCLCR_refined_seg" "$NEW_ROOT/masks/NSCLCR/refined_seg" - -# --- NLST3D: removed due to data quality issues (internal) --- - -# --- IMDCT --- -echo " IMDCT masks..." -mv "$OLD_SYNLST/IMDCT_v1/IMDCT_org_noduleseg" "$NEW_ROOT/masks/IMDCT/nodule_seg" -mv "$OLD_SYNLST/IMDCT_v1/IMDCT_KNN_2mm_Extend_RadiomicsSeg" "$NEW_ROOT/masks/IMDCT/radiomics_seg" -mv "$OLD_SYNLST/IMDCT_v1/IMDCT_KNN_2mm_Extend_Seg" "$NEW_ROOT/masks/IMDCT/combined_seg" -mv "$OLD_SYNLST/IMDCT_v1/IMDCT_vista3Dauto_organseg" "$NEW_ROOT/masks/IMDCT/organ_seg" -mv "$OLD_SYNLST/IMDCT_v1/IMDCT_refined_seg" "$NEW_ROOT/masks/IMDCT/refined_seg" - -echo "Masks moved." - -# ══════════════════════════════════════════════════════════════════════════ -# PROFILE CSVs → profiles/ -# ══════════════════════════════════════════════════════════════════════════ -echo "" -echo ">>> Copying profile CSVs (keeping originals as backup)..." - -for DS in DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT; do - SRC="$OLD_SYNLST/${DS}_v1/${DS}_nodule_profiles.csv" - if [ -f "$SRC" ]; then - cp "$SRC" "$NEW_ROOT/profiles/${DS}_nodule_profiles.csv" - echo " $DS profile CSV copied" - else - echo " WARNING: $SRC not found" - fi -done - -# ══════════════════════════════════════════════════════════════════════════ -# METADATA CSVs → meta/ -# ══════════════════════════════════════════════════════════════════════════ -echo "" -echo ">>> Copying metadata CSVs..." - -for DS in DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT; do - # Find the metadata CSV (pattern: *_dataset_*_FIT_*.csv or *_BMdataset_*.csv) - META=$(ls "$OLD_SYNLST/${DS}_v1/"*dataset*FIT*.csv "$OLD_SYNLST/${DS}_v1/"*BMdataset*.csv 2>/dev/null | head -1) - if [ -n "$META" ]; then - BASENAME=$(basename "$META") - cp "$META" "$NEW_ROOT/meta/$BASENAME" - echo " $DS: $BASENAME" - else - echo " WARNING: No metadata CSV found for $DS" - fi -done - -# ══════════════════════════════════════════════════════════════════════════ -# SHARED FILES -# ══════════════════════════════════════════════════════════════════════════ -echo "" -echo ">>> Copying shared files..." -cp "$OLD_SYNLST/label_dict.json" "$NEW_ROOT/" 2>/dev/null || true -cp "$OLD_SYNLST/totalsegmentator_label_dict.json" "$NEW_ROOT/" 2>/dev/null || true -cp "$OLD_SYNLST/vista_label_dict.json" "$NEW_ROOT/" 2>/dev/null || true - -# ══════════════════════════════════════════════════════════════════════════ -# VERIFICATION -# ══════════════════════════════════════════════════════════════════════════ -echo "" -echo ">>> Verifying..." -echo "" -echo "Directory structure:" -find "$NEW_ROOT" -maxdepth 3 -type d | sort - -echo "" -echo "File counts per directory:" -for DIR in raw_ct masks profiles meta; do - COUNT=$(find "$NEW_ROOT/$DIR" -type f | wc -l) - echo " $DIR/: $COUNT files" -done - -echo "" -echo "Per-dataset raw_ct counts:" -for DS in DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT; do - COUNT=$(find "$NEW_ROOT/raw_ct/$DS" -type f 2>/dev/null | wc -l) - echo " $DS: $COUNT CT files" -done - -echo "" -echo "Per-dataset mask counts:" -for DS in DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT; do - for TYPE in nodule_seg combined_seg organ_seg refined_seg; do - COUNT=$(find "$NEW_ROOT/masks/$DS/$TYPE" -type f 2>/dev/null | wc -l) - if [ "$COUNT" -gt 0 ]; then - echo " $DS/$TYPE: $COUNT files" - fi - done -done - -echo "" -echo "=== Data move complete ===" -echo "Finished: $(date)" -echo "" -echo "IMPORTANT: Do NOT delete old directories until Python verification passes." -echo "Next steps:" -echo " 1. Run the ct_path update script on the profile CSVs" -echo " 2. Update paths.yaml to point to the new layout" -echo " 3. Run verification: python -c 'from itrialspace import NoduleIndex; ...'" diff --git a/itrialspace/infra/slurm/trials/submit_all.sh b/itrialspace/infra/slurm/trials/submit_all.sh deleted file mode 100644 index b29bf7d1f89f1e6b65a44c9f4895fac3802311f1..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/trials/submit_all.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash -# Submit all iTrialSpace trial mode jobs to SLURM -# -# Usage: -# ./submit_all.sh # submit all modes -# ./submit_all.sh 1 3 8 # submit only modes 1, 3, 8 -# -# Each mode runs independently — no dependencies between jobs. - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -cd "$SCRIPT_DIR" - -# Ensure logs directory exists -mkdir -p logs - -MODES=( - "mode1_controlled_prevalence" - "mode2_size_detection_curve" - "mode3_location_sensitivity" - "mode4_demographic_stratification" - "mode5_counterfactual" - "mode6_cross_dataset" - "mode7_bootstrap_confidence" - "mode8_algorithm_comparison" - "mode9_screening_simulation" - "mode10_multi_nodule_realism" - "mode11_digital_twin_isolation" - "mode12_digital_twin_complete" - "mode13_digital_twin_cross" -) - -if [ $# -eq 0 ]; then - # Submit all - echo "Submitting all ${#MODES[@]} trial modes..." - for mode in "${MODES[@]}"; do - echo -n " $mode: " - sbatch "${mode}.sub" - done -else - # Submit selected modes - echo "Submitting selected trial modes..." - for num in "$@"; do - idx=$((num - 1)) - if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then - mode="${MODES[$idx]}" - echo -n " $mode: " - sbatch "${mode}.sub" - else - echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" - fi - done -fi - -echo "" -echo "Check status with: squeue -u $USER" -echo "Check logs in: $SCRIPT_DIR/logs/" diff --git a/itrialspace/infra/slurm/vlm_eval/ext_build_sharded.sub b/itrialspace/infra/slurm/vlm_eval/ext_build_sharded.sub deleted file mode 100644 index 6ea751db67fa8ddcf07ded6599a5eb29b596af9e..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/ext_build_sharded.sub +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_bext -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=1 -#SBATCH --mem=16G -#SBATCH --array=0-7 -#SBATCH --output=logs/VLR_bext_%A_%a.out -#SBATCH --error=logs/VLR_bext_%A_%a.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Sharded Ext Build — 8 parallel jobs ───────────────────────────────────── -# Each array task processes a shard of manifests for BOTH profiles. -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/ext_build_sharded.sub -# ───────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -SHARD_FILE="${PROJ_DIR}/src/itrialspace/evaluation/vlm_eval/ext_shards/shard_${SLURM_ARRAY_TASK_ID}.txt" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Read manifest paths from shard file ────────────────────────────────────── -MANIFEST_ARGS="" -while IFS= read -r line; do - [[ -n "${line}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${line}" -done < "${SHARD_FILE}" - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -echo "===============================================" -echo "Sharded Ext Build — Shard ${SLURM_ARRAY_TASK_ID}/7" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_ARRAY_JOB_ID}_${SLURM_ARRAY_TASK_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Build lung_axial profile ───────────────────────────────────────────────── -PROFILE="lung_axial" -OUTDIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}_s${SLURM_ARRAY_TASK_ID}" - -echo "" -echo ">>> Profile: ${PROFILE} → ${OUTDIR}" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${OUTDIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing \ - --workers 1 - -echo "${PROFILE} shard ${SLURM_ARRAY_TASK_ID} done: ${OUTDIR}/eval_dataset.csv" - -# ── Build lung_axial_medgemma profile ──────────────────────────────────────── -PROFILE="lung_axial_medgemma" -OUTDIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}_s${SLURM_ARRAY_TASK_ID}" - -echo "" -echo ">>> Profile: ${PROFILE} → ${OUTDIR}" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${OUTDIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing \ - --workers 1 - -echo "${PROFILE} shard ${SLURM_ARRAY_TASK_ID} done: ${OUTDIR}/eval_dataset.csv" -echo "" -echo "All profiles done for shard ${SLURM_ARRAY_TASK_ID} at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/ext_merge_shards.sub b/itrialspace/infra/slurm/vlm_eval/ext_merge_shards.sub deleted file mode 100644 index aa7f7b6ab2e88d13c78e150df8ae9dcaa4a82ed3..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/ext_merge_shards.sub +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_merge -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=1 -#SBATCH --mem=4G -#SBATCH --output=logs/VLR_merge_%j.out -#SBATCH --error=logs/VLR_merge_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Merge 8 sharded ext builds into final layout ──────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch --dependency=afterok: vlm_evaluation/ext_merge_shards.sub -# ───────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" - -cd "${PROJ_DIR}" - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "Merging 8 ext build shards" -echo " Host: $(hostname)" -echo " Time: $(date)" -echo "===============================================" - -python3 -c " -import pandas as pd -import os, glob, shutil - -DATA_BASE = '${DATA_BASE}' - -for profile in ('lung_axial', 'lung_axial_medgemma'): - final_dir = os.path.join(DATA_BASE, 'vlm_eval_ext', profile) - os.makedirs(final_dir, exist_ok=True) - - dfs = [] - for shard_id in range(8): - shard_dir = os.path.join(DATA_BASE, 'vlm_eval_ext', f'{profile}_s{shard_id}') - csv_path = os.path.join(shard_dir, 'eval_dataset.csv') - if os.path.isfile(csv_path): - df = pd.read_csv(csv_path) - dfs.append(df) - print(f' {profile} shard {shard_id}: {len(df)} rows') - else: - print(f' WARNING: {csv_path} not found!') - - if dfs: - merged = pd.concat(dfs, ignore_index=True) - # Sort for deterministic order - merged = merged.sort_values(['mode', 'trial_name', 'case_id']).reset_index(drop=True) - out_csv = os.path.join(final_dir, 'eval_dataset.csv') - merged.to_csv(out_csv, index=False) - print(f'{profile}: merged {len(merged)} rows -> {out_csv}') - else: - print(f'WARNING: No shards found for {profile}!') - -print() -print('Merge complete at', pd.Timestamp.now()) -" - -echo "" -echo "Merge done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/m13_missing_rerun.sub b/itrialspace/infra/slurm/vlm_eval/m13_missing_rerun.sub deleted file mode 100644 index 09107920309fa9c84f3424515c4d587fcd5593f9..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/m13_missing_rerun.sub +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_m13fix -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=24G -#SBATCH --output=logs/VLR_m13fix_%j.out -#SBATCH --error=logs/VLR_m13fix_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── M13 Missing Slice Re-run ───────────────────────────────────────────────── -# Re-extracts the 1,550 Mode-13 CTs that were never sliced. -# -# Background: 9,378 M13 synthetic CTs exist on disk but only 7,828 unique -# ct_paths appear in vlm_eval_ext/lung_axial/eval_dataset.csv. The 14 cross- -# pair sub-trials below account for all 1,550 missing cases: -# -# LNDbv4_x_NSCLCR 214 LUNGx_x_NSCLCR 201 LUNA25_x_NSCLCR 201 -# DLCS24_x_NSCLCR 199 LUNA16_x_NSCLCR 197 IMDCT_x_NSCLCR 189 -# LNDbv4_x_IMDCT 83 LNDbv4_x_LUNA25 81 LNDbv4_x_LUNA16 81 -# LNDbv4_x_DLCS24 81 LUNA25_x_IMDCT 6 LUNA16_x_IMDCT 6 -# DLCS24_x_IMDCT 6 LUNGx_x_IMDCT 5 -# -# --skip-existing reads the existing eval_dataset.csv and skips any ct_path -# whose plain PNG is already on disk, so only the 1,550 missing cases are -# processed. Overlays (bbox/contour/bbox_contour) are generated together. -# -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/m13_missing_rerun.sub -# -# After completion, re-submit VLM inference jobs for the new rows: -# sbatch --dependency=afterok: vlm_evaluation/vlm_cond_biomedclip_ext.sub -# sbatch --dependency=afterok: vlm_evaluation/vlm_cond_llava_med_ext.sub -# sbatch --dependency=afterok: vlm_evaluation/vlm_cond_medgemma_ext.sub -# ───────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -MANIFEST_ROOT="${DATA_BASE}/manifests/mode13_digital_twin_cross" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "M13 Missing Slice Re-run" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Collect all 42 mode13 manifests ───────────────────────────────────────── -MANIFEST_ARGS="" -for mpath in "${MANIFEST_ROOT}"/*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) -echo " Mode-13 manifests found: ${NCSV}" - -if [[ ${NCSV} -eq 0 ]]; then - echo "ERROR: No mode13 manifests found under ${MANIFEST_ROOT}" - exit 1 -fi - -# ── Profile 1: lung_axial ───────────────────────────────────────────────────── -PROFILE="lung_axial" -OUTDIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}" -echo "" -echo ">>> Profile: ${PROFILE} → ${OUTDIR}" -echo " (--skip-existing: only the ~1,550 missing cases will be processed)" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${OUTDIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing \ - --workers "${SLURM_CPUS_PER_TASK:-4}" - -echo "${PROFILE} done at $(date)" -echo " Dataset: ${OUTDIR}/eval_dataset.csv" - -# ── Profile 2: lung_axial_medgemma ─────────────────────────────────────────── -PROFILE="lung_axial_medgemma" -OUTDIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}" -echo "" -echo ">>> Profile: ${PROFILE} → ${OUTDIR}" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${OUTDIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing \ - --workers "${SLURM_CPUS_PER_TASK:-4}" - -echo "${PROFILE} done at $(date)" -echo " Dataset: ${OUTDIR}/eval_dataset.csv" - -# ── Summary ─────────────────────────────────────────────────────────────────── -echo "" -echo "===============================================" -echo "Re-run complete at $(date)" -echo "" -echo "New M13 row counts:" -python3 -c " -import pandas as pd -BASE = '${DATA_BASE}/vlm_eval_ext' -for profile in ('lung_axial', 'lung_axial_medgemma'): - csv = f'{BASE}/{profile}/eval_dataset.csv' - try: - df = pd.read_csv(csv) - m13 = df[df['mode'] == 'digital_twin_cross'] - print(f' {profile}: total={len(df)}, M13_rows={len(m13)}, M13_unique_cts={m13[\"ct_path\"].nunique()}') - except Exception as e: - print(f' {profile}: ERROR reading {csv}: {e}') -" -echo "===============================================" diff --git a/itrialspace/infra/slurm/vlm_eval/run_ext_reeval_parallel.sh b/itrialspace/infra/slurm/vlm_eval/run_ext_reeval_parallel.sh deleted file mode 100644 index 58401359f525f5b645851dcafb79b66bc01c5284..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/run_ext_reeval_parallel.sh +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ── Extended Modes VLM Re-Evaluation — Parallel 6-GPU Plan ─────────────────── -# Submit from: ${PROJ_DIR} -# Usage: bash vlm_evaluation/run_ext_reeval_parallel.sh -# -# Re-runs ALL ext VLM evaluation (M7, M11-M13) on the rebuilt Apr 13 dataset. -# Old results (Apr 9, ~9,448 rows) are stale — dataset now has 33,471 cases. -# -# GPU Allocation (6 total): -# node001 (5 GPUs): -# GPU1: LLaVA-Med plain (~2 hrs) -# GPU2: LLaVA-Med bbox (~2 hrs) -# GPU3: LLaVA-Med contour (~2 hrs) -# GPU4: LLaVA-Med bbox_ctr (~2 hrs) -# GPU5: BiomedCLIP all 4 (~1.25 hrs) -# node003 (1 GPU): -# GPU6: MedGemma all 4 (~2.5 hrs) -# -# Total wall time: ~2.5 hrs (vs ~12 hrs sequential) -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJ_DIR="$(dirname "${SCRIPT_DIR}")" -cd "${PROJ_DIR}" - -DATA_BASE="${ITRIALSPACE_OUTPUT_DIR}/vlm_eval_ext" - -echo "============================================================" -echo " EXT VLM Re-Evaluation — Parallel 6-GPU Plan" -echo " Dataset: 33,471 cases (M7, M11-13)" -echo " GPUs: 5 × node001 + 1 × node003" -echo " Working dir: ${PROJ_DIR}" -echo " Time: $(date)" -echo "============================================================" - -# ── Pre-flight: archive stale results ───────────────────────────────────────── -ARCHIVE_TAG="stale_$(date +%Y%m%d_%H%M%S)" - -for vlm_dir in "${DATA_BASE}/lung_axial/biomedclip" \ - "${DATA_BASE}/lung_axial/llava_med" \ - "${DATA_BASE}/lung_axial_medgemma/medgemma"; do - if [[ -d "${vlm_dir}" ]]; then - # Archive only the result CSVs, not the directory structure - for csv in $(find "${vlm_dir}" -name "*_results.csv" 2>/dev/null); do - archive_dir="$(dirname "${csv}")/${ARCHIVE_TAG}" - mkdir -p "${archive_dir}" - mv "${csv}" "${archive_dir}/" - echo " Archived: ${csv} -> ${archive_dir}/" - done - fi -done -echo "" - -# ── node001: 4 LLaVA-Med per-condition jobs (GPUs 1-4) ────────────────────── -echo "Submitting LLaVA-Med (4 conditions parallel on node001)..." - -LLAVA_JOBS=() -for cond in plain bbox contour bbox_contour; do - JOB=$(sbatch --parsable \ - --nodelist=node001 \ - --export=ALL,CONDITION=${cond} \ - infra/slurm/vlm_eval/vlm_ext_llava_single_cond.sub) - LLAVA_JOBS+=("${JOB}") - echo " Job ${JOB}: LLaVA-Med ${cond} (node001)" -done - -# ── node001: BiomedCLIP all conditions (GPU 5) ────────────────────────────── -echo "" -echo "Submitting BiomedCLIP (all 4 conditions on node001)..." - -BIOMED_JOB=$(sbatch --parsable \ - --nodelist=node001 \ - infra/slurm/vlm_eval/vlm_cond_biomedclip_ext.sub) -echo " Job ${BIOMED_JOB}: BiomedCLIP all conditions (node001)" - -# ── node003: MedGemma all conditions (GPU 6) ──────────────────────────────── -echo "" -echo "Submitting MedGemma (all 4 conditions on node003)..." - -MEDGEM_JOB=$(sbatch --parsable \ - --nodelist=node003 \ - infra/slurm/vlm_eval/vlm_cond_medgemma_ext.sub) -echo " Job ${MEDGEM_JOB}: MedGemma all conditions (node003)" - -# ── Cross-model comparison (after all inference) ──────────────────────────── -ALL_DEPS="${LLAVA_JOBS[0]}:${LLAVA_JOBS[1]}:${LLAVA_JOBS[2]}:${LLAVA_JOBS[3]}:${BIOMED_JOB}:${MEDGEM_JOB}" - -echo "" -echo "Submitting cross-model comparison (after all Stage 2)..." - -CMP_JOB=$(sbatch --parsable \ - --dependency=afterok:${ALL_DEPS} \ - infra/slurm/vlm_eval/vlm_cross_comparison_ext.sub) -echo " Job ${CMP_JOB}: cross-model comparison" - -# ── LLaVA-Med per-model comparison (after all 4 conditions done) ──────────── -LLAVA_DEP="${LLAVA_JOBS[0]}:${LLAVA_JOBS[1]}:${LLAVA_JOBS[2]}:${LLAVA_JOBS[3]}" - -LLAVA_CMP_JOB=$(sbatch --parsable \ - --dependency=afterok:${LLAVA_DEP} \ - --partition=defq \ - --ntasks=1 --cpus-per-task=2 --mem=8G \ - --job-name=VLX_lcmp \ - --output=logs/VLX_lcmp_%j.out \ - --error=logs/VLX_lcmp_%j.err \ - --wrap="cd ${PROJ_DIR} && \ -itrialspace_activate_conda && \ -export PYTHONPATH='${PROJ_DIR}:\${PYTHONPATH:-}' && \ -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir '${DATA_BASE}/lung_axial/llava_med' \ - --conditions plain bbox contour bbox_contour \ - --model-name 'LLaVA-Med'") -echo " Job ${LLAVA_CMP_JOB}: LLaVA-Med comparison (after all 4 conditions)" - -# ── Summary ────────────────────────────────────────────────────────────────── -echo "" -echo "============================================================" -echo " EXT VLM Re-Evaluation — All jobs submitted!" -echo "" -echo " node001 (5 GPUs):" -echo " LLaVA-Med plain: ${LLAVA_JOBS[0]}" -echo " LLaVA-Med bbox: ${LLAVA_JOBS[1]}" -echo " LLaVA-Med contour: ${LLAVA_JOBS[2]}" -echo " LLaVA-Med bbox_contour: ${LLAVA_JOBS[3]}" -echo " BiomedCLIP (all 4): ${BIOMED_JOB}" -echo "" -echo " node003 (1 GPU):" -echo " MedGemma (all 4): ${MEDGEM_JOB}" -echo "" -echo " Post-inference:" -echo " LLaVA-Med comparison: ${LLAVA_CMP_JOB}" -echo " Cross-model comparison: ${CMP_JOB}" -echo "" -echo " Estimated wall time: ~2.5 hrs" -echo " Monitor: squeue -u \$USER" -echo " Logs: logs/VLX_*_{JOBID}.{out,err}" -echo "============================================================" diff --git a/itrialspace/infra/slurm/vlm_eval/run_extended_modes_pipeline.sh b/itrialspace/infra/slurm/vlm_eval/run_extended_modes_pipeline.sh deleted file mode 100644 index 64fb698d07e7b95ab7103998ab407f90d085e7b4..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/run_extended_modes_pipeline.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ── Extended Modes Pipeline Orchestrator ────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: bash vlm_evaluation/run_extended_modes_pipeline.sh -# -# Runs VLM evaluation for modes 7, 11, 12, 13 (bootstrap + digital twin) -# that were not in the original mode 1-10 run. -# -# Total cases: ~32,500 (mode7=3913, mode11=10755, mode12=8875, mode13=8973) -# Output base: vlm_eval_ext/ (separate from vlm_eval/ to preserve mode 1-10) -# -# Dependencies: -# 1a ──→ BiomedCLIP ──┐ -# 1a ──→ LLaVA-Med ──┼──→ Cross-model comparison -# 1b ──→ MedGemma ──┘ -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJ_DIR="$(dirname "${SCRIPT_DIR}")" -cd "${PROJ_DIR}" - -echo "============================================================" -echo " Extended Modes VLM Evaluation Pipeline" -echo " Modes: 7 (bootstrap), 11-13 (digital twin)" -echo " Working dir: ${PROJ_DIR}" -echo " Time: $(date)" -echo "============================================================" - -# ── Stage 1a: Build overlay dataset — lung_axial (CPU) ─────────────────────── -echo "" -echo "Stage 1a: lung_axial overlay build..." -STD_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_overlay_build_std_ext.sub) -echo " Job ${STD_JOB}: vlm_overlay_build_std_ext.sub" - -# ── Stage 1b: Build overlay dataset — lung_axial_medgemma (CPU) ────────────── -echo "" -echo "Stage 1b: lung_axial_medgemma overlay build..." -MG_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_overlay_build_medgemma_ext.sub) -echo " Job ${MG_JOB}: vlm_overlay_build_medgemma_ext.sub" - -# ── Stage 2: Per-model condition evaluation (GPU, parallel) ────────────────── -echo "" -echo "Stage 2: Per-model condition jobs..." - -BIOMED_JOB=$(sbatch --parsable --dependency=afterok:${STD_JOB} \ - --nodelist=node001 \ - infra/slurm/vlm_eval/vlm_cond_biomedclip_ext.sub) -echo " Job ${BIOMED_JOB}: BiomedCLIP (after ${STD_JOB})" - -LLAVA_JOB=$(sbatch --parsable --dependency=afterok:${STD_JOB} \ - --nodelist=node001 \ - infra/slurm/vlm_eval/vlm_cond_llava_med_ext.sub) -echo " Job ${LLAVA_JOB}: LLaVA-Med (after ${STD_JOB})" - -MEDGEM_JOB=$(sbatch --parsable --dependency=afterok:${MG_JOB} \ - --nodelist=node001 \ - infra/slurm/vlm_eval/vlm_cond_medgemma_ext.sub) -echo " Job ${MEDGEM_JOB}: MedGemma (after ${MG_JOB})" - -# ── Stage 3: Cross-model comparison (CPU) ──────────────────────────────────── -echo "" -echo "Stage 3: Cross-model comparison (after all Stage 2)..." -CMP_JOB=$(sbatch --parsable \ - --dependency=afterok:${BIOMED_JOB}:${LLAVA_JOB}:${MEDGEM_JOB} \ - infra/slurm/vlm_eval/vlm_cross_comparison_ext.sub) -echo " Job ${CMP_JOB}: cross-model comparison" - -# ── Summary ────────────────────────────────────────────────────────────────── -echo "" -echo "============================================================" -echo " Extended Modes Pipeline submitted!" -echo "" -echo " Stage 1a (lung_axial build): ${STD_JOB}" -echo " Stage 1b (medgemma build): ${MG_JOB}" -echo " Stage 2 (BiomedCLIP): ${BIOMED_JOB}" -echo " Stage 2 (LLaVA-Med): ${LLAVA_JOB}" -echo " Stage 2 (MedGemma): ${MEDGEM_JOB}" -echo " Stage 3 (cross-model compare): ${CMP_JOB}" -echo "" -echo " Output: ${ITRIALSPACE_OUTPUT_DIR}/vlm_eval_ext/" -echo " Monitor: squeue -u \$USER" -echo " Logs: logs/VLX_*_{JOBID}.{out,err}" -echo "============================================================" diff --git a/itrialspace/infra/slurm/vlm_eval/run_postfix_rerun_pipeline.sh b/itrialspace/infra/slurm/vlm_eval/run_postfix_rerun_pipeline.sh deleted file mode 100644 index d1f53e8813e2dfa6f6509c7c5b1f7889d3d8c1db..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/run_postfix_rerun_pipeline.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ── Post-Fix VLM Rerun Pipeline ────────────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: bash vlm_evaluation/run_postfix_rerun_pipeline.sh -# -# Rebuilds VLM evaluation datasets with --skip-existing to pick up newly -# generated synthetic CTs from the April 2026 pipeline fixes, then re-runs -# all 3 VLMs and cross-model comparison. -# -# Uses two output directories (same as original): -# vlm_eval/ → modes 1-6, 8-10 (~9,400+ cases) -# vlm_eval_ext/ → modes 7, 11-13 (~9,400+ cases) -# -# With --skip-existing, only the ~2,500 new CTs need NIfTI loading. -# Existing PNGs and metadata are reused from the prior eval_dataset.csv. -# -# Dependencies: -# 1a (std build) ──→ BiomedCLIP ──┐ -# 1a (std build) ──→ LLaVA-Med ──┼──→ Per-dataset comparison -# 1b (mg build) ──→ MedGemma ──┘ -# (same for ext) -# All comparisons ──→ Cross-model comparison -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJ_DIR="$(dirname "${SCRIPT_DIR}")" -cd "${PROJ_DIR}" - -echo "============================================================" -echo " Post-Fix VLM Rerun Pipeline" -echo " Working dir: ${PROJ_DIR}" -echo " Time: $(date)" -echo "============================================================" - -# ── Stage 1: Rebuild eval datasets with skip-existing (CPU) ───────────────── -echo "" -echo "Stage 1: Rebuilding eval datasets (skip-existing)..." - -# M1-6, 8-10: lung_axial -STD_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_postfix_build_std.sub) -echo " Job ${STD_JOB}: vlm_postfix_build_std.sub (M1-6, 8-10 lung_axial)" - -# M1-6, 8-10: lung_axial_medgemma -MG_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_postfix_build_medgemma.sub) -echo " Job ${MG_JOB}: vlm_postfix_build_medgemma.sub (M1-6, 8-10 medgemma)" - -# M7, 11-13: lung_axial -STD_EXT_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_postfix_build_std_ext.sub) -echo " Job ${STD_EXT_JOB}: vlm_postfix_build_std_ext.sub (M7, 11-13 lung_axial)" - -# M7, 11-13: lung_axial_medgemma -MG_EXT_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_postfix_build_medgemma_ext.sub) -echo " Job ${MG_EXT_JOB}: vlm_postfix_build_medgemma_ext.sub (M7, 11-13 medgemma)" - -# ── Stage 2: VLM inference (GPU) ──────────────────────────────────────────── -echo "" -echo "Stage 2: VLM inference jobs..." - -# --- M1-6, 8-10 --- -BIOMED_JOB=$(sbatch --parsable --dependency=afterok:${STD_JOB} \ - infra/slurm/vlm_eval/vlm_cond_biomedclip.sub) -echo " Job ${BIOMED_JOB}: BiomedCLIP M1-10 (after ${STD_JOB})" - -LLAVA_JOB=$(sbatch --parsable --dependency=afterok:${STD_JOB} \ - infra/slurm/vlm_eval/vlm_cond_llava_med.sub) -echo " Job ${LLAVA_JOB}: LLaVA-Med M1-10 (after ${STD_JOB})" - -MEDGEM_JOB=$(sbatch --parsable --dependency=afterok:${MG_JOB} \ - infra/slurm/vlm_eval/vlm_cond_medgemma.sub) -echo " Job ${MEDGEM_JOB}: MedGemma M1-10 (after ${MG_JOB})" - -# --- M7, 11-13 --- -BIOMED_EXT_JOB=$(sbatch --parsable --dependency=afterok:${STD_EXT_JOB} \ - infra/slurm/vlm_eval/vlm_cond_biomedclip_ext.sub) -echo " Job ${BIOMED_EXT_JOB}: BiomedCLIP ext (after ${STD_EXT_JOB})" - -LLAVA_EXT_JOB=$(sbatch --parsable --dependency=afterok:${STD_EXT_JOB} \ - infra/slurm/vlm_eval/vlm_cond_llava_med_ext.sub) -echo " Job ${LLAVA_EXT_JOB}: LLaVA-Med ext (after ${STD_EXT_JOB})" - -MEDGEM_EXT_JOB=$(sbatch --parsable --dependency=afterok:${MG_EXT_JOB} \ - infra/slurm/vlm_eval/vlm_cond_medgemma_ext.sub) -echo " Job ${MEDGEM_EXT_JOB}: MedGemma ext (after ${MG_EXT_JOB})" - -# ── Stage 3: Per-dataset comparison (CPU) ──────────────────────────────────── -echo "" -echo "Stage 3: Cross-model comparison..." - -CMP_JOB=$(sbatch --parsable \ - --dependency=afterok:${BIOMED_JOB}:${LLAVA_JOB}:${MEDGEM_JOB} \ - infra/slurm/vlm_eval/vlm_cross_comparison.sub) -echo " Job ${CMP_JOB}: cross-model M1-10" - -CMP_EXT_JOB=$(sbatch --parsable \ - --dependency=afterok:${BIOMED_EXT_JOB}:${LLAVA_EXT_JOB}:${MEDGEM_EXT_JOB} \ - infra/slurm/vlm_eval/vlm_cross_comparison_ext.sub) -echo " Job ${CMP_EXT_JOB}: cross-model ext" - -# ── Summary ────────────────────────────────────────────────────────────────── -echo "" -echo "============================================================" -echo " Post-Fix VLM Rerun Pipeline Submitted!" -echo "" -echo " Stage 1 (data builds):" -echo " ${STD_JOB} M1-10 lung_axial" -echo " ${MG_JOB} M1-10 medgemma" -echo " ${STD_EXT_JOB} ext lung_axial" -echo " ${MG_EXT_JOB} ext medgemma" -echo "" -echo " Stage 2 (VLM inference):" -echo " ${BIOMED_JOB} BiomedCLIP M1-10" -echo " ${LLAVA_JOB} LLaVA-Med M1-10" -echo " ${MEDGEM_JOB} MedGemma M1-10" -echo " ${BIOMED_EXT_JOB} BiomedCLIP ext" -echo " ${LLAVA_EXT_JOB} LLaVA-Med ext" -echo " ${MEDGEM_EXT_JOB} MedGemma ext" -echo "" -echo " Stage 3 (comparison):" -echo " ${CMP_JOB} cross-model M1-10" -echo " ${CMP_EXT_JOB} cross-model ext" -echo "" -echo " Monitor: squeue -u \$USER" -echo " Logs: logs/VLR_*_{JOBID}.{out,err}" -echo "============================================================" diff --git a/itrialspace/infra/slurm/vlm_eval/run_real_ct_pipeline.sh b/itrialspace/infra/slurm/vlm_eval/run_real_ct_pipeline.sh deleted file mode 100644 index 768d35305e83a9eac3e6b877511d689a38870b62..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/run_real_ct_pipeline.sh +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ── Real CT Spatial Guidance Pipeline Orchestrator ──────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: bash vlm_evaluation/run_real_ct_pipeline.sh -# -# Submits the full 5-stage pipeline for real CT evaluation with SLURM -# dependencies, mirroring the synthetic pipeline structure: -# -# Stage 1a (CPU): Build overlay dataset — lung_axial (BiomedCLIP + LLaVA-Med) -# Stage 1b (CPU): Build overlay dataset — lung_axial_medgemma (MedGemma) -# -# Stage 2 (GPU): Run each model under all 4 conditions (parallel) -# → BiomedCLIP depends on 1a -# → LLaVA-Med depends on 1a -# → MedGemma depends on 1b -# -# Stage 3 (CPU): Cross-model comparison -# -# Dependencies: -# 1a ──→ BiomedCLIP ──┐ -# 1a ──→ LLaVA-Med ──┼──→ Cross-model comparison -# 1b ──→ MedGemma ──┘ -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJ_DIR="$(dirname "${SCRIPT_DIR}")" -cd "${PROJ_DIR}" - -echo "============================================================" -echo " Real CT VLM Evaluation Pipeline" -echo " Working dir: ${PROJ_DIR}" -echo " Time: $(date)" -echo "============================================================" - -# ── Stage 1a: Build overlay dataset — lung_axial (CPU) ─────────────────────── -echo "" -echo "Stage 1a: Submitting lung_axial overlay build (BiomedCLIP + LLaVA-Med)..." -STD_DATA_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_real_overlay_build_std.sub) -echo " Job ${STD_DATA_JOB}: vlm_real_overlay_build_std.sub" - -# ── Stage 1b: Build overlay dataset — lung_axial_medgemma (CPU) ────────────── -echo "" -echo "Stage 1b: Submitting lung_axial_medgemma overlay build (MedGemma)..." -MG_DATA_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_real_overlay_build_medgemma.sub) -echo " Job ${MG_DATA_JOB}: vlm_real_overlay_build_medgemma.sub" - -# ── Stage 2: Per-model condition evaluation (GPU, parallel) ────────────────── -echo "" -echo "Stage 2: Submitting per-model condition jobs..." - -BIOMED_JOB=$(sbatch --parsable --dependency=afterok:${STD_DATA_JOB} \ - infra/slurm/vlm_eval/vlm_real_cond_biomedclip.sub) -echo " Job ${BIOMED_JOB}: vlm_real_cond_biomedclip.sub (after ${STD_DATA_JOB})" - -LLAVA_JOB=$(sbatch --parsable --dependency=afterok:${STD_DATA_JOB} \ - infra/slurm/vlm_eval/vlm_real_cond_llava_med.sub) -echo " Job ${LLAVA_JOB}: vlm_real_cond_llava_med.sub (after ${STD_DATA_JOB})" - -MEDGEM_JOB=$(sbatch --parsable --dependency=afterok:${MG_DATA_JOB} \ - infra/slurm/vlm_eval/vlm_real_cond_medgemma.sub) -echo " Job ${MEDGEM_JOB}: vlm_real_cond_medgemma.sub (after ${MG_DATA_JOB})" - -# ── Stage 3: Cross-model comparison (CPU) ──────────────────────────────────── -echo "" -echo "Stage 3: Submitting cross-model comparison (after all Stage 2)..." -CMP_JOB=$(sbatch --parsable \ - --dependency=afterok:${BIOMED_JOB}:${LLAVA_JOB}:${MEDGEM_JOB} \ - infra/slurm/vlm_eval/vlm_real_cross_comparison.sub) -echo " Job ${CMP_JOB}: vlm_real_cross_comparison.sub" - -# ── Summary ────────────────────────────────────────────────────────────────── -echo "" -echo "============================================================" -echo " Real CT Pipeline submitted!" -echo "" -echo " Stage 1a (lung_axial data): ${STD_DATA_JOB}" -echo " Stage 1b (lung_axial_medgemma data): ${MG_DATA_JOB}" -echo " Stage 2 (BiomedCLIP): ${BIOMED_JOB}" -echo " Stage 2 (LLaVA-Med): ${LLAVA_JOB}" -echo " Stage 2 (MedGemma): ${MEDGEM_JOB}" -echo " Stage 3 (cross-model compare): ${CMP_JOB}" -echo "" -echo " Monitor: squeue -u \$USER" -echo " Logs: logs/VLR_*_{JOBID}.{out,err}" -echo " Results: ${ITRIALSPACE_OUTPUT_DIR}/vlm_eval_real/" -echo "============================================================" diff --git a/itrialspace/infra/slurm/vlm_eval/run_spatial_guidance_pipeline.sh b/itrialspace/infra/slurm/vlm_eval/run_spatial_guidance_pipeline.sh deleted file mode 100644 index 36fd244c24b70b7c03d6ad7d62845108448b317a..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/run_spatial_guidance_pipeline.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ── Spatial Guidance Pipeline Orchestrator ──────────────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: bash vlm_evaluation/run_spatial_guidance_pipeline.sh -# -# Submits the full 5-stage pipeline with SLURM dependencies: -# -# Stage 1a (CPU): Build overlay dataset — lung_axial (BiomedCLIP + LLaVA-Med) -# Stage 1b (CPU): Build overlay dataset — lung_axial_medgemma (MedGemma) -# -# Stage 2 (GPU): Run each model under all 4 conditions (parallel) -# → BiomedCLIP depends on 1a -# → LLaVA-Med depends on 1a -# → MedGemma depends on 1b -# -# Stage 3 (CPU): Cross-model comparison -# → Accuracy heatmap, delta plots, unified summary -# -# Dependencies: -# 1a ──→ BiomedCLIP ──┐ -# 1a ──→ LLaVA-Med ──┼──→ Cross-model comparison -# 1b ──→ MedGemma ──┘ -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJ_DIR="$(dirname "${SCRIPT_DIR}")" -cd "${PROJ_DIR}" - -echo "============================================================" -echo " Spatial Guidance VLM Evaluation Pipeline" -echo " Working dir: ${PROJ_DIR}" -echo " Time: $(date)" -echo "============================================================" - -# ── Stage 1a: Build overlay dataset — lung_axial (CPU) ─────────────────────── -echo "" -echo "Stage 1a: Submitting lung_axial overlay build (BiomedCLIP + LLaVA-Med)..." -STD_DATA_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_overlay_build_std.sub) -echo " Job ${STD_DATA_JOB}: vlm_overlay_build_std.sub" - -# ── Stage 1b: Build overlay dataset — lung_axial_medgemma (CPU) ────────────── -echo "" -echo "Stage 1b: Submitting lung_axial_medgemma overlay build (MedGemma)..." -MG_DATA_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_overlay_build_medgemma.sub) -echo " Job ${MG_DATA_JOB}: vlm_overlay_build_medgemma.sub" - -# ── Stage 2: Per-model condition evaluation (GPU, parallel) ────────────────── -echo "" -echo "Stage 2: Submitting per-model condition jobs..." - -BIOMED_JOB=$(sbatch --parsable --dependency=afterok:${STD_DATA_JOB} \ - infra/slurm/vlm_eval/vlm_cond_biomedclip.sub) -echo " Job ${BIOMED_JOB}: vlm_cond_biomedclip.sub (after ${STD_DATA_JOB})" - -LLAVA_JOB=$(sbatch --parsable --dependency=afterok:${STD_DATA_JOB} \ - infra/slurm/vlm_eval/vlm_cond_llava_med.sub) -echo " Job ${LLAVA_JOB}: vlm_cond_llava_med.sub (after ${STD_DATA_JOB})" - -MEDGEM_JOB=$(sbatch --parsable --dependency=afterok:${MG_DATA_JOB} \ - infra/slurm/vlm_eval/vlm_cond_medgemma.sub) -echo " Job ${MEDGEM_JOB}: vlm_cond_medgemma.sub (after ${MG_DATA_JOB})" - -# ── Stage 3: Cross-model comparison (CPU) ──────────────────────────────────── -echo "" -echo "Stage 3: Submitting cross-model comparison (after all Stage 2)..." -CMP_JOB=$(sbatch --parsable \ - --dependency=afterok:${BIOMED_JOB}:${LLAVA_JOB}:${MEDGEM_JOB} \ - infra/slurm/vlm_eval/vlm_cross_comparison.sub) -echo " Job ${CMP_JOB}: vlm_cross_comparison.sub" - -# ── Summary ────────────────────────────────────────────────────────────────── -echo "" -echo "============================================================" -echo " Pipeline submitted!" -echo "" -echo " Stage 1a (lung_axial data): ${STD_DATA_JOB}" -echo " Stage 1b (lung_axial_medgemma data): ${MG_DATA_JOB}" -echo " Stage 2 (BiomedCLIP): ${BIOMED_JOB}" -echo " Stage 2 (LLaVA-Med): ${LLAVA_JOB}" -echo " Stage 2 (MedGemma): ${MEDGEM_JOB}" -echo " Stage 3 (cross-model compare): ${CMP_JOB}" -echo "" -echo " Monitor: squeue -u \$USER" -echo " Logs: logs/VLM_*_{JOBID}.{out,err}" -echo "============================================================" diff --git a/itrialspace/infra/slurm/vlm_eval/run_std_reeval.sh b/itrialspace/infra/slurm/vlm_eval/run_std_reeval.sh deleted file mode 100644 index f97943d8e6c58190d7dec4496f5bc43fb839574b..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/run_std_reeval.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env bash - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" - -# ── STD Modes (M1-10) Incremental Rebuild + VLM Re-evaluation ──────────────── -# -# Context: -# eval_dataset was built on Apr 12 09:56 → 9,305 rows -# Extraction code was updated on Apr 12 20:58-21:05 (post-build) -# 78 generated CTs missing from eval (extraction attrition) -# 11 cases missing overlays (overlay conditions have 9,294 vs 9,305 plain) -# -# Pipeline: -# 1. CPU rebuild (both profiles) with --skip-existing --overlays -# 2. GPU VLM eval (3 models × 4 conditions) with --skip-existing -# 3. Cross-model comparison -# -# Usage: -# cd ${PROJ_DIR} -# bash vlm_evaluation/run_std_reeval.sh - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -cd "${PROJ_DIR}" -mkdir -p logs - -echo "==============================================" -echo "STD Modes M1-10 Incremental Rebuild + Re-eval" -echo " Time: $(date)" -echo "==============================================" - -# ── Step 1: CPU rebuild (both profiles) ────────────────────────────────────── -BUILD_JOB=$(sbatch --parsable infra/slurm/vlm_eval/vlm_std_rebuild.sub) -echo " Rebuild: job ${BUILD_JOB}" - -# ── Step 2: GPU VLM eval (chained after rebuild) ──────────────────────────── -BIOMED=$(sbatch --parsable --dependency=afterok:${BUILD_JOB} \ - infra/slurm/vlm_eval/vlm_cond_biomedclip.sub) -echo " BiomedCLIP: job ${BIOMED} (after ${BUILD_JOB})" - -LLAVA=$(sbatch --parsable --dependency=afterok:${BUILD_JOB} \ - infra/slurm/vlm_eval/vlm_cond_llava_med.sub) -echo " LLaVA-Med: job ${LLAVA} (after ${BUILD_JOB})" - -MEDGEM=$(sbatch --parsable --dependency=afterok:${BUILD_JOB} \ - infra/slurm/vlm_eval/vlm_cond_medgemma.sub) -echo " MedGemma: job ${MEDGEM} (after ${BUILD_JOB})" - -# ── Step 3: Cross-model comparison ────────────────────────────────────────── -CROSS=$(sbatch --parsable \ - --dependency=afterok:${BIOMED}:${LLAVA}:${MEDGEM} \ - infra/slurm/vlm_eval/vlm_cross_comparison.sub) -echo " Cross-model: job ${CROSS} (after ${BIOMED},${LLAVA},${MEDGEM})" - -echo "" -echo "===== Job Chain =====" -echo " ${BUILD_JOB} → Rebuild (CPU, both profiles)" -echo " ${BIOMED} → BiomedCLIP (GPU)" -echo " ${LLAVA} → LLaVA-Med (GPU)" -echo " ${MEDGEM} → MedGemma (GPU)" -echo " ${CROSS} → Comparison (CPU)" -echo "" -echo "Monitor: squeue -u ft42" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_biomedclip.sub b/itrialspace/infra/slurm/vlm_eval/vlm_biomedclip.sub deleted file mode 100644 index 3e0f274131d525d160579f3c608eaec01f828707..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_biomedclip.sub +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_biomed -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLM_biomed_%j.out -#SBATCH --error=logs/VLM_biomed_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── BiomedCLIP VLM Evaluation ──────────────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Requires the shared dataset to be built first: -# DATA_JOB=$(sbatch --parsable vlm_evaluation/vlm_build_dataset.sub) -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_biomedclip.sub -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_llava_med.sub -# -# Set PROFILE to match the dataset build step (default: lung_axial): -# PROFILE=mediastinal_axial sbatch vlm_evaluation/vlm_biomedclip.sub -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="${PROFILE:-lung_axial}" -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/biomedclip" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "VLM BiomedCLIP Evaluation" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset exists ──────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_build_dataset.sub first." - exit 1 -fi - -echo "Using pre-built dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run ────────────────────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.run_biomedclip \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --device cuda \ - --tasks presence lobe size - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_build_dataset.sub b/itrialspace/infra/slurm/vlm_eval/vlm_build_dataset.sub deleted file mode 100644 index 4ae9a7f471adcf359fd5bcb9aa5485bb2de89c1c..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_build_dataset.sub +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_data -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLM_data_%j.out -#SBATCH --error=logs/VLM_data_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Shared VLM Evaluation Dataset ─────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_build_dataset.sub -# -# CPU-only job: loads each NIfTI, extracts lesion-centred slices as PNGs/npy, -# and writes eval_dataset.csv. No GPU required. -# -# Preprocessing profile (controls CT window, slice plane, output format): -# Default: lung_axial (lung window, axial plane, PNG grayscale) -# Override: PROFILE=mediastinal_axial sbatch vlm_evaluation/vlm_build_dataset.sub -# -# Available profiles: lung_axial, mediastinal_axial, bone_axial, -# lung_coronal, lung_sagittal, lung_axial_npy -# -# After this finishes, submit the model jobs: -# sbatch --dependency=afterok: vlm_evaluation/vlm_biomedclip.sub -# sbatch --dependency=afterok: vlm_evaluation/vlm_llava_med.sub -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="${PROFILE:-lung_axial}" -DATASET_DIR="${DATA_BASE}/vlm_eval/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "VLM Dataset Build" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Profile: ${PROFILE}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -# ── Collect manifests ──────────────────────────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" -# Depth 2: modes 1-10, 7 (mode*/*.csv) -# Depth 3: modes 11-13 (mode*/DATASET/*.csv) -for mpath in "${MANIFEST_DIR}"/mode*/*.csv "${MANIFEST_DIR}"/mode*/*/*.csv; do - if [[ -f "${mpath}" ]]; then - MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" - fi -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found in ${MANIFEST_DIR}/mode*/" - exit 1 -fi - -# ── Run ────────────────────────────────────────────────────────────────────── -# Set OVERLAYS=1 to generate bbox/contour overlay PNGs alongside plain slices: -# OVERLAYS=1 sbatch vlm_evaluation/vlm_build_dataset.sub -OVERLAY_FLAG="" -if [[ "${OVERLAYS:-0}" == "1" ]]; then - OVERLAY_FLAG="--overlays" - echo "Overlay generation ENABLED (bbox + contour + bbox_contour)" -fi - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - ${OVERLAY_FLAG} - -echo "" -echo "Done at $(date)" -echo "Profile: ${PROFILE}" -echo "Dataset: ${DATASET_DIR}/eval_dataset.csv" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cond_biomedclip.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cond_biomedclip.sub deleted file mode 100644 index 0058e43c1092b0d4a697d45e85eee26a7956a577..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cond_biomedclip.sub +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_cbd -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLM_cbd_%j.out -#SBATCH --error=logs/VLM_cbd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── BiomedCLIP Condition-Aware Evaluation ───────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs BiomedCLIP under all image presentation conditions (plain, bbox, -# contour, bbox_contour) and produces per-condition results + comparison. -# -# Requires overlay dataset built first: -# DATA_JOB=$(sbatch --parsable vlm_evaluation/vlm_overlay_build.sub) -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_cond_biomedclip.sub -# -# BiomedCLIP uses contrastive (CLIP) scoring → ~2 GB VRAM, fast inference. -# Running all 4 conditions sequentially is still fast (~15-20 min total). -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/biomedclip" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "BiomedCLIP – Condition-Aware Evaluation" -echo " Conditions: plain bbox contour bbox_contour" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset ─────────────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_overlay_build.sub first." - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run all conditions ─────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model biomedclip \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -# ── Per-model comparison ───────────────────────────────────────────────────── -echo "" -echo "Running BiomedCLIP cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "BiomedCLIP" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cond_biomedclip_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cond_biomedclip_ext.sub deleted file mode 100644 index 0db45ed5d8469d5add12d0728fac3aa0e01c060c..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cond_biomedclip_ext.sub +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_cbd -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLX_cbd_%j.out -#SBATCH --error=logs/VLX_cbd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── BiomedCLIP — Extended Modes (7, 11, 12, 13) ───────────────────────────── -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval_ext/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}/biomedclip" - -cd "${PROJ_DIR}" -mkdir -p logs - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "BiomedCLIP — Extended Modes" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Dataset: ${DATASET_CSV}" -echo " Time: $(date)" -echo "===============================================" - -[[ -f "${DATASET_CSV}" ]] || { echo "ERROR: ${DATASET_CSV} not found"; exit 1; } -wc -l "${DATASET_CSV}" - -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model biomedclip \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "BiomedCLIP" - -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cond_llava_med.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cond_llava_med.sub deleted file mode 100644 index 5797f6c8f07cd7798b53676e0a70cbec7966dba9..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cond_llava_med.sub +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_cld -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --output=logs/VLM_cld_%j.out -#SBATCH --error=logs/VLM_cld_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── LLaVA-Med Condition-Aware Evaluation ────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs LLaVA-Med under all image presentation conditions (plain, bbox, -# contour, bbox_contour) and produces per-condition results + comparison. -# -# Requires overlay dataset built first: -# DATA_JOB=$(sbatch --parsable vlm_evaluation/vlm_overlay_build.sub) -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_cond_llava_med.sub -# -# LLaVA-Med is a 7B generative model → ~16 GB VRAM in float16. -# Sequential generation per image; running 4 conditions may take ~2 hrs total. -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/llava_med" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "LLaVA-Med – Condition-Aware Evaluation" -echo " Conditions: plain bbox contour bbox_contour" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset ─────────────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_overlay_build.sub first." - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run all conditions ─────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model llava_med \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -# ── Per-model comparison ───────────────────────────────────────────────────── -echo "" -echo "Running LLaVA-Med cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "LLaVA-Med" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cond_llava_med_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cond_llava_med_ext.sub deleted file mode 100644 index dadd6e3a854da550474da50ce584612ecee7cbcb..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cond_llava_med_ext.sub +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_cld -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --output=logs/VLX_cld_%j.out -#SBATCH --error=logs/VLX_cld_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── LLaVA-Med — Extended Modes (7, 11, 12, 13) ────────────────────────────── -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval_ext/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}/llava_med" - -cd "${PROJ_DIR}" -mkdir -p logs - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "LLaVA-Med — Extended Modes" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Dataset: ${DATASET_CSV}" -echo " Time: $(date)" -echo "===============================================" - -[[ -f "${DATASET_CSV}" ]] || { echo "ERROR: ${DATASET_CSV} not found"; exit 1; } -wc -l "${DATASET_CSV}" - -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model llava_med \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "LLaVA-Med" - -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cond_medgemma.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cond_medgemma.sub deleted file mode 100644 index 9d9d98bd962a58317cf99709775c10aae31a0488..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cond_medgemma.sub +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_cmd -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLM_cmd_%j.out -#SBATCH --error=logs/VLM_cmd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── MedGemma Condition-Aware Evaluation ─────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs MedGemma 1.5 4B under all image presentation conditions (plain, bbox, -# contour, bbox_contour) and produces per-condition results + comparison. -# -# Requires overlay dataset built first (with medgemma profile): -# DATA_JOB=$(sbatch --parsable vlm_evaluation/vlm_overlay_build.sub) -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_cond_medgemma.sub -# -# MedGemma uses lung_axial_medgemma profile (3-channel CT windowing). -# Multi-slice input: centre + context slices auto-discovered per case. -# ~8 GB VRAM in bfloat16; 4 conditions × ~9k cases → ~40 min total. -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/medgemma" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# cuDNN 9 lives inside the conda nvidia package; torch 2.6 needs it on -# LD_LIBRARY_PATH. -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "MedGemma 1.5 4B – Condition-Aware Evaluation" -echo " Conditions: plain bbox contour bbox_contour" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset ─────────────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_overlay_build.sub first." - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run all conditions ─────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model medgemma \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -# ── Per-model comparison ───────────────────────────────────────────────────── -echo "" -echo "Running MedGemma cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "MedGemma" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cond_medgemma_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cond_medgemma_ext.sub deleted file mode 100644 index 8f3ecaab3b84563147c889016dc62694823137c1..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cond_medgemma_ext.sub +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_cmd -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLX_cmd_%j.out -#SBATCH --error=logs/VLX_cmd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── MedGemma — Extended Modes (7, 11, 12, 13) ─────────────────────────────── -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_CSV="${DATA_BASE}/vlm_eval_ext/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}/medgemma" - -cd "${PROJ_DIR}" -mkdir -p logs - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "MedGemma 1.5 4B — Extended Modes" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Dataset: ${DATASET_CSV}" -echo " Time: $(date)" -echo "===============================================" - -[[ -f "${DATASET_CSV}" ]] || { echo "ERROR: ${DATASET_CSV} not found"; exit 1; } -wc -l "${DATASET_CSV}" - -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model medgemma \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "MedGemma" - -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_conditions.sub b/itrialspace/infra/slurm/vlm_eval/vlm_conditions.sub deleted file mode 100644 index a41598c088de56dac020452201554be999259c2a..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_conditions.sub +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_cond -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --output=logs/VLM_cond_%j.out -#SBATCH --error=logs/VLM_cond_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Condition-Aware VLM Evaluation ──────────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs a model under one or more image presentation conditions -# (plain / bbox / contour / bbox_contour). -# -# REQUIRES: dataset built with OVERLAYS=1: -# OVERLAYS=1 sbatch vlm_evaluation/vlm_build_dataset.sub -# -# Usage: -# MODEL=biomedclip CONDITIONS="plain bbox contour" \ -# sbatch vlm_evaluation/vlm_conditions.sub -# -# MODEL=llava_med CONDITIONS="all" \ -# sbatch vlm_evaluation/vlm_conditions.sub -# -# MODEL=medgemma CONDITIONS="plain bbox" \ -# sbatch vlm_evaluation/vlm_conditions.sub -# -# Environment variables: -# MODEL - biomedclip | llava_med | medgemma (required) -# CONDITIONS - space-separated list, or "all" (default: "plain bbox contour bbox_contour") -# PROFILE - preprocessing profile (default: lung_axial, or lung_axial_medgemma for medgemma) -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -MODEL="${MODEL:?ERROR: Set MODEL=biomedclip|llava_med|medgemma}" -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" - -# Auto-detect profile for MedGemma if not explicitly set -if [[ -z "${PROFILE:-}" ]]; then - if [[ "${MODEL}" == "medgemma" ]]; then - PROFILE="lung_axial_medgemma" - else - PROFILE="lung_axial" - fi -fi -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/${MODEL}" -CONDITIONS="${CONDITIONS:-plain bbox contour bbox_contour}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# cuDNN 9 for torch 2.6 (needed by MedGemma) -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "VLM Condition-Aware Evaluation" -echo " Model: ${MODEL}" -echo " Conditions: ${CONDITIONS}" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset exists ──────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run: OVERLAYS=1 sbatch vlm_evaluation/vlm_build_dataset.sub" - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Build condition flags ──────────────────────────────────────────────────── -if [[ "${CONDITIONS}" == "all" ]]; then - COND_FLAG="--run-all-conditions" -else - COND_FLAG="--image-condition ${CONDITIONS}" -fi - -# ── Run ────────────────────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model "${MODEL}" \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - ${COND_FLAG} \ - --device cuda \ - --tasks presence lobe size - -# ── Cross-condition comparison ─────────────────────────────────────────────── -echo "" -echo "Running cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions ${CONDITIONS} \ - --model-name "${MODEL}" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cross_comparison.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cross_comparison.sub deleted file mode 100644 index 8185b0bb254468fedbc882a873598c2daceb8be2..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cross_comparison.sub +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_cmpall -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=2 -#SBATCH --mem=8G -#SBATCH --output=logs/VLM_cmpall_%j.out -#SBATCH --error=logs/VLM_cmpall_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Cross-Model Condition Comparison ───────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# CPU-only job that reads per-model per-condition summary.json files and -# produces a unified cross-model comparison report: -# - accuracy_heatmap.png (model × condition × task) -# - per-task bar charts (all models side-by-side, grouped by condition) -# - per-task delta charts (accuracy Δ vs plain, all models) -# - cross_model_accuracy.csv -# - cross_model_deltas.csv -# - cross_model_summary.json -# -# Requires all model condition jobs to finish first: -# BIOMED_JOB=$(sbatch --parsable vlm_evaluation/vlm_cond_biomedclip.sub) -# LLAVA_JOB=$(sbatch --parsable vlm_evaluation/vlm_cond_llava_med.sub) -# MEDGEM_JOB=$(sbatch --parsable vlm_evaluation/vlm_cond_medgemma.sub) -# sbatch --dependency=afterok:${BIOMED_JOB}:${LLAVA_JOB}:${MEDGEM_JOB} \ -# vlm_evaluation/vlm_cross_comparison.sub -# -# Or use the orchestrator: -# bash vlm_evaluation/run_spatial_guidance_pipeline.sh -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -EVAL_BASE="${DATA_BASE}/vlm_eval" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "Cross-Model Condition Comparison" -echo " Models: BiomedCLIP, LLaVA-Med, MedGemma" -echo " Conditions: plain, bbox, contour, bbox_contour" -echo " Eval base: ${EVAL_BASE}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Run ────────────────────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.cross_model_comparison \ - --eval-base "${EVAL_BASE}" \ - --models biomedclip llava_med medgemma \ - --conditions plain bbox contour bbox_contour - -echo "" -echo "Done at $(date)" -echo "Outputs: ${EVAL_BASE}/cross_model_comparison/" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_cross_comparison_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_cross_comparison_ext.sub deleted file mode 100644 index 3d3c78dc981b742691fde258ce6edff560a43e66..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_cross_comparison_ext.sub +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_cmpall -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=2 -#SBATCH --mem=8G -#SBATCH --output=logs/VLX_cmpall_%j.out -#SBATCH --error=logs/VLX_cmpall_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Cross-Model Comparison — Extended Modes ────────────────────────────────── -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -EVAL_BASE="${DATA_BASE}/vlm_eval_ext" - -cd "${PROJ_DIR}" -mkdir -p logs - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "Cross-Model Comparison — Extended Modes" -echo " Models: BiomedCLIP, LLaVA-Med, MedGemma" -echo " Conditions: plain, bbox, contour, bbox_contour" -echo " Eval base: ${EVAL_BASE}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.cross_model_comparison \ - --eval-base "${EVAL_BASE}" \ - --models biomedclip llava_med medgemma \ - --conditions plain bbox contour bbox_contour - -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_ext_llava_single_cond.sub b/itrialspace/infra/slurm/vlm_eval/vlm_ext_llava_single_cond.sub deleted file mode 100644 index 0d47f6f20e243656519934a7cc48f31de6ad5648..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_ext_llava_single_cond.sub +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_lsc -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --output=logs/VLX_lsc_%j.out -#SBATCH --error=logs/VLX_lsc_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── LLaVA-Med — Extended Modes — Single Condition ──────────────────────────── -# Usage: sbatch --export=CONDITION=plain vlm_evaluation/vlm_ext_llava_single_cond.sub -set -euo pipefail - -: "${CONDITION:?ERROR: CONDITION not set (plain|bbox|contour|bbox_contour)}" - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval_ext/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}/llava_med" - -cd "${PROJ_DIR}" -mkdir -p logs - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "LLaVA-Med — Extended Modes — ${CONDITION}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Condition: ${CONDITION}" -echo " Dataset: ${DATASET_CSV}" -echo " Time: $(date)" -echo "===============================================" - -[[ -f "${DATASET_CSV}" ]] || { echo "ERROR: ${DATASET_CSV} not found"; exit 1; } -wc -l "${DATASET_CSV}" - -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model llava_med \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --image-condition "${CONDITION}" \ - --device cuda \ - --tasks presence lobe size - -echo "Done ${CONDITION} at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_ext_medgemma_single_cond.sub b/itrialspace/infra/slurm/vlm_eval/vlm_ext_medgemma_single_cond.sub deleted file mode 100644 index c60e4e0e53420092ced023f2d7fddce9eb09c8d3..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_ext_medgemma_single_cond.sub +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VXM_sc -#SBATCH --partition=defq -#SBATCH --nodelist=node003 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VXM_sc_%j.out -#SBATCH --error=logs/VXM_sc_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── MedGemma EXT — Single Condition Job ────────────────────────────────────── -# Submit with CONDITION env var set to parallelize across GPUs: -# CONDITION=plain sbatch vlm_evaluation/vlm_ext_medgemma_single_cond.sub -# CONDITION=bbox sbatch vlm_evaluation/vlm_ext_medgemma_single_cond.sub -# etc. -# ───────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -CONDITION="${CONDITION:?ERROR: Set CONDITION=plain|bbox|contour|bbox_contour}" - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_CSV="${DATA_BASE}/vlm_eval_ext/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}/medgemma" - -cd "${PROJ_DIR}" -mkdir -p logs - -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "MedGemma EXT — Condition: ${CONDITION}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model medgemma \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --image-condition "${CONDITION}" \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -echo "Done ${CONDITION} at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_llava_med.sub b/itrialspace/infra/slurm/vlm_eval/vlm_llava_med.sub deleted file mode 100644 index 5075289c88b1fb08fb34654233deccd3d449273a..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_llava_med.sub +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_llava -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --output=logs/VLM_llava_%j.out -#SBATCH --error=logs/VLM_llava_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── LLaVA-Med VLM Evaluation ───────────────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Requires the shared dataset to be built first: -# DATA_JOB=$(sbatch --parsable vlm_evaluation/vlm_build_dataset.sub) -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_biomedclip.sub -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_llava_med.sub -# -# Set PROFILE to match the dataset build step (default: lung_axial): -# PROFILE=mediastinal_axial sbatch vlm_evaluation/vlm_llava_med.sub -# -# LLaVA is a 7B generative model → needs ~16 GB VRAM in float16. -# Generation is sequential per image so wall-time is higher than BiomedCLIP. -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="${PROFILE:-lung_axial}" -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/llava_med" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "VLM LLaVA-Med Evaluation" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset exists ──────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_build_dataset.sub first." - exit 1 -fi - -echo "Using pre-built dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run ────────────────────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_llava_med \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --device cuda \ - --tasks presence lobe size - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_medgemma.sub b/itrialspace/infra/slurm/vlm_eval/vlm_medgemma.sub deleted file mode 100644 index 2248b404cea2d7205978e37f28413231e1042685..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_medgemma.sub +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_medgem -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLM_medgem_%j.out -#SBATCH --error=logs/VLM_medgem_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── MedGemma 1.5 4B VLM Evaluation ─────────────────────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Requires the shared dataset to be built first with the medgemma profile: -# PROFILE=lung_axial_medgemma DATA_JOB=$(sbatch --parsable vlm_evaluation/vlm_build_dataset.sub) -# sbatch --dependency=afterok:${DATA_JOB} vlm_evaluation/vlm_medgemma.sub -# -# Override PROFILE if needed: -# PROFILE=lung_axial sbatch vlm_evaluation/vlm_medgemma.sub -# -# MedGemma 1.5 4B → ~8 GB VRAM in bfloat16 (multi-slice = 3 images/case). -# Uses 3-channel CT windowing: R=wide, G=soft tissue, B=brain. -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="${PROFILE:-lung_axial_medgemma}" -DATASET_CSV="${DATA_BASE}/vlm_eval/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval/${PROFILE}/medgemma" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# cuDNN 9 lives inside the conda nvidia package; torch 2.6 (user-installed) -# needs it on LD_LIBRARY_PATH. -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "VLM MedGemma 1.5 4B Evaluation (3-channel CT windowing)" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Verify dataset exists ──────────────────────────────────────────────────── -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_build_dataset.sub first." - exit 1 -fi - -echo "Using pre-built dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run ────────────────────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_medgemma \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --device cuda \ - --tasks presence lobe size - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build.sub b/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build.sub deleted file mode 100644 index bb20b4310064131e79ae5540ab81c8ebc95bdeeb..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build.sub +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_ovdata -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLM_ovdata_%j.out -#SBATCH --error=logs/VLM_ovdata_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Overlay-Enabled VLM Evaluation Dataset ───────────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_overlay_build.sub -# -# CPU-only job: extracts lesion-centred slices AND generates bbox / contour / -# bbox_contour overlay PNGs for every case. Writes eval_dataset.csv with -# additional columns: png_bbox_path, png_contour_path, png_bbox_contour_path. -# -# PROFILES: Two datasets are built — -# 1. lung_axial (grayscale, for BiomedCLIP + LLaVA-Med) -# 2. lung_axial_medgemma (3-channel RGB, for MedGemma) -# Both include overlay generation. -# -# After this finishes, submit the per-model condition jobs: -# sbatch --dependency=afterok: vlm_evaluation/vlm_cond_biomedclip.sub -# sbatch --dependency=afterok: vlm_evaluation/vlm_cond_llava_med.sub -# sbatch --dependency=afterok: vlm_evaluation/vlm_cond_medgemma.sub -# -# Or use the orchestrator: -# bash vlm_evaluation/run_spatial_guidance_pipeline.sh -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests ──────────────────────────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" -for mpath in "${MANIFEST_DIR}"/mode*/*.csv; do - if [[ -f "${mpath}" ]]; then - MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" - fi -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found in ${MANIFEST_DIR}/mode*/" - exit 1 -fi - -# ── Profile 1: lung_axial (BiomedCLIP + LLaVA-Med) ────────────────────────── -PROFILE_STD="lung_axial" -DATASET_DIR_STD="${DATA_BASE}/vlm_eval/${PROFILE_STD}" - -echo "===============================================" -echo "VLM Overlay Dataset Build — ${PROFILE_STD}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR_STD}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR_STD}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE_STD}" \ - --overlays - -echo "" -echo "lung_axial dataset: ${DATASET_DIR_STD}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR_STD}/eval_dataset.csv") rows" - -# ── Profile 2: lung_axial_medgemma (MedGemma) ─────────────────────────────── -PROFILE_MG="lung_axial_medgemma" -DATASET_DIR_MG="${DATA_BASE}/vlm_eval/${PROFILE_MG}" - -echo "" -echo "===============================================" -echo "VLM Overlay Dataset Build — ${PROFILE_MG}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR_MG}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE_MG}" \ - --overlays - -echo "" -echo "lung_axial_medgemma dataset: ${DATASET_DIR_MG}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR_MG}/eval_dataset.csv") rows" - -echo "" -echo "===============================================" -echo "Both overlay datasets built at $(date)" -echo " 1. ${DATASET_DIR_STD}/eval_dataset.csv" -echo " 2. ${DATASET_DIR_MG}/eval_dataset.csv" -echo "===============================================" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_medgemma.sub b/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_medgemma.sub deleted file mode 100644 index 9c307ccd7f82be187445d615234e279d564a8994..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_medgemma.sub +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_ovmg -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLM_ovmg_%j.out -#SBATCH --error=logs/VLM_ovmg_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Overlay Dataset — lung_axial_medgemma (MedGemma) ─────────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_overlay_build_medgemma.sub -# -# CPU-only job: extracts 3-channel RGB lesion-centred slices AND generates -# bbox / contour / bbox_contour overlay PNGs + context-slice symlinks. -# -# Profile: lung_axial_medgemma (3-channel RGB, for MedGemma multi-slice) -# Output: vlm_eval/lung_axial_medgemma/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_DIR="${DATA_BASE}/vlm_eval/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests ──────────────────────────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" -# Depth 2: modes 1-10, 7 (mode*/*.csv) -# Depth 3: modes 11-13 (mode*/DATASET/*.csv) -for mpath in "${MANIFEST_DIR}"/mode*/*.csv "${MANIFEST_DIR}"/mode*/*/*.csv; do - if [[ -f "${mpath}" ]]; then - MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" - fi -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found in ${MANIFEST_DIR}/mode*/" - exit 1 -fi - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "VLM Overlay Dataset Build — ${PROFILE}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_medgemma_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_medgemma_ext.sub deleted file mode 100644 index 4a4232fa31fe4e1d9f90e1fb5c3ee4149e5da599..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_medgemma_ext.sub +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_ovmg -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLX_ovmg_%j.out -#SBATCH --error=logs/VLX_ovmg_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Overlay Dataset — Extended Modes (7, 11, 12, 13) — MedGemma ─────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_overlay_build_medgemma_ext.sub -# -# CPU-only job for digital-twin and bootstrap modes that were not included -# in the original mode 1-10 evaluation. -# -# Profile: lung_axial_medgemma (3-channel RGB, for MedGemma multi-slice) -# Output: vlm_eval_ext/lung_axial_medgemma/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests — extended modes only ────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" - -# Mode 7: bootstrap (depth 2) -for mpath in "${MANIFEST_DIR}"/mode7_bootstrap_confidence/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -# Modes 11, 12, 13: digital twin (depth 3) -for mpath in "${MANIFEST_DIR}"/mode1[1-3]_*/*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found for extended modes (7, 11, 12, 13)" - exit 1 -fi - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "VLM Overlay Build — Extended Modes — ${PROFILE}" -echo " Modes: 7 (bootstrap), 11-13 (digital twin)" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_std.sub b/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_std.sub deleted file mode 100644 index 7e2981da958f14cdbdfccf5cb650ffe00714f034..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_std.sub +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLM_ovstd -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLM_ovstd_%j.out -#SBATCH --error=logs/VLM_ovstd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Overlay Dataset — lung_axial (BiomedCLIP + LLaVA-Med) ───────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_overlay_build_std.sub -# -# CPU-only job: extracts grayscale lesion-centred slices AND generates -# bbox / contour / bbox_contour overlay PNGs. -# -# Profile: lung_axial (grayscale, for BiomedCLIP + LLaVA-Med) -# Output: vlm_eval/lung_axial/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_DIR="${DATA_BASE}/vlm_eval/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests ──────────────────────────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" -# Depth 2: modes 1-10, 7 (mode*/*.csv) -# Depth 3: modes 11-13 (mode*/DATASET/*.csv) -for mpath in "${MANIFEST_DIR}"/mode*/*.csv "${MANIFEST_DIR}"/mode*/*/*.csv; do - if [[ -f "${mpath}" ]]; then - MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" - fi -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found in ${MANIFEST_DIR}/mode*/" - exit 1 -fi - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "VLM Overlay Dataset Build — ${PROFILE}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_std_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_std_ext.sub deleted file mode 100644 index 85d0a531d7e3afed27294f734ccd7c0722dee824..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_overlay_build_std_ext.sub +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLX_ovstd -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLX_ovstd_%j.out -#SBATCH --error=logs/VLX_ovstd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Overlay Dataset — Extended Modes (7, 11, 12, 13) — lung_axial ───── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_overlay_build_std_ext.sub -# -# CPU-only job for digital-twin and bootstrap modes that were not included -# in the original mode 1-10 evaluation. -# -# Profile: lung_axial (grayscale, for BiomedCLIP + LLaVA-Med) -# Output: vlm_eval_ext/lung_axial/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests — extended modes only ────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" - -# Mode 7: bootstrap (depth 2) -for mpath in "${MANIFEST_DIR}"/mode7_bootstrap_confidence/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -# Modes 11, 12, 13: digital twin (depth 3) -for mpath in "${MANIFEST_DIR}"/mode1[1-3]_*/*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found for extended modes (7, 11, 12, 13)" - exit 1 -fi - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "VLM Overlay Build — Extended Modes — ${PROFILE}" -echo " Modes: 7 (bootstrap), 11-13 (digital twin)" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_medgemma.sub b/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_medgemma.sub deleted file mode 100644 index 82c51d6c8460b95dce965f307d90a3d4a41fa8f2..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_medgemma.sub +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_bmg -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLR_bmg_%j.out -#SBATCH --error=logs/VLR_bmg_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Post-Fix Rebuild — Modes 1-6, 8-10 — lung_axial_medgemma ──────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_postfix_build_medgemma.sub -# -# Incremental rebuild with --skip-existing: reuses cached rows from the -# prior eval_dataset.csv, only extracts new PNGs for cases whose synthetic -# CT appeared after the April 2025 pipeline fixes. -# -# Profile: lung_axial_medgemma (3-channel RGB, for MedGemma) -# Output: vlm_eval/lung_axial_medgemma/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_DIR="${DATA_BASE}/vlm_eval/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests — modes 1-6, 8-10 only ──────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" - -for mode_num in 1 2 3 4 5 6 8 9 10; do - for mpath in "${MANIFEST_DIR}"/mode${mode_num}_*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" - done -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found for modes 1-6, 8-10" - exit 1 -fi - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "Post-Fix VLM Rebuild — ${PROFILE}" -echo " Modes: 1-6, 8-10" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_medgemma_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_medgemma_ext.sub deleted file mode 100644 index d90bd4793f5b31277bd476a533f5bb8992e31552..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_medgemma_ext.sub +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_bmgx -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=1 -#SBATCH --mem=16G -#SBATCH --output=logs/VLR_bmgx_%j.out -#SBATCH --error=logs/VLR_bmgx_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Post-Fix Rebuild — Extended Modes (7, 11-13) — lung_axial_medgemma ────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_postfix_build_medgemma_ext.sub -# -# Incremental rebuild with --skip-existing: reuses cached rows from the -# prior eval_dataset.csv, only extracts new PNGs for cases whose synthetic -# CT appeared after the April 2025 pipeline fixes. -# -# Profile: lung_axial_medgemma (3-channel RGB, for MedGemma) -# Output: vlm_eval_ext/lung_axial_medgemma/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests — extended modes only ────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" - -# Mode 7: bootstrap (depth 2) -for mpath in "${MANIFEST_DIR}"/mode7_bootstrap_confidence/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -# Modes 11, 12, 13: digital twin (depth 3 — mode*/DATASET/*.csv) -for mpath in "${MANIFEST_DIR}"/mode1[1-3]_*/*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found for extended modes (7, 11-13)" - exit 1 -fi - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "Post-Fix VLM Rebuild — Extended Modes — ${PROFILE}" -echo " Modes: 7 (bootstrap), 11-13 (digital twin)" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing \ - --workers 1 - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_std.sub b/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_std.sub deleted file mode 100644 index c1d8e313c279b47edbab167cd3c902d9edbc5f9f..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_std.sub +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_bstd -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=4 -#SBATCH --mem=16G -#SBATCH --output=logs/VLR_bstd_%j.out -#SBATCH --error=logs/VLR_bstd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Post-Fix Rebuild — Modes 1-6, 8-10 — lung_axial ───────────────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_postfix_build_std.sub -# -# Incremental rebuild with --skip-existing: reuses cached rows from the -# prior eval_dataset.csv, only extracts new PNGs for cases whose synthetic -# CT appeared after the April 2025 pipeline fixes. -# -# Profile: lung_axial (grayscale, for BiomedCLIP + LLaVA-Med) -# Output: vlm_eval/lung_axial/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_DIR="${DATA_BASE}/vlm_eval/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests — modes 1-6, 8-10 only ──────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" - -for mode_num in 1 2 3 4 5 6 8 9 10; do - for mpath in "${MANIFEST_DIR}"/mode${mode_num}_*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" - done -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found for modes 1-6, 8-10" - exit 1 -fi - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "Post-Fix VLM Rebuild — ${PROFILE}" -echo " Modes: 1-6, 8-10" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_std_ext.sub b/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_std_ext.sub deleted file mode 100644 index dd642f5d77f514f662b681ec19d063afbef6ae52..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_postfix_build_std_ext.sub +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_bstdx -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=1 -#SBATCH --mem=16G -#SBATCH --output=logs/VLR_bstdx_%j.out -#SBATCH --error=logs/VLR_bstdx_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Post-Fix Rebuild — Extended Modes (7, 11-13) — lung_axial ─────────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_postfix_build_std_ext.sub -# -# Incremental rebuild with --skip-existing: reuses cached rows from the -# prior eval_dataset.csv, only extracts new PNGs for cases whose synthetic -# CT appeared after the April 2025 pipeline fixes. -# -# Profile: lung_axial (grayscale, for BiomedCLIP + LLaVA-Med) -# Output: vlm_eval_ext/lung_axial/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_DIR="${DATA_BASE}/vlm_eval_ext/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Collect manifests — extended modes only ────────────────────────────────── -MANIFEST_DIR="${DATA_BASE}/manifests" -MANIFEST_ARGS="" - -# Mode 7: bootstrap (depth 2) -for mpath in "${MANIFEST_DIR}"/mode7_bootstrap_confidence/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -# Modes 11, 12, 13: digital twin (depth 3 — mode*/DATASET/*.csv) -for mpath in "${MANIFEST_DIR}"/mode1[1-3]_*/*/*.csv; do - [[ -f "${mpath}" ]] && MANIFEST_ARGS="${MANIFEST_ARGS} ${mpath}" -done - -if [[ -z "${MANIFEST_ARGS}" ]]; then - echo "ERROR: No manifest CSVs found for extended modes (7, 11-13)" - exit 1 -fi - -NCSV=$(echo ${MANIFEST_ARGS} | wc -w) - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "Post-Fix VLM Rebuild — Extended Modes — ${PROFILE}" -echo " Modes: 7 (bootstrap), 11-13 (digital twin)" -echo " CSVs: ${NCSV}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest ${MANIFEST_ARGS} \ - --output-dir "${DATASET_DIR}" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile "${PROFILE}" \ - --overlays \ - --skip-existing \ - --workers 1 - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_biomedclip.sub b/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_biomedclip.sub deleted file mode 100644 index 538671fc1484b499b627d071433fc5cacd25afe7..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_biomedclip.sub +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_cbd -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLR_cbd_%j.out -#SBATCH --error=logs/VLR_cbd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── BiomedCLIP Condition-Aware Evaluation — Real CTs ───────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs BiomedCLIP under all 4 image conditions on real CT nodule slices. -# Requires vlm_real_overlay_build_std.sub to complete first. -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval_real/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_real/${PROFILE}/biomedclip" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "BiomedCLIP – Real CT Condition-Aware Evaluation" -echo " Conditions: plain bbox contour bbox_contour" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_real_overlay_build_std.sub first." - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run all conditions ─────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model biomedclip \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -# ── Per-model comparison ───────────────────────────────────────────────────── -echo "" -echo "Running BiomedCLIP cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "BiomedCLIP" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_llava_med.sub b/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_llava_med.sub deleted file mode 100644 index dc21c28d490eee3937d0a400aa3ea2bee70bb158..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_llava_med.sub +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_cld -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=48G -#SBATCH --output=logs/VLR_cld_%j.out -#SBATCH --error=logs/VLR_cld_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── LLaVA-Med Condition-Aware Evaluation — Real CTs ────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs LLaVA-Med under all 4 image conditions on real CT nodule slices. -# Requires vlm_real_overlay_build_std.sub to complete first. -# -# LLaVA-Med is 7B float16 → ~16 GB VRAM; sequential generation. -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_CSV="${DATA_BASE}/vlm_eval_real/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_real/${PROFILE}/llava_med" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "LLaVA-Med – Real CT Condition-Aware Evaluation" -echo " Conditions: plain bbox contour bbox_contour" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_real_overlay_build_std.sub first." - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run all conditions ─────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model llava_med \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -# ── Per-model comparison ───────────────────────────────────────────────────── -echo "" -echo "Running LLaVA-Med cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "LLaVA-Med" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_medgemma.sub b/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_medgemma.sub deleted file mode 100644 index 31c37cb202e23831c6bebc0510868a2de96e7be3..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_real_cond_medgemma.sub +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_cmd -#SBATCH --partition=vram48 -#SBATCH --ntasks=1 -#SBATCH --gpus=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLR_cmd_%j.out -#SBATCH --error=logs/VLR_cmd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── MedGemma Condition-Aware Evaluation — Real CTs ─────────────────────────── -# Submit from: ${PROJ_DIR} -# -# Runs MedGemma 1.5 4B under all 4 image conditions on real CT nodule slices. -# Requires vlm_real_overlay_build_medgemma.sub to complete first. -# -# Uses lung_axial_medgemma profile (3-channel CT windowing). -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_CSV="${DATA_BASE}/vlm_eval_real/${PROFILE}/eval_dataset.csv" -OUTPUT_DIR="${DATA_BASE}/vlm_eval_real/${PROFILE}/medgemma" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# cuDNN 9 for torch 2.6 -export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" - -echo "===============================================" -echo "MedGemma 1.5 4B – Real CT Condition-Aware Evaluation" -echo " Conditions: plain bbox contour bbox_contour" -echo " Profile: ${PROFILE}" -echo " Host: $(hostname)" -echo " GPU: $(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo 'N/A')" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -if [[ ! -f "${DATASET_CSV}" ]]; then - echo "ERROR: Dataset not found at ${DATASET_CSV}" - echo "Run vlm_real_overlay_build_medgemma.sub first." - exit 1 -fi - -echo "Using dataset: ${DATASET_CSV}" -wc -l "${DATASET_CSV}" - -# ── Run all conditions ─────────────────────────────────────────────────────── -python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ - --model medgemma \ - --dataset-csv "${DATASET_CSV}" \ - --output-dir "${OUTPUT_DIR}" \ - --run-all-conditions \ - --skip-existing \ - --device cuda \ - --tasks presence lobe size - -# ── Per-model comparison ───────────────────────────────────────────────────── -echo "" -echo "Running MedGemma cross-condition comparison..." -python -m itrialspace.evaluation.vlm_eval.comparison \ - --results-dir "${OUTPUT_DIR}" \ - --conditions plain bbox contour bbox_contour \ - --model-name "MedGemma" - -echo "" -echo "Done at $(date)" -echo "Outputs: ${OUTPUT_DIR}" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_real_cross_comparison.sub b/itrialspace/infra/slurm/vlm_eval/vlm_real_cross_comparison.sub deleted file mode 100644 index 24a0f2e031bcdc12d4cd41063c7b419c2c2aecf8..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_real_cross_comparison.sub +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_cmpall -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=2 -#SBATCH --mem=8G -#SBATCH --output=logs/VLR_cmpall_%j.out -#SBATCH --error=logs/VLR_cmpall_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Cross-Model Condition Comparison — Real CTs ───────────────────────────── -# Submit from: ${PROJ_DIR} -# -# CPU-only job producing unified cross-model comparison: -# - accuracy heatmap, delta plots, bar charts -# - cross_model_accuracy.csv, cross_model_deltas.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -EVAL_BASE="${DATA_BASE}/vlm_eval_real" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "Cross-Model Comparison — Real CTs" -echo " Models: BiomedCLIP, LLaVA-Med, MedGemma" -echo " Conditions: plain, bbox, contour, bbox_contour" -echo " Eval base: ${EVAL_BASE}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.cross_model_comparison \ - --eval-base "${EVAL_BASE}" \ - --models biomedclip llava_med medgemma \ - --conditions plain bbox contour bbox_contour - -echo "" -echo "Done at $(date)" -echo "Outputs: ${EVAL_BASE}/cross_model_comparison/" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_real_overlay_build_medgemma.sub b/itrialspace/infra/slurm/vlm_eval/vlm_real_overlay_build_medgemma.sub deleted file mode 100644 index a91af95ced87f7c25e628941b4b4d1f0cd032606..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_real_overlay_build_medgemma.sub +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_ovmg -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLR_ovmg_%j.out -#SBATCH --error=logs/VLR_ovmg_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Real CT Overlay Dataset — lung_axial_medgemma (MedGemma) ─────────── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_real_overlay_build_medgemma.sub -# -# CPU-only job: extracts 3-channel RGB lesion-centred slices from real CTs -# AND generates bbox / contour / bbox_contour overlay PNGs. -# -# Profile: lung_axial_medgemma (3-channel RGB, for MedGemma multi-slice) -# Data: 8 datasets (~14,333 nodules) -# Output: vlm_eval_real/lung_axial_medgemma/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial_medgemma" -DATASET_DIR="${DATA_BASE}/vlm_eval_real/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "Real CT Overlay Dataset Build — ${PROFILE}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_real_dataset \ - --data-base "${DATA_BASE}" \ - --output-dir "${DATASET_DIR}" \ - --profile "${PROFILE}" \ - --datasets DLCS24 IMDCT LNDbv4 LUNA16 LUNA25 LUNGx NSCLCR \ - --overlays - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_real_overlay_build_std.sub b/itrialspace/infra/slurm/vlm_eval/vlm_real_overlay_build_std.sub deleted file mode 100644 index 10c68aa1e382dea8c615bac656d5b37e1d011813..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_real_overlay_build_std.sub +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=VLR_ovstd -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/VLR_ovstd_%j.out -#SBATCH --error=logs/VLR_ovstd_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Build Real CT Overlay Dataset — lung_axial (BiomedCLIP + LLaVA-Med) ───── -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_real_overlay_build_std.sub -# -# CPU-only job: extracts grayscale lesion-centred slices from real CTs AND -# generates bbox / contour / bbox_contour overlay PNGs using per-nodule masks. -# -# Profile: lung_axial (grayscale, for BiomedCLIP + LLaVA-Med) -# Data: 8 datasets (~14,333 nodules) -# Output: vlm_eval_real/lung_axial/eval_dataset.csv -# ────────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -PROFILE="lung_axial" -DATASET_DIR="${DATA_BASE}/vlm_eval_real/${PROFILE}" - -cd "${PROJ_DIR}" -mkdir -p logs - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -# ── Build ──────────────────────────────────────────────────────────────────── -echo "===============================================" -echo "Real CT Overlay Dataset Build — ${PROFILE}" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Output: ${DATASET_DIR}" -echo " Time: $(date)" -echo "===============================================" - -python -m itrialspace.evaluation.vlm_eval.build_real_dataset \ - --data-base "${DATA_BASE}" \ - --output-dir "${DATASET_DIR}" \ - --profile "${PROFILE}" \ - --datasets DLCS24 IMDCT LNDbv4 LUNA16 LUNA25 LUNGx NSCLCR \ - --overlays - -echo "" -echo "${PROFILE} dataset: ${DATASET_DIR}/eval_dataset.csv" -echo " $(wc -l < "${DATASET_DIR}/eval_dataset.csv") rows" -echo "Done at $(date)" diff --git a/itrialspace/infra/slurm/vlm_eval/vlm_std_rebuild.sub b/itrialspace/infra/slurm/vlm_eval/vlm_std_rebuild.sub deleted file mode 100644 index 69e597d77f6584ea74ded05fd489934fb68768e6..0000000000000000000000000000000000000000 --- a/itrialspace/infra/slurm/vlm_eval/vlm_std_rebuild.sub +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env bash -#SBATCH --job-name=STD_bld -#SBATCH --partition=defq -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=8 -#SBATCH --mem=32G -#SBATCH --output=logs/STD_build_%j.out -#SBATCH --error=logs/STD_build_%j.err - -# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── -ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" -itrialspace_activate_conda - - -# ── Incremental STD Eval-Dataset Rebuild (both profiles) ───────────────────── -# Rebuilds eval_dataset.csv with --skip-existing --overlays for STD modes 1-10. -# Code was updated post-build (Apr 12 20:58 vs 09:56) so this may recover -# previously-failed extraction cases. -# -# Submit from: ${PROJ_DIR} -# Usage: sbatch vlm_evaluation/vlm_std_rebuild.sub -# ───────────────────────────────────────────────────────────────────────────── - -set -euo pipefail - -PROJ_DIR="${PROJ_DIR}" -DATA_BASE="${ITRIALSPACE_DATA_DIR}" -MANIFEST_DIR="${DATA_BASE}/manifests" - -cd "${PROJ_DIR}" - -# ── Environment ────────────────────────────────────────────────────────────── -export PYTHONPATH="${PROJ_DIR}:${PYTHONPATH:-}" - -echo "===============================================" -echo "STD Eval-Dataset Incremental Rebuild" -echo " Host: $(hostname)" -echo " Job ID: ${SLURM_JOB_ID}" -echo " Time: $(date)" -echo "===============================================" - -# ── Collect STD manifests (modes 1-6, 8-10) ───────────────────────────────── -# Use an array to handle filenames with special characters (< > etc.) -MANIFESTS=() -for mode_dir in "${MANIFEST_DIR}"/mode{1,2,3,4,5,6,8,9,10}_*/; do - if [[ -d "${mode_dir}" ]]; then - for csv in "${mode_dir}"*.csv; do - if [[ -f "${csv}" ]]; then - MANIFESTS+=("${csv}") - fi - done - fi -done - -echo "Found ${#MANIFESTS[@]} manifest CSV(s)" - -# ── Record pre-rebuild sizes ───────────────────────────────────────────────── -PRE_LUNG=$(wc -l < "${DATA_BASE}/vlm_eval/lung_axial/eval_dataset.csv") -PRE_MED=$(wc -l < "${DATA_BASE}/vlm_eval/lung_axial_medgemma/eval_dataset.csv") -echo "Pre-rebuild: lung_axial=${PRE_LUNG} rows, lung_axial_medgemma=${PRE_MED} rows" - -# ── Profile 1: lung_axial (BiomedCLIP + LLaVA-Med) ────────────────────────── -echo "" -echo "=== Rebuilding lung_axial ===" -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest "${MANIFESTS[@]}" \ - --output-dir "${DATA_BASE}/vlm_eval/lung_axial" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile lung_axial \ - --overlays \ - --skip-existing \ - --workers 4 - -POST_LUNG=$(wc -l < "${DATA_BASE}/vlm_eval/lung_axial/eval_dataset.csv") -echo "Post-rebuild: lung_axial=${POST_LUNG} rows (was ${PRE_LUNG})" -echo "Recovered: $((POST_LUNG - PRE_LUNG)) new rows" - -# ── Profile 2: lung_axial_medgemma (MedGemma) ─────────────────────────────── -echo "" -echo "=== Rebuilding lung_axial_medgemma ===" -python -m itrialspace.evaluation.vlm_eval.build_dataset \ - --manifest "${MANIFESTS[@]}" \ - --output-dir "${DATA_BASE}/vlm_eval/lung_axial_medgemma" \ - --ct-base "${DATA_BASE}/generated_cts" \ - --mask-base "${DATA_BASE}/inserted_masks" \ - --profile lung_axial_medgemma \ - --overlays \ - --skip-existing \ - --workers 4 - -POST_MED=$(wc -l < "${DATA_BASE}/vlm_eval/lung_axial_medgemma/eval_dataset.csv") -echo "Post-rebuild: lung_axial_medgemma=${POST_MED} rows (was ${PRE_MED})" -echo "Recovered: $((POST_MED - PRE_MED)) new rows" - -echo "" -echo "Done at $(date)" diff --git a/itrialspace/nodmaisi_synth/README_NEURIPS_ANON.md b/itrialspace/nodmaisi_synth/README_NEURIPS_ANON.md deleted file mode 100644 index 5e26729ebb77aa5195fa0ca1ec4e0ee78f1776ef..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/README_NEURIPS_ANON.md +++ /dev/null @@ -1,507 +0,0 @@ -# NodMAISI Synthesizer — ControlNet-Conditioned CT Generation - -> **Module**: `nodmaisi_synth` within the [iTrialSpace](../README.md) pipeline -> **Location**: `/workspace/nodmaisi_synth/` -> **GPU Partition**: `vram48` (1× GPU, 16 CPUs, 64 GB RAM per task) - -NodMAISI (Nodule-conditioned Medical AI Synthesis and Inference) generates -realistic 3D CT volumes from binary organ+nodule segmentation masks produced -by the [iTrialSpace Mask Inserter](../itrialspace_mask_inserter/). It uses a -**ControlNet-conditioned rectified-flow diffusion model** built on MONAI to -produce full-resolution synthetic CTs (typically 512×512×256 at 0.7×0.7×1.25 mm -spacing). - ---- - -## Pipeline Position - -``` -┌──────────────┐ ┌───────────────────────┐ ┌──────────────────┐ ┌──────────────┐ -│ site_trials │────▶│ itrialspace_mask_ │────▶│ nodmaisi_synth │────▶│ detection_ │ -│ (cohort │ │ inserter │ │ (CT synthesis) │ │ inference │ -│ generation) │ │ (mask insertion) │ │ │ │ (CADx eval) │ -└──────────────┘ └───────────────────────┘ └──────────────────┘ └──────────────┘ - │ │ │ - │ CohortManifest │ audit.json + │ synthetic_ct.nii.gz - │ (CSV/JSON) │ inserted masks │ + QC PNGs - │ │ (.nii.gz) │ - ▼ ▼ ▼ - /Data/iTrialSpace/ - ├── inserted_masks/mode{1..13}_*/ - ├── generated_cts/mode{1..13}_*/ - └── nodmaisi_case_lists/ -``` - ---- - -## Directory Layout - -``` -nodmaisi_synth/ -├── README.md ← This file -├── INFERENCE_GUIDE.md ← Step-by-step inference guide -├── inference.sub ← Single-job SLURM script (standalone demo) -│ -├── models/ ← Pre-trained weights (2.4 GB total) -│ ├── autoencoder.pt ← VAE encoder/decoder (80 MB) -│ ├── diffusion_unet.pt ← Diffusion U-Net backbone (2.1 GB) -│ └── Experiments_NoMAISI_* ← ControlNet fine-tune (275 MB) -│ ..._finetune_500epoch_best.pt -│ -├── scripts/ ← Model code (training + inference) -│ ├── infer_testV2_controlnet.py ← Main ControlNet inference entry -│ ├── rectified_flow.py ← Rectified-flow sampler -│ ├── diff_model_setting.py ← Network architecture definitions -│ ├── transforms.py ← MONAI data transforms -│ ├── augmentation.py ← Training augmentations -│ ├── train_controlnet.py ← ControlNet training loop -│ ├── quality_check.py ← QC metric computation -│ └── ... ← utilities, schedulers, etc. -│ -├── configs/ ← JSON configuration files -│ ├── config_maisi3d-rflow.json ← Model architecture config -│ ├── infr_config_NoMAISI_controlnet.json ← Inference hyper-parameters -│ └── infr_env_NoMAISI_DLCSD24_demo.json ← Paths for demo inference -│ -├── tools/ ← iTrialSpace integration layer -│ ├── run_itrialspace_to_ct.py ← Main integration script (876 lines) -│ ├── integration_config.yaml ← Pipeline configuration -│ └── INTEGRATION_PLAN.md ← Original design document -│ -├── slurm_nodmaisi/ ← SLURM submission scripts -│ ├── submit_all_nodmaisi.sh ← Submit all 13 modes (single-job each) -│ ├── submit_array_jobs.sh ← Submit all 13 modes (array jobs, 1 GPU/case) -│ ├── nodmaisi_array.sub ← Generic array job template -│ ├── mode1_nodmaisi_array.sub ← Mode 1 specific array template -│ ├── template_nodmaisi_from_masks.sub ← Single-job template (all cases) -│ └── logs/ ← SLURM stdout/stderr -│ -├── data/ ← Demo/reference data -├── outputs/ ← Default output directory (standalone) -├── logs/ ← Runtime logs -└── NoMAISI/ ← Legacy model package (Python module) -``` - ---- - -## How It Works - -### Model Architecture - -NodMAISI uses a **3-stage pipeline** to synthesize a CT volume from a -segmentation mask: - -1. **Autoencoder** (`autoencoder.pt`): A 3D VAE that compresses 512×512×256 - voxel volumes into a 4×64×64×64 latent space (64× spatial compression). - -2. **Diffusion U-Net** (`diffusion_unet.pt`): A rectified-flow diffusion model - that learns the distribution of latent CT representations. Uses 30 - denoising steps at inference time. - -3. **ControlNet** (`*_finetune_500epoch_best.pt`): A conditioning network that - takes the organ+nodule segmentation mask and guides the diffusion process - to produce anatomically consistent CT volumes. - -``` -Segmentation Mask ──► ControlNet ──┐ - ├──► Diffusion U-Net ──► Autoencoder Decoder ──► Synthetic CT - Noise ──► (30 steps) ────┘ -``` - -### Integration Script (`tools/run_itrialspace_to_ct.py`) - -The integration script bridges iTrialSpace output (masks + audit) with the -NodMAISI model. It handles: - -- **Case discovery**: Reads `audit.json` files from Mask Inserter output, - or scans directories for `.nii.gz` mask files. -- **Subdirectory handling**: When masks are in subdirectories (e.g., - `size_curve_5-10mm/`, `size_curve_10-15mm/`), case IDs are automatically - prefixed with the subdirectory name to avoid collisions (e.g., - `size_curve_5-10mm/42`). -- **Geometry validation**: Checks that mask dimensions match NodMAISI's - valid sizes (256/384/512 XY, 128–768 Z). Auto-resizes if `auto_resize: true`. -- **Inference**: Calls `scripts.infer_testV2_controlnet` with proper - environment variables (`MONAI_DATA_DIRECTORY`, `PYTHONPATH`). -- **QC output**: Generates axial slice PNGs showing the synthetic CT with - nodule overlay. -- **Audit trail**: Writes per-case `nodmaisi_audit.json` with timing, - geometry, sanity checks, and output paths. - ---- - -## Quick Start - -### Prerequisites - -```bash -# Activate the conda environment -source /cm/shared/apps/miniconda/etc/profile.d/conda.sh -conda activate monai-auto3dseg - -# Verify GPU access -python -c "import torch; print(torch.cuda.get_device_name(0))" - -# Verify MONAI -python -c "import monai; print(monai.__version__)" -``` - -### 1. Standalone Demo Inference - -Run NodMAISI on the bundled demo data (single GPU job): - -```bash -cd /workspace/nodmaisi_synth -sbatch inference.sub -``` - -### 2. Single Mode — From iTrialSpace Masks - -Run all cases from a single trial mode in one GPU job: - -```bash -cd slurm_nodmaisi - -# Using audit.json (preferred — contains case metadata) -AUDIT_PATH=/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json \ -OUT_DIR=/Data/iTrialSpace/generated_cts/mode1_controlled_prevalence \ -sbatch template_nodmaisi_from_masks.sub - -# Or using mask directory (fallback) -MASK_ROOT=/Data/iTrialSpace/inserted_masks/mode2_size_detection_curve \ -OUT_DIR=/Data/iTrialSpace/generated_cts/mode2_size_detection_curve \ -sbatch template_nodmaisi_from_masks.sub -``` - -### 3. Array Jobs — One GPU Per Case (Recommended) - -Maximum parallelism: each case gets its own GPU task. - -```bash -cd slurm_nodmaisi - -# Submit all 13 modes as array jobs -./submit_array_jobs.sh - -# Submit specific modes only -./submit_array_jobs.sh 2 3 5 - -# Dry run (validate without running inference) -./submit_array_jobs.sh --dry-run - -# Control concurrency (default: 10 concurrent GPU tasks per mode) -./submit_array_jobs.sh --max-concurrent 20 - -# Override walltime per task (default: 2 hours) -./submit_array_jobs.sh --time 04:00:00 -``` - -### 4. Batch Submit — All 13 Modes (Single Jobs) - -One GPU job per mode (processes all cases sequentially): - -```bash -cd slurm_nodmaisi -./submit_all_nodmaisi.sh # all 13 modes -./submit_all_nodmaisi.sh 1 3 8 # selected modes only -./submit_all_nodmaisi.sh --dry-run # validate only -``` - ---- - -## The 13 Trial Modes - -| Mode | Name | Description | -|------|------|-------------| -| 1 | Controlled Prevalence | Vary cancer prevalence rates in screening cohorts | -| 2 | Size Detection Curve | Detection sensitivity across nodule size ranges (5–10, 10–15, 15–20, 20–30 mm) | -| 3 | Location Sensitivity | Detection by anatomical lobe (LUL, LLL, RUL, RML, RLL) | -| 4 | Demographic Stratification | Performance across age/sex/race groups | -| 5 | Counterfactual | Same patient with/without nodule insertion | -| 6 | Cross-Dataset | Nodules sourced from varied detection datasets | -| 7 | Bootstrap Confidence | Statistical confidence intervals via resampling | -| 8 | Algorithm Comparison | Head-to-head CADx evaluation under identical conditions | -| 9 | Screening Simulation | Time-series screening program simulation | -| 10 | Multi-Nodule Realism | Multi-nodule context effects on detection | -| 11 | Digital Twin Isolation | Single native nodule per case (lesion-level evaluation) | -| 12 | Digital Twin Complete | All native nodules per case (full burden reconstruction) | -| 13 | Digital Twin Cross | Cross-patient/cross-dataset nodule transfer | - -Modes 2 and 3 use **subdirectory layouts** (e.g., `size_curve_5-10mm/`, -`lobe_LUL/`). Case IDs are automatically prefixed with the subdirectory name -to avoid collisions across groups. - ---- - -## Configuration Reference - -### `tools/integration_config.yaml` - -| Section | Key | Description | -|---------|-----|-------------| -| `nodmaisi.project_dir` | Root of this module | Used to locate models/ and scripts/ | -| `nodmaisi.model_config` | `configs/config_maisi3d-rflow.json` | Model architecture | -| `nodmaisi.controlnet_config` | `configs/infr_config_NoMAISI_controlnet.json` | Inference params | -| `inference.num_inference_steps` | `30` | Diffusion denoising steps | -| `inference.seed` | `42` | Reproducibility seed | -| `inference.device` | `cuda:0` | GPU device | -| `itrialspace.nodule_label_value` | `23` | Label value for inserted nodules | -| `itrialspace.base_dir` | `/scratch/.../iTrialSpace` | Data root | -| `output.root` | `.../generated_cts` | Output base directory | -| `output.case_dir_template` | `case_{case_id}` | Per-case folder naming | -| `qc.enabled` | `true` | Generate QC PNG overlays | -| `geometry.valid_xy_sizes` | `[256, 384, 512]` | Accepted XY dimensions | -| `geometry.auto_resize` | `true` | Auto-resize masks to valid dims | - -### SLURM Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `TRIAL_MODE` | *required* | e.g., `mode1_controlled_prevalence` | -| `CASE_LIST` | auto-generated | Path to text file with case IDs | -| `AUDIT_PATH` | `inserted_masks/{mode}/audit.json` | iTrialSpace audit | -| `MASK_ROOT` | `inserted_masks/{mode}` | Mask directory (fallback) | -| `OUT_DIR` | `generated_cts/{mode}` | Output directory | -| `CONFIG_PATH` | `tools/integration_config.yaml` | Pipeline config | -| `DRY_RUN` | `false` | Validate without inference | -| `MAX_CONCURRENT` | `10` | Array job concurrency limit | - ---- - -## Output Structure - -For each case, the pipeline produces: - -``` -generated_cts/mode2_size_detection_curve/ -├── case_size_curve_5-10mm_42/ ← case directory (subdir-prefixed ID) -│ ├── synthetic_ct.nii.gz ← Generated CT volume -│ ├── input_mask.nii.gz ← Copy of input mask -│ ├── host_ct.nii.gz ← Symlink to original host CT -│ ├── nodmaisi_audit.json ← Per-case audit (timing, geometry, QC) -│ └── qc/ -│ ├── axial_slice_001.png ← QC overlay (3 slices through nodule) -│ ├── axial_slice_002.png -│ └── axial_slice_003.png -└── ... -``` - -### Per-Case Audit (`nodmaisi_audit.json`) - -```json -{ - "case_id": "size_curve_5-10mm/42", - "status": "success", - "input_mask_path": "/scratch/.../inserted_masks/mode2_.../size_curve_5-10mm/iTS--...nii.gz", - "synthetic_ct_path": "/scratch/.../generated_cts/mode2_.../case_size_curve_5-10mm_42/synthetic_ct.nii.gz", - "original_dim": [512, 512, 256], - "original_spacing": [0.7, 0.7, 1.25], - "inference_sec": 87.3, - "total_sec": 92.1, - "shape_match": true, - "has_nodule_label": true, - "ct_min_hu": -1024.0, - "ct_max_hu": 2134.0, - "has_nan": false -} -``` - ---- - -## GPU & Resource Requirements - -| Resource | Requirement | -|----------|-------------| -| GPU | 1× NVIDIA GPU with ≥48 GB VRAM (A6000, A100, etc.) | -| GPU Memory | ~35 GB peak (autoencoder sliding window + diffusion) | -| CPU | 16 cores (data loading, NIfTI I/O) | -| RAM | 64 GB | -| Disk per case | ~150 MB (synthetic CT + mask + QC) | -| Time per case | ~1.5–3 min (depends on volume size, GPU model) | -| Model weights | 2.4 GB (loaded once, reused across cases) | - ---- - -## Data Flow - -``` - ┌─────────────────────────────┐ - │ iTrialSpace Mask Inserter │ - │ (upstream) │ - └─────────────┬───────────────┘ - │ - ▼ - audit.json + inserted mask .nii.gz - (per-case: host CT, donor nodule, - organ seg, combined mask) - │ - ┌─────────────────────────────┤ - │ │ - ▼ ▼ - cases_from_audit() cases_from_mask_root() - (reads audit.json, (scans for *.nii.gz, - extracts case_id, parses case_id from - mask_path, host_ct) filename pattern) - │ │ - └──────────┬──────────────────┘ - │ - ▼ - List[CaseSpec] - (case_id, mask_path, dim, spacing) - │ - ▼ - ┌──────────────────────┐ - │ Geometry Validation │ - │ - Check XY ∈ {256, │ - │ 384, 512} │ - │ - Check Z ∈ {128, │ - │ 256, ..., 768} │ - │ - auto_resize if │ - │ needed │ - └──────────┬───────────┘ - │ - ▼ - ┌──────────────────────┐ - │ NodMAISI Inference │ - │ - Load autoencoder │ - │ - Load diffusion │ - │ - Load ControlNet │ - │ - 30-step rectified │ - │ flow sampling │ - └──────────┬───────────┘ - │ - ▼ - ┌──────────────────────┐ - │ Post-processing │ - │ - Save synthetic CT │ - │ - Generate QC PNGs │ - │ - Write audit JSON │ - │ - Link host CT │ - └──────────────────────┘ -``` - ---- - -## Subdirectory Layout & Case ID Collision Prevention - -Some trial modes (2, 3) organize masks into subdirectories by experimental -condition: - -``` -inserted_masks/mode2_size_detection_curve/ -├── size_curve_5-10mm/ -│ ├── audit.json (case_ids: 0, 1, ..., 99) -│ └── iTS--...--C0000--*.nii.gz -├── size_curve_10-15mm/ -│ ├── audit.json (case_ids: 0, 1, ..., 99) ← Same IDs! -│ └── iTS--...--C0000--*.nii.gz -├── size_curve_15-20mm/ -│ └── ... -└── size_curve_20-30mm/ - └── ... -``` - -**Problem**: Each subdirectory independently numbers case IDs from 0. Naively -merging would lose ~75% of data through key collisions. - -**Solution**: When subdirectory audits are detected (and no root-level -`audit.json` exists), case IDs are automatically prefixed with the -subdirectory name: - -``` -size_curve_5-10mm/0 ← unique -size_curve_5-10mm/1 -size_curve_10-15mm/0 ← unique (different prefix) -size_curve_10-15mm/1 -... -``` - -This is handled transparently in: -- `submit_array_jobs.sh` → `generate_case_list()` -- `run_itrialspace_to_ct.py` → `cases_from_audit()` and `cases_from_mask_root()` - ---- - -## Monitoring & Troubleshooting - -### Check Job Status - -```bash -squeue -u $USER # all your jobs -squeue -u $USER --name='NM_*' # NodMAISI jobs only -``` - -### View Logs - -```bash -# Array job logs -ls slurm_nodmaisi/logs/NM_*.out - -# Last 50 lines of a specific task -tail -50 slurm_nodmaisi/logs/NM_M2_arr_45012_42.out -``` - -### Common Issues - -| Symptom | Cause | Fix | -|---------|-------|-----| -| `CUDA out of memory` | Volume too large for GPU | Reduce `autoencoder_sliding_window_infer_size` in config | -| `No cases found` | Empty mask directory or failed insertion | Check mask inserter audit | -| `Shape mismatch` | Mask dims not in valid set | Set `geometry.auto_resize: true` in config | -| `FileNotFoundError: autoencoder.pt` | Models not in expected path | Verify `models/` directory has all 3 `.pt` files | -| `ModuleNotFoundError: monai` | Wrong conda env | `conda activate monai-auto3dseg` | - -### Cancel Jobs - -```bash -scancel -u $USER --name='NM_*' # cancel all NodMAISI jobs -scancel 45012 # cancel specific job -scancel 45012_42 # cancel specific array task -``` - ---- - -## File Reference - -| File | Lines | Purpose | -|------|-------|---------| -| `tools/run_itrialspace_to_ct.py` | 876 | Main integration: mask → CT synthesis pipeline | -| `tools/integration_config.yaml` | 71 | All configurable paths, inference params, QC settings | -| `scripts/infer_testV2_controlnet.py` | — | Low-level ControlNet inference (called by integration) | -| `scripts/rectified_flow.py` | — | Rectified-flow ODE sampler | -| `scripts/diff_model_setting.py` | — | U-Net + ControlNet architecture definitions | -| `scripts/transforms.py` | — | MONAI data transforms for medical images | -| `slurm_nodmaisi/submit_array_jobs.sh` | — | Batch array job submission (recommended) | -| `slurm_nodmaisi/submit_all_nodmaisi.sh` | — | Batch single-job submission | -| `slurm_nodmaisi/nodmaisi_array.sub` | — | Generic SLURM array template | -| `slurm_nodmaisi/template_nodmaisi_from_masks.sub` | — | Single-job SLURM template | -| `configs/config_maisi3d-rflow.json` | — | Model architecture hyperparameters | - ---- - -## Migration Note - -This module was moved from `/workspace/NoMAISI` into the iTrialSpace project -as `nodmaisi_synth` on 2025-03-07. A backward-compatibility symlink exists at -the old location: - -``` -/workspace/NoMAISI → /workspace/nodmaisi_synth -``` - -All path references in SLURM scripts, configs, and integration code have been -updated to the new canonical path. The symlink ensures that any running jobs -submitted before the move continue to work without interruption. - ---- - -## Related Modules - -| Module | Description | -|--------|-------------| -| [`site_trials/`](../site_trials/) | Cohort generation (demographic matching, trial design) | -| [`itrialspace_mask_inserter/`](../itrialspace_mask_inserter/) | Nodule mask insertion into host CTs | -| [`nodulemap/`](../nodulemap/) | Sigma.js visualization of 13,140 nodules across 7 datasets | -| [`retriever/`](../retriever/) | FastAPI + Streamlit search/matching interface | -| [`detection_inference/`](../detection_inference/) | CADx algorithm evaluation on generated CTs | -| [`itrialspace/`](../itrialspace/) | Core library (CohortManifest, placement, etc.) | diff --git a/itrialspace/nodmaisi_synth/configs/config_maisi3d-rflow.json b/itrialspace/nodmaisi_synth/configs/config_maisi3d-rflow.json deleted file mode 100644 index 1f2ee4619b464ba47e619191085214bcf042752e..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/configs/config_maisi3d-rflow.json +++ /dev/null @@ -1,150 +0,0 @@ -{ - "spatial_dims": 3, - "image_channels": 1, - "latent_channels": 4, - "include_body_region": false, - "mask_generation_latent_shape": [ - 4, - 64, - 64, - 64 - ], - "autoencoder_def": { - "_target_": "monai.apps.generation.maisi.networks.autoencoderkl_maisi.AutoencoderKlMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": "@image_channels", - "out_channels": "@image_channels", - "latent_channels": "@latent_channels", - "num_channels": [ - 64, - 128, - 256 - ], - "num_res_blocks": [2,2,2], - "norm_num_groups": 32, - "norm_eps": 1e-06, - "attention_levels": [ - false, - false, - false - ], - "with_encoder_nonlocal_attn": false, - "with_decoder_nonlocal_attn": false, - "use_checkpointing": false, - "use_convtranspose": false, - "norm_float16": true, - "num_splits": 4, - "dim_split": 1 - }, - "diffusion_unet_def": { - "_target_": "monai.apps.generation.maisi.networks.diffusion_model_unet_maisi.DiffusionModelUNetMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": "@latent_channels", - "out_channels": "@latent_channels", - "num_channels": [64, 128, 256, 512], - "attention_levels": [ - false, - false, - true, - true - ], - "num_head_channels": [ - 0, - 0, - 32, - 32 - ], - "num_res_blocks": 2, - "use_flash_attention": true, - "include_top_region_index_input": "@include_body_region", - "include_bottom_region_index_input": "@include_body_region", - "include_spacing_input": true, - "num_class_embeds": 128, - "resblock_updown": true, - "include_fc": true - }, - "controlnet_def": { - "_target_": "monai.apps.generation.maisi.networks.controlnet_maisi.ControlNetMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": "@latent_channels", - "num_channels": [64, 128, 256, 512], - "attention_levels": [ - false, - false, - true, - true - ], - "num_head_channels": [ - 0, - 0, - 32, - 32 - ], - "num_res_blocks": 2, - "use_flash_attention": true, - "conditioning_embedding_in_channels": 8, - "conditioning_embedding_num_channels": [8, 32, 64], - "num_class_embeds": 128, - "resblock_updown": true, - "include_fc": true - }, - "mask_generation_autoencoder_def": { - "_target_": "monai.apps.generation.maisi.networks.autoencoderkl_maisi.AutoencoderKlMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": 8, - "out_channels": 125, - "latent_channels": "@latent_channels", - "num_channels": [ - 32, - 64, - 128 - ], - "num_res_blocks": [1, 2, 2], - "norm_num_groups": 32, - "norm_eps": 1e-06, - "attention_levels": [ - false, - false, - false - ], - "with_encoder_nonlocal_attn": false, - "with_decoder_nonlocal_attn": false, - "use_flash_attention": false, - "use_checkpointing": true, - "use_convtranspose": true, - "norm_float16": true, - "num_splits": 8, - "dim_split": 1 - }, - "mask_generation_diffusion_def": { - "_target_": "monai.networks.nets.diffusion_model_unet.DiffusionModelUNet", - "spatial_dims": "@spatial_dims", - "in_channels": "@latent_channels", - "out_channels": "@latent_channels", - "channels":[64, 128, 256, 512], - "attention_levels":[false, false, true, true], - "num_head_channels":[0, 0, 32, 32], - "num_res_blocks": 2, - "use_flash_attention": true, - "with_conditioning": true, - "upcast_attention": true, - "cross_attention_dim": 10 - }, - "mask_generation_scale_factor": 1.0055984258651733, - "noise_scheduler": { - "_target_": "monai.networks.schedulers.rectified_flow.RFlowScheduler", - "num_train_timesteps": 1000, - "use_discrete_timesteps": false, - "use_timestep_transform": true, - "sample_method": "uniform", - "scale":1.4 - }, - "mask_generation_noise_scheduler": { - "_target_": "monai.networks.schedulers.ddpm.DDPMScheduler", - "num_train_timesteps": 1000, - "beta_start": 0.0015, - "beta_end": 0.0195, - "schedule": "scaled_linear_beta", - "clip_sample": false - } -} diff --git a/itrialspace/nodmaisi_synth/configs/infr_config_NoMAISI_controlnet.json b/itrialspace/nodmaisi_synth/configs/infr_config_NoMAISI_controlnet.json deleted file mode 100644 index 95f5dee643dfb75659cc11b0c8c77feaf1a5ff54..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/configs/infr_config_NoMAISI_controlnet.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "controlnet_train": { - "batch_size": 2, - "cache_rate": 0.0, - "fold": 1, - "lr": 1e-5, - "n_epochs": 500, - "weighted_loss_label": [23], - "weighted_loss": 100 - }, - "controlnet_infer": { - "num_inference_steps": 30, - "autoencoder_sliding_window_infer_size": [80, 80, 64], - "autoencoder_sliding_window_infer_overlap": 0.25, - "modality": 1 - } -} diff --git a/itrialspace/nodmaisi_synth/configs/infr_env_NoMAISI_DLCSD24_demo.json b/itrialspace/nodmaisi_synth/configs/infr_env_NoMAISI_DLCSD24_demo.json deleted file mode 100644 index 57c028265b7464aa6fff48a61591ad848a4f4b51..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/configs/infr_env_NoMAISI_DLCSD24_demo.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "model_dir": "./models/", - "output_dir": "./outputs/NoMAISI_DLCSD24_demo_512xy_256z_771p25m", - "tfevent_path": "./outputs/tfevent", - "trained_autoencoder_path": "./models/autoencoder.pt", - "trained_diffusion_path": "./models/diffusion_unet.pt", - "trained_controlnet_path": "./models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt", - "exp_name": "NoMAISI_DLCSD24_demo_512xy_256z_771p25m", - "data_base_dir": ["/home/ft42/ANod/itrialspace/nodmaisi_synth/data"], - "json_data_list": ["/home/ft42/ANod/itrialspace/nodmaisi_synth/data/infr_NoMAISI_DLCSD24_demo_512xy_256z_771p25m_dataset.json"] -} \ No newline at end of file diff --git a/itrialspace/nodmaisi_synth/models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt b/itrialspace/nodmaisi_synth/models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt deleted file mode 100644 index c5dfa7beb748dbacda8f7ca08f452dac2640c074..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e11ebc532c433316a13d30e97ab72bff42ad9f1dd841d36e7181a6d83986c71c -size 288268713 diff --git a/itrialspace/nodmaisi_synth/models/autoencoder.pt b/itrialspace/nodmaisi_synth/models/autoencoder.pt deleted file mode 100644 index 4956b34b62543d2ecac67f9350ff058e52fc7b3b..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/models/autoencoder.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1f8a7a056d0ebc00486edc43c26768bf1c12eaa6df9dd172e34598003be95eb3 -size 83831868 diff --git a/itrialspace/nodmaisi_synth/models/diffusion_unet.pt b/itrialspace/nodmaisi_synth/models/diffusion_unet.pt deleted file mode 100644 index 883c65af4c3cdcdb57c8c1ff93660e96dca53853..0000000000000000000000000000000000000000 --- a/itrialspace/nodmaisi_synth/models/diffusion_unet.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cfc1ec59782f5ac7c0d22dd501654732109a971b93cbaa6607c4106a7f29066f -size 2166600232 diff --git a/itrialspace/pyproject.toml b/itrialspace/pyproject.toml deleted file mode 100644 index 00273bba2345a076f7fcc54d01b72303634398e0..0000000000000000000000000000000000000000 --- a/itrialspace/pyproject.toml +++ /dev/null @@ -1,144 +0,0 @@ -[build-system] -requires = ["setuptools>=68.0", "wheel"] -build-backend = "setuptools.build_meta" - -[project] -name = "itrialspace" -version = "0.1.0" -description = "iTrialSpace — Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation" -readme = "README.md" -requires-python = ">=3.10" -# TODO: confirm license before public release (Apache-2.0 / MIT / BSD-3-Clause) -license = {text = "LicenseRef-TODO"} -authors = [{ name = "iTrialSpace contributors" }] -keywords = ["medical-imaging", "lung-ct", "synthetic-data", "clinical-trial", "CADe", "CADx", "VLM"] -classifiers = [ - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Intended Audience :: Science/Research", - "Topic :: Scientific/Engineering :: Medical Science Apps.", - "Operating System :: POSIX :: Linux", -] - -# Core dependencies — enough to build the nodule index, query, and plan trials. -dependencies = [ - "pandas>=1.5", - "numpy>=1.23", - "pyyaml>=6.0", -] - -[project.optional-dependencies] -# Mask insertion + NIfTI handling -imaging = ["nibabel>=5.0", "scipy>=1.10", "SimpleITK>=2.2"] - -# Interactive exploration apps: NoduleMap (FastAPI + sigma.js) and Retriever (FastAPI + Streamlit) -apps = [ - "fastapi>=0.104", - "uvicorn[standard]>=0.24", - "pydantic>=2.0", - "streamlit>=1.28", - "nibabel>=5.0", - "Pillow>=10.0", - "matplotlib>=3.5", - "requests>=2.28", - "scikit-learn>=1.2", - "umap-learn>=0.5", - "faiss-cpu>=1.7", - "pyarrow>=10.0", -] -# Backward-compatible alias for the previous name. -web = ["itrialspace[apps]"] - -# CT synthesis (NodMAISI). Heavy; torch/monai install is platform-specific — see docs/installation.md. -synthesis = [ - "monai>=1.3", - "nibabel>=5.0", - "scipy>=1.10", - "matplotlib>=3.5", - "scikit-image>=0.21", - "fire>=0.5", - "tqdm>=4.60", - "einops>=0.6", -] - -# Vision-Language Model evaluation. Model backends pulled separately — see docs/installation.md. -vlm = [ - "transformers>=4.40", - "open_clip_torch>=2.24", - "nibabel>=5.0", - "Pillow>=10.0", - "matplotlib>=3.5", - "seaborn>=0.12", -] - - -# OPTIONAL CADe/CADx evaluation — also requires EXTERNAL models/repos not bundled here. -# See docs/evaluation_external_dependencies.md before using. -eval = ["monai>=1.3", "nibabel>=5.0", "scipy>=1.10", "scikit-learn>=1.2"] - -# Developer tooling -dev = [ - "pytest>=7.0", - "ruff>=0.4", - "black>=24.0", - "pre-commit>=3.5", -] - -# Everything except the heavy/optional eval externals -all = [ - "itrialspace[imaging,apps,vlm,dev]", -] - -[project.scripts] -its = "itrialspace.cli:main" -its-insert = "itrialspace.mask_inserter.cli:main" -its-trials = "itrialspace.trials.run_trial:main" -its-nodulemap = "itrialspace.apps.nodulemap.cli.cli:main" -its-retriever = "itrialspace.apps.retriever.cli:main" - -[tool.setuptools.packages.find] -where = ["src"] -include = ["itrialspace*"] - -[tool.setuptools.package-data] -itrialspace = [ - "config/*.yaml", - "site/config/*.yaml", - "apps/nodulemap/configs/*.yaml", - "apps/nodulemap/frontend/static/*", - "synthesis/configs/*.json", -] - -[tool.ruff] -line-length = 100 -target-version = "py310" -extend-exclude = ["docs", "infra"] - -[tool.ruff.lint] -select = ["E", "F", "I", "W"] -ignore = [ - "E501", # line length handled by black - "E402", # module-level import not at top (needed for src-path bootstrap / lazy config) - "E741", # ambiguous variable names (research code uses l/I occasionally) - "E711", # `== None` — kept where pandas/None semantics are intentional - "E712", # `== True/False` — idiomatic in pandas boolean masks here - "F841", # unused locals — common in research code; not a correctness risk -] - -[tool.ruff.lint.per-file-ignores] -# __init__.py intentionally re-exports the public API. -"**/__init__.py" = ["F401"] -# Tests use fixtures/imports that linters misread as unused. -"tests/**" = ["F401", "F811", "E731"] -# Vendored MAISI inference code (run as scripts) — keep upstream style as-is. -"src/itrialspace/synthesis/scripts/**" = ["F401", "F403", "F405", "F841", "E711", "E712", "E721", "E722"] - -[tool.black] -line-length = 100 -target-version = ["py310", "py311"] - -[tool.pytest.ini_options] -markers = [ - "full_volume: tests that require real CT data (env-gated, skipped in CI)", -] -testpaths = ["tests"] diff --git a/itrialspace/requirements.lock.txt b/itrialspace/requirements.lock.txt deleted file mode 100644 index cded37e207297d2a535a378f6b72b142c090943c..0000000000000000000000000000000000000000 --- a/itrialspace/requirements.lock.txt +++ /dev/null @@ -1,149 +0,0 @@ -# Reproducible lock — exact freeze of the verified iTrialSpace environment. -# Python 3.10, linux-64, CUDA 12.1. Generated 2026-06-04. -# python3.10 -m venv .venv && . .venv/bin/activate -# pip install -r requirements.lock.txt && pip install -e . -# torch = cu121 build; MONAI = git-pinned dev commit. Full pipeline (incl. GPU -# synthesis) verified across modes 1-10 in this env. ---extra-index-url https://download.pytorch.org/whl/cu121 - -altair==6.1.0 -annotated-doc==0.0.4 -annotated-types==0.7.0 -anyio==4.13.0 -attrs==26.1.0 -black==26.5.1 -blinker==1.9.0 -cachetools==7.1.4 -certifi==2026.5.20 -cfgv==3.5.0 -charset-normalizer==3.4.7 -click==8.4.1 -contourpy==1.3.2 -cuda-bindings==13.3.1 -cuda-pathfinder==1.5.5 -cuda-toolkit==13.0.2 -cycler==0.12.1 -distlib==0.4.1 -einops==0.8.2 -exceptiongroup==1.3.1 -faiss-cpu==1.14.2 -fastapi==0.136.3 -filelock==3.29.0 -fire==0.7.1 -fonttools==4.63.0 -fsspec==2026.4.0 -ftfy==6.3.1 -gitdb==4.0.12 -GitPython==3.1.50 -h11==0.16.0 -hf-xet==1.5.0 -httpcore==1.0.9 -httptools==0.8.0 -httpx==0.28.1 -huggingface_hub==0.36.2 -identify==2.6.19 -idna==3.18 -ImageIO==2.37.3 -importlib_resources==7.1.0 -iniconfig==2.3.0 -itsdangerous==2.2.0 -Jinja2==3.1.6 -joblib==1.5.3 -jsonschema-specifications==2025.9.1 -jsonschema==4.26.0 -kiwisolver==1.5.0 -lazy-loader==0.5 -llvmlite==0.47.0 -markdown-it-py==4.2.0 -MarkupSafe==3.0.3 -matplotlib==3.10.9 -mdurl==0.1.2 -monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a -mpmath==1.3.0 -mypy_extensions==1.1.0 -narwhals==2.22.0 -networkx==3.4.2 -nibabel==5.4.2 -nodeenv==1.10.0 -numba==0.65.1 -numpy==1.26.4 -nvidia-cublas-cu12==12.1.3.1 -nvidia-cuda-cupti-cu12==12.1.105 -nvidia-cuda-nvrtc-cu12==12.1.105 -nvidia-cuda-runtime-cu12==12.1.105 -nvidia-cudnn-cu12==9.1.0.70 -nvidia-cufft-cu12==11.0.2.54 -nvidia-curand-cu12==10.3.2.106 -nvidia-cusolver-cu12==11.4.5.107 -nvidia-cusparse-cu12==12.1.0.106 -nvidia-nccl-cu12==2.20.5 -nvidia-nvjitlink-cu12==12.1.105 -nvidia-nvtx-cu12==12.1.105 -open_clip_torch==2.32.0 -packaging==26.0 -pandas==2.3.3 -pathspec==1.1.1 -pillow==12.2.0 -platformdirs==4.10.0 -pluggy==1.6.0 -pre_commit==4.6.0 -protobuf==6.33.6 -pyarrow==24.0.0 -pydantic==2.13.4 -pydantic_core==2.46.4 -pydeck==0.9.2 -Pygments==2.20.0 -pynndescent==0.6.0 -pyparsing==3.3.2 -pytest==9.0.3 -python-dateutil==2.9.0.post0 -python-discovery==1.4.0 -python-dotenv==1.2.2 -python-multipart==0.0.30 -pytokens==0.4.1 -pytz==2026.2 -PyYAML==6.0.3 -referencing==0.37.0 -regex==2026.5.9 -requests==2.34.2 -rich==15.0.0 -rpds-py==0.30.0 -ruff==0.15.15 -safetensors==0.7.0 -scikit-image==0.25.2 -scikit-learn==1.7.2 -scipy==1.15.3 -seaborn==0.13.2 -shellingham==1.5.4 -simpleitk==2.5.5 -six==1.17.0 -smmap==5.0.3 -starlette==1.2.1 -streamlit==1.58.0 -sympy==1.14.0 -tenacity==9.1.4 -termcolor==3.3.0 -threadpoolctl==3.6.0 -tifffile==2025.5.10 -timm==1.0.27 -tokenizers==0.21.4 -toml==0.10.2 -tomli==2.4.1 -torch==2.4.1+cu121 -torchvision==0.19.1+cu121 -tqdm==4.67.3 -transformers==4.51.3 -triton==3.0.0 -typer==0.25.1 -typing-inspection==0.4.2 -typing_extensions==4.15.0 -tzdata==2026.2 -umap-learn==0.5.12 -urllib3==2.7.0 -uvicorn==0.49.0 -uvloop==0.22.1 -virtualenv==21.4.2 -watchdog==6.0.0 -watchfiles==1.2.0 -wcwidth==0.7.0 -websockets==16.0 diff --git a/itrialspace/src/itrialspace.egg-info/PKG-INFO b/itrialspace/src/itrialspace.egg-info/PKG-INFO deleted file mode 100644 index 5dc26fdd06f4cdd4685bc2e8ee3953f6370f9c06..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace.egg-info/PKG-INFO +++ /dev/null @@ -1,168 +0,0 @@ -Metadata-Version: 2.4 -Name: itrialspace -Version: 0.1.0 -Summary: iTrialSpace — Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation -Author: iTrialSpace contributors -License: LicenseRef-TODO -Keywords: medical-imaging,lung-ct,synthetic-data,clinical-trial,CADe,CADx,VLM -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Intended Audience :: Science/Research -Classifier: Topic :: Scientific/Engineering :: Medical Science Apps. -Classifier: Operating System :: POSIX :: Linux -Requires-Python: >=3.10 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: pandas>=1.5 -Requires-Dist: numpy>=1.23 -Requires-Dist: pyyaml>=6.0 -Provides-Extra: imaging -Requires-Dist: nibabel>=5.0; extra == "imaging" -Requires-Dist: scipy>=1.10; extra == "imaging" -Requires-Dist: SimpleITK>=2.2; extra == "imaging" -Provides-Extra: apps -Requires-Dist: fastapi>=0.104; extra == "apps" -Requires-Dist: uvicorn[standard]>=0.24; extra == "apps" -Requires-Dist: pydantic>=2.0; extra == "apps" -Requires-Dist: streamlit>=1.28; extra == "apps" -Requires-Dist: nibabel>=5.0; extra == "apps" -Requires-Dist: Pillow>=10.0; extra == "apps" -Requires-Dist: matplotlib>=3.5; extra == "apps" -Requires-Dist: requests>=2.28; extra == "apps" -Requires-Dist: scikit-learn>=1.2; extra == "apps" -Requires-Dist: umap-learn>=0.5; extra == "apps" -Requires-Dist: faiss-cpu>=1.7; extra == "apps" -Requires-Dist: pyarrow>=10.0; extra == "apps" -Provides-Extra: web -Requires-Dist: itrialspace[apps]; extra == "web" -Provides-Extra: synthesis -Requires-Dist: monai>=1.3; extra == "synthesis" -Requires-Dist: nibabel>=5.0; extra == "synthesis" -Requires-Dist: scipy>=1.10; extra == "synthesis" -Requires-Dist: matplotlib>=3.5; extra == "synthesis" -Requires-Dist: scikit-image>=0.21; extra == "synthesis" -Requires-Dist: fire>=0.5; extra == "synthesis" -Requires-Dist: tqdm>=4.60; extra == "synthesis" -Requires-Dist: einops>=0.6; extra == "synthesis" -Provides-Extra: vlm -Requires-Dist: transformers>=4.40; extra == "vlm" -Requires-Dist: open_clip_torch>=2.24; extra == "vlm" -Requires-Dist: nibabel>=5.0; extra == "vlm" -Requires-Dist: Pillow>=10.0; extra == "vlm" -Requires-Dist: matplotlib>=3.5; extra == "vlm" -Requires-Dist: seaborn>=0.12; extra == "vlm" -Provides-Extra: eval -Requires-Dist: monai>=1.3; extra == "eval" -Requires-Dist: nibabel>=5.0; extra == "eval" -Requires-Dist: scipy>=1.10; extra == "eval" -Requires-Dist: scikit-learn>=1.2; extra == "eval" -Provides-Extra: dev -Requires-Dist: pytest>=7.0; extra == "dev" -Requires-Dist: ruff>=0.4; extra == "dev" -Requires-Dist: black>=24.0; extra == "dev" -Requires-Dist: pre-commit>=3.5; extra == "dev" -Provides-Extra: all -Requires-Dist: itrialspace[apps,dev,imaging,vlm]; extra == "all" -Dynamic: license-file - -# iTrialSpace - -**Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation.** - -> ⚠️ License is not yet finalized — see [`LICENSE`](LICENSE). Do not redistribute until confirmed. - -iTrialSpace turns medical-imaging AI evaluation from *"find more data"* into *"specify the -data you need."* It harmonizes **13,140 nodule profiles** from **7 public lung CT datasets**, -generates virtual clinical-trial cohorts across **13 trial modes**, inserts donor nodule masks -into real host anatomy, synthesizes CT volumes with a ControlNet-conditioned rectified-flow -diffusion model (**NodMAISI**), and evaluates **CADe/CADx** detectors and **vision-language -models** under systematically controlled conditions. - -## Why - -Public lung-screening datasets are narrow (NLST = heavy smokers, LUNA16 has no malignancy -labels, NSCLC-Radiomics = only large cancers), so AI models get tested on data that -under-represents where they fail. iTrialSpace lets you declare a cohort by its *statistical -properties* (prevalence, size distribution, lobe distribution, demographics) and manufactures -anatomically grounded synthetic CTs to match — enabling controlled, one-variable-at-a-time -experiments impossible with fixed retrospective datasets. - -## Architecture - -``` -itrialspace → trials → mask_inserter → synthesis → evaluation -(nodule index) (manifests) (mask paste) (NodMAISI CT) (CADe/CADx/VLM) - │ - ├─ nodulemap (graph viz) - └─ retriever (faceted search) -``` - -See [docs/architecture.md](docs/architecture.md) for the full component map. - -## Quickstart - -```bash -# 1. Environment -conda env create -f environment.yml && conda activate itrialspace - -# 2. Install (pick the extras you need — see Install matrix below) -pip install -e ".[imaging,web]" - -# 3. Configure paths -cp .env.example .env # edit ITRIALSPACE_DATA_DIR etc. - -# 4. Run unit tests (no external data required) -pytest -m "not full_volume" - -# 5. Build the nodule index and print stats (requires profile CSVs — see docs/data.md) -its index stats -``` - -## Install matrix - -| Extra | Installs | For | -|-------|----------|-----| -| *(base)* | pandas, numpy, pyyaml | Index, query, trial planning | -| `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI handling | -| `web` | fastapi, streamlit, faiss, umap | NoduleMap + Retriever UIs | -| `synthesis` | monai, (torch) | NodMAISI CT synthesis* | -| `vlm` | transformers, open_clip | VLM evaluation* | -| `eval` | monai, scikit-learn | CADe/CADx evaluation** | -| `dev` | pytest, ruff, black, pre-commit | Development | -| `all` | imaging + web + vlm + dev | Everything bundled | - -\* torch is platform-specific — see [docs/installation.md](docs/installation.md). -\*\* also needs **external** models/repos — see [docs/evaluation_external_dependencies.md](docs/evaluation_external_dependencies.md). - -## Console commands - -| Command | Does | -|---------|------| -| `its` | Umbrella CLI (index, query, info) | -| `its-insert` | Insert nodule masks from a cohort manifest | -| `its-trials` | Generate cohort manifests for the 13 trial modes | -| `its-nodulemap` | Launch the NoduleMap graph-visualization server | -| `its-retriever` | Launch the Retriever search API + UI | - -## Documentation - -- [Installation](docs/installation.md) · [Quickstart](docs/quickstart.md) · [Configuration](docs/configuration.md) -- [Architecture](docs/architecture.md) · [Pipeline](docs/pipeline.md) · [Trial modes](docs/trial_modes.md) -- [Data preparation](docs/data.md) · [Reproducibility](docs/reproducibility.md) -- [SKILL.md](SKILL.md) — exhaustive machine-readable reference for AI coding assistants - -## Data & models - -This repository contains **code only**. Source CT datasets and trained model weights are -**not** redistributed here (they carry their own licenses and are large). See -[docs/data.md](docs/data.md) and [docs/installation.md](docs/installation.md) for how to obtain -and lay them out. - -## Citation - -See [CITATION.cff](CITATION.cff). - -## Contributing - -See [CONTRIBUTING.md](CONTRIBUTING.md). All contributions run through CI (lint + tests + -portability gate). diff --git a/itrialspace/src/itrialspace.egg-info/SOURCES.txt b/itrialspace/src/itrialspace.egg-info/SOURCES.txt deleted file mode 100644 index ec60619fa428258f4619f566e28bdde5674f0504..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace.egg-info/SOURCES.txt +++ /dev/null @@ -1,156 +0,0 @@ -LICENSE -README.md -pyproject.toml -src/itrialspace/__init__.py -src/itrialspace/cli.py -src/itrialspace.egg-info/PKG-INFO -src/itrialspace.egg-info/SOURCES.txt -src/itrialspace.egg-info/dependency_links.txt -src/itrialspace.egg-info/entry_points.txt -src/itrialspace.egg-info/requires.txt -src/itrialspace.egg-info/top_level.txt -src/itrialspace/apps/__init__.py -src/itrialspace/apps/nodulemap/__init__.py -src/itrialspace/apps/nodulemap/__main__.py -src/itrialspace/apps/nodulemap/backend/__init__.py -src/itrialspace/apps/nodulemap/backend/app.py -src/itrialspace/apps/nodulemap/backend/data_store.py -src/itrialspace/apps/nodulemap/backend/export.py -src/itrialspace/apps/nodulemap/cli/__init__.py -src/itrialspace/apps/nodulemap/cli/cli.py -src/itrialspace/apps/nodulemap/client/__init__.py -src/itrialspace/apps/nodulemap/client/notebook_client.py -src/itrialspace/apps/nodulemap/configs/features.yaml -src/itrialspace/apps/nodulemap/embeddings/__init__.py -src/itrialspace/apps/nodulemap/embeddings/build_embeddings.py -src/itrialspace/apps/nodulemap/frontend/__init__.py -src/itrialspace/apps/nodulemap/frontend/static/index.html -src/itrialspace/apps/nodulemap/neighbors/__init__.py -src/itrialspace/apps/nodulemap/neighbors/build_edges.py -src/itrialspace/apps/nodulemap/tools/__init__.py -src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py -src/itrialspace/apps/nodulemap/tools/verify_purge.py -src/itrialspace/apps/retriever/__init__.py -src/itrialspace/apps/retriever/__main__.py -src/itrialspace/apps/retriever/cli.py -src/itrialspace/apps/retriever/engine.py -src/itrialspace/apps/retriever/notebook.py -src/itrialspace/apps/retriever/search.py -src/itrialspace/apps/retriever/similarity.py -src/itrialspace/apps/retriever/slicer.py -src/itrialspace/apps/retriever/api/__init__.py -src/itrialspace/apps/retriever/api/app.py -src/itrialspace/apps/retriever/api/models.py -src/itrialspace/apps/retriever/ui/__init__.py -src/itrialspace/apps/retriever/ui/app.py -src/itrialspace/config/__init__.py -src/itrialspace/config/datasets.yaml -src/itrialspace/config/settings.py -src/itrialspace/core/__init__.py -src/itrialspace/core/label.py -src/itrialspace/core/profile.py -src/itrialspace/core/schema.py -src/itrialspace/evaluation/__init__.py -src/itrialspace/evaluation/cade/__init__.py -src/itrialspace/evaluation/cade/chunk_csv.py -src/itrialspace/evaluation/cade/inference_CADe_at_locations.py -src/itrialspace/evaluation/cadx/__init__.py -src/itrialspace/evaluation/cadx/build_synthetic_candidate_csv.py -src/itrialspace/evaluation/cadx/check_csv.py -src/itrialspace/evaluation/vlm_eval/__init__.py -src/itrialspace/evaluation/vlm_eval/biomedclip_model.py -src/itrialspace/evaluation/vlm_eval/build_dataset.py -src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py -src/itrialspace/evaluation/vlm_eval/build_real_dataset.py -src/itrialspace/evaluation/vlm_eval/comparison.py -src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py -src/itrialspace/evaluation/vlm_eval/inference_cache.py -src/itrialspace/evaluation/vlm_eval/metrics.py -src/itrialspace/evaluation/vlm_eval/overlay.py -src/itrialspace/evaluation/vlm_eval/parsers.py -src/itrialspace/evaluation/vlm_eval/plots.py -src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py -src/itrialspace/evaluation/vlm_eval/prompt_templates.py -src/itrialspace/evaluation/vlm_eval/run_all.py -src/itrialspace/evaluation/vlm_eval/run_biomedclip.py -src/itrialspace/evaluation/vlm_eval/slice_extractor.py -src/itrialspace/evaluation/vlm_eval/models/__init__.py -src/itrialspace/evaluation/vlm_eval/models/llava_med.py -src/itrialspace/evaluation/vlm_eval/models/medgemma.py -src/itrialspace/evaluation/vlm_eval/runners/__init__.py -src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py -src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py -src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py -src/itrialspace/index/__init__.py -src/itrialspace/index/nodule_index.py -src/itrialspace/io/__init__.py -src/itrialspace/io/loader.py -src/itrialspace/io/registry.py -src/itrialspace/io/adapters/__init__.py -src/itrialspace/io/adapters/adapters.py -src/itrialspace/mask_inserter/__init__.py -src/itrialspace/mask_inserter/__main__.py -src/itrialspace/mask_inserter/cli.py -src/itrialspace/mask_inserter/inserter.py -src/itrialspace/mask_inserter/placement.py -src/itrialspace/mask_inserter/resample.py -src/itrialspace/mask_inserter/resolver_bridge.py -src/itrialspace/mask_inserter/tools/__init__.py -src/itrialspace/mask_inserter/tools/list_manifests.py -src/itrialspace/mask_inserter/tools/make_test_manifest.py -src/itrialspace/query/__init__.py -src/itrialspace/query/matcher.py -src/itrialspace/query/query_api.py -src/itrialspace/site/__init__.py -src/itrialspace/site/cohort_builder.py -src/itrialspace/site/insertion_planner.py -src/itrialspace/site/knowledge_base.py -src/itrialspace/site/manifest.py -src/itrialspace/site/path_resolver.py -src/itrialspace/site/sampling.py -src/itrialspace/site/spec.py -src/itrialspace/site/trial_modes.py -src/itrialspace/site/validation.py -src/itrialspace/site/config/paths.yaml -src/itrialspace/site/config/trials.yaml -src/itrialspace/synthesis/__init__.py -src/itrialspace/synthesis/configs/config_maisi3d-rflow.json -src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json -src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json -src/itrialspace/synthesis/scripts/__init__.py -src/itrialspace/synthesis/scripts/augmentation.py -src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py -src/itrialspace/synthesis/scripts/diff_model_create_training_data.py -src/itrialspace/synthesis/scripts/diff_model_infer.py -src/itrialspace/synthesis/scripts/diff_model_setting.py -src/itrialspace/synthesis/scripts/diff_model_train.py -src/itrialspace/synthesis/scripts/find_masks.py -src/itrialspace/synthesis/scripts/infer_controlnet.py -src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py -src/itrialspace/synthesis/scripts/infer_test_controlnet.py -src/itrialspace/synthesis/scripts/inference.py -src/itrialspace/synthesis/scripts/quality_check.py -src/itrialspace/synthesis/scripts/rectified_flow.py -src/itrialspace/synthesis/scripts/sample.py -src/itrialspace/synthesis/scripts/scheduler.py -src/itrialspace/synthesis/scripts/train_controlnet.py -src/itrialspace/synthesis/scripts/transforms.py -src/itrialspace/synthesis/scripts/utils.py -src/itrialspace/synthesis/scripts/utils_plot.py -src/itrialspace/synthesis/scripts/schedulers/__init__.py -src/itrialspace/synthesis/scripts/schedulers/ddim.py -src/itrialspace/synthesis/scripts/schedulers/ddpm.py -src/itrialspace/synthesis/scripts/schedulers/pndm.py -src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py -src/itrialspace/synthesis/scripts/schedulers/scheduler.py -src/itrialspace/synthesis/tools/__init__.py -src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py -src/itrialspace/trials/__init__.py -src/itrialspace/trials/run_trial.py -src/itrialspace/utils/__init__.py -tests/test_digital_twin_complete.py -tests/test_digital_twin_cross.py -tests/test_digital_twin_isolation.py -tests/test_itrialspace.py -tests/test_p0_fixes.py -tests/test_site.py \ No newline at end of file diff --git a/itrialspace/src/itrialspace.egg-info/dependency_links.txt b/itrialspace/src/itrialspace.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/itrialspace/src/itrialspace.egg-info/entry_points.txt b/itrialspace/src/itrialspace.egg-info/entry_points.txt deleted file mode 100644 index 19509a3bf1ecad34d3ffbb2e8b76bcc7960343d3..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace.egg-info/entry_points.txt +++ /dev/null @@ -1,6 +0,0 @@ -[console_scripts] -its = itrialspace.cli:main -its-insert = itrialspace.mask_inserter.cli:main -its-nodulemap = itrialspace.apps.nodulemap.cli.cli:main -its-retriever = itrialspace.apps.retriever.cli:main -its-trials = itrialspace.trials.run_trial:main diff --git a/itrialspace/src/itrialspace.egg-info/requires.txt b/itrialspace/src/itrialspace.egg-info/requires.txt deleted file mode 100644 index b856850c7d460540e5d27572b9b42aa2363ff6a9..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace.egg-info/requires.txt +++ /dev/null @@ -1,58 +0,0 @@ -pandas>=1.5 -numpy>=1.23 -pyyaml>=6.0 - -[all] -itrialspace[apps,dev,imaging,vlm] - -[apps] -fastapi>=0.104 -uvicorn[standard]>=0.24 -pydantic>=2.0 -streamlit>=1.28 -nibabel>=5.0 -Pillow>=10.0 -matplotlib>=3.5 -requests>=2.28 -scikit-learn>=1.2 -umap-learn>=0.5 -faiss-cpu>=1.7 -pyarrow>=10.0 - -[dev] -pytest>=7.0 -ruff>=0.4 -black>=24.0 -pre-commit>=3.5 - -[eval] -monai>=1.3 -nibabel>=5.0 -scipy>=1.10 -scikit-learn>=1.2 - -[imaging] -nibabel>=5.0 -scipy>=1.10 -SimpleITK>=2.2 - -[synthesis] -monai>=1.3 -nibabel>=5.0 -scipy>=1.10 -matplotlib>=3.5 -scikit-image>=0.21 -fire>=0.5 -tqdm>=4.60 -einops>=0.6 - -[vlm] -transformers>=4.40 -open_clip_torch>=2.24 -nibabel>=5.0 -Pillow>=10.0 -matplotlib>=3.5 -seaborn>=0.12 - -[web] -itrialspace[apps] diff --git a/itrialspace/src/itrialspace.egg-info/top_level.txt b/itrialspace/src/itrialspace.egg-info/top_level.txt deleted file mode 100644 index daa1bfff281e4b4d0f8d0d3519947972dcf0cbe2..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -itrialspace diff --git a/itrialspace/src/itrialspace/__init__.py b/itrialspace/src/itrialspace/__init__.py deleted file mode 100644 index 73b34583d2f9bce8b25e4350462944a9566180df..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -__version__ = "0.1.0" -from itrialspace.core.label import LabelNormaliser -from itrialspace.core.profile import NoduleProfile -from itrialspace.core.schema import ( - CORE_COLS, - DATASET_FLAGS, - DATASET_NAMES, - LOBE_NAMES, - REINSERTION_COLS, - SIDE_NAMES, - ZONE_NAMES, - CentralPeripheral, - Lobe, - Side, - Zone, -) -from itrialspace.index.nodule_index import NoduleIndex -from itrialspace.io.loader import DatasetLoader -from itrialspace.io.registry import DatasetRegistry -from itrialspace.query.matcher import MatchResult, ReinsertionMatcher, ReinsertionTarget -from itrialspace.query.query_api import NoduleQuery diff --git a/itrialspace/src/itrialspace/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 349ad9d9369df37ef920d5b2d7d2a52bad534a7e..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/__pycache__/cli.cpython-310.pyc deleted file mode 100644 index 7fabeba0a372bf641a423485bcaf308a2a305227..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/__pycache__/cli.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/__init__.py b/itrialspace/src/itrialspace/apps/__init__.py deleted file mode 100644 index a299eed667856f58627e70aed6255396d3b24e2d..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Interactive exploration tools layered on the iTrialSpace core. - -These are optional applications (not part of the generative engine): NoduleMap -(embedding graph visualization) and Retriever (faceted search). They depend on the -core (`itrialspace.core`/`index`/`query`); the core never depends on them. -Install with: ``pip install -e ".[apps]"``. -""" diff --git a/itrialspace/src/itrialspace/apps/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index bf8c331ebce9f9d92ecaa1d0732cb3e61ac1a344..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/__init__.py deleted file mode 100644 index a12b94c984c2831416725a823a54fe8c84e7de78..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# -*- coding: utf-8 -*- -""" -iTrialSpace NoduleMap -- embedding-based interactive nodule similarity explorer. - -Subpackages ------------ -embeddings : Embedding generation pipeline (PCA, UMAP, t-SNE). -neighbors : KNN index + edge list computation (FAISS). -backend : FastAPI server for graph + neighbor queries. -cli : Command-line interface for batch + serve modes. -client : Jupyter notebook helper. -""" - -__version__ = "0.1.0" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__main__.py b/itrialspace/src/itrialspace/apps/nodulemap/__main__.py deleted file mode 100644 index d795b81e20d3b5e2aa3140d56634451c75df6857..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -"""Allow running as `python -m itrialspace.apps.nodulemap`.""" -from itrialspace.apps.nodulemap.cli.cli import main - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index cb55602b17525c858dead8d28733ccdcd3196252..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__main__.cpython-310.pyc deleted file mode 100644 index e5f2cebd9ecda5c3f85fcb1f37fecced5fd2bef7..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__main__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/backend/__init__.py deleted file mode 100644 index 12cafe069bd462bcd20e267d94d75e69a43adeb9..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/backend/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: utf-8 -*- -""" -nodulemap.backend — FastAPI server + data store + neighbor queries + exports. -""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 62dbed3902c57d2b1d0c6d87dcd3f4798fca62ec..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/app.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/app.cpython-310.pyc deleted file mode 100644 index 834e38303664a046982915df8b18af1cdb58ba0b..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/app.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/data_store.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/data_store.cpython-310.pyc deleted file mode 100644 index 397bec3a580b71423081c7eb8a5e54a24d96d3f5..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/data_store.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/export.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/export.cpython-310.pyc deleted file mode 100644 index c0c902ffa95b49715fc4634ac95f3e26c38ea89e..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/export.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/app.py b/itrialspace/src/itrialspace/apps/nodulemap/backend/app.py deleted file mode 100644 index 04ad1c4839d13cc9c562ea82fa2832cf65cc9650..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/backend/app.py +++ /dev/null @@ -1,481 +0,0 @@ -# -*- coding: utf-8 -*- -""" -app.py — FastAPI backend for NoduleMap. - -Endpoints: - GET / → serves static frontend - GET /api/models → available embedding models - GET /api/graph → nodes + edges for map view - GET /api/node/{node_id} → full metadata for a node - GET /api/node/{node_id}/neighbors → ranked neighbor list - POST /api/export → export selection to file - GET /api/filters → available filter values - GET /health → health check - -Start: - uvicorn nodulemap.backend.app:create_app --factory --host 0.0.0.0 --port 8422 -""" -from __future__ import annotations - -import os -from pathlib import Path - -from fastapi import FastAPI, HTTPException -from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import HTMLResponse -from fastapi.staticfiles import StaticFiles -from pydantic import BaseModel - -from itrialspace.apps.nodulemap.backend.data_store import DataStore -from itrialspace.apps.nodulemap.backend.export import Exporter -from itrialspace.config import settings - -# Artifact directory (configurable via env var; default resolved by settings: -# $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts) -_DEFAULT_ARTIFACT_DIR = str(settings.nodulemap_artifacts_dir()) -_EXPORT_DIR = os.environ.get( - "NODULEMAP_EXPORTS", - str(settings.output_dir() / "nodulemap_exports"), -) -_STATIC_DIR = Path(__file__).parent.parent / "frontend" / "static" - - -# ── Pydantic models ────────────────────────────────────────────────────── - - -class GraphRequest(BaseModel): - vis_model: str = "UMAP_2D" - search_model: str = "UMAP_2D" - feature_set: str = "reinsertion_core" - k: int = 5 - mode: str = "closest" - scope: str = "cross_dataset" - color_by: str = "dataset" - filters: dict | None = None - - -class NeighborRequest(BaseModel): - model: str = "UMAP_2D" - feature_set: str = "reinsertion_core" - k: int = 10 - scope: str = "cross_dataset" - datasets: list[str] | None = None - balance_by_dataset: bool = False - - -class ExportRequest(BaseModel): - node_id: str - model: str = "UMAP_2D" - feature_set: str = "reinsertion_core" - k: int = 10 - scope: str = "cross_dataset" - format: str = "csv" # csv | json | donors - - -# ── App factory ────────────────────────────────────────────────────────── - - -def create_app(artifact_dir: str | None = None) -> FastAPI: - """Create the NoduleMap FastAPI app.""" - art_dir = artifact_dir or _DEFAULT_ARTIFACT_DIR - - app = FastAPI( - title="iTrialSpace NoduleMap", - version="0.1.0", - description="Embedding-based interactive nodule similarity explorer", - ) - - app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_methods=["*"], - allow_headers=["*"], - ) - - # Lazy init data store (on first request) - store: dict = {"instance": None} - exporter = Exporter(_EXPORT_DIR) - - def get_store() -> DataStore: - if store["instance"] is None: - print(f"[NoduleMap] Loading artifacts from {art_dir}") - store["instance"] = DataStore(art_dir) - return store["instance"] - - # ── Health ────────────────────────────────────────────────────────── - @app.get("/health") - def health(): - ds = get_store() - return { - "status": "ok", - "version": "0.1.0", - "models": ds.available_models, - "artifact_dir": art_dir, - } - - # ── Models ────────────────────────────────────────────────────────── - @app.get("/api/models") - def list_models(): - ds = get_store() - # Probe readiness: each model has embeddings + metadata + edge files - model_health: list[dict] = [] - for m in ds.available_models: - mn, fs = m["model_name"], m["feature_set"] - ok = True - try: - meta = ds.get_metadata(mn, fs) - emb = ds.get_embeddings(mn, fs) - ok = len(meta) == emb.shape[0] > 0 - except Exception: - ok = False - model_health.append({**m, "ready": ok}) - return { - "models": ds.available_models, - "layout_models": ds.layout_models, - "search_models": ds.search_models, - "health": model_health, - "version": "0.2.0", - } - - # ── Filters ───────────────────────────────────────────────────────── - @app.get("/api/filters") - def get_filters( - model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - ): - """Return all unique values for filterable columns.""" - ds = get_store() - meta = ds.get_metadata(model, feature_set) - - def unique_list(col): - if col in meta.columns: - return sorted([str(v) for v in meta[col].dropna().unique()]) - return [] - - return { - "datasets": unique_list("dataset"), - "labels": ["benign", "malignant", "unlabelled"], - "lobes": unique_list("reinsertion_lobe"), - "zones": unique_list("reinsertion_lung_zone"), - "sides": unique_list("reinsertion_lung_side"), - "size_buckets": unique_list("size_bucket"), - "label_sources": unique_list("label_source") if "label_source" in meta.columns else [], - "population_types": ( - unique_list("population_type") if "population_type" in meta.columns else [] - ), - "diameter_range": { - "min": ( - float(meta["reinsertion_nodule_diam_mm"].min()) - if "reinsertion_nodule_diam_mm" in meta.columns - else 0 - ), - "max": ( - float(meta["reinsertion_nodule_diam_mm"].max()) - if "reinsertion_nodule_diam_mm" in meta.columns - else 100 - ), - }, - } - - # ── Graph ─────────────────────────────────────────────────────────── - @app.post("/api/graph") - def get_graph(req: GraphRequest): - ds = get_store() - try: - data = ds.get_graph_data( - vis_model=req.vis_model, - search_model=req.search_model, - feature_set=req.feature_set, - k=req.k, - mode=req.mode, - scope=req.scope, - color_by=req.color_by, - filters=req.filters, - ) - return data - except FileNotFoundError as e: - raise HTTPException(status_code=404, detail=str(e)) - - # Also support GET for simpler access - @app.get("/api/graph") - def get_graph_get( - vis_model: str = "UMAP_2D", - search_model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - k: int = 5, - mode: str = "closest", - scope: str = "cross_dataset", - color_by: str = "dataset", - datasets: str | None = None, - label: str | None = None, - lobe: str | None = None, - zone: str | None = None, - side: str | None = None, - size_bucket: str | None = None, - diameter_min: float | None = None, - diameter_max: float | None = None, - ): - filters = {} - if datasets: - filters["datasets"] = datasets.split(",") - if label: - filters["label"] = label - if lobe: - filters["lobe"] = lobe.split(",") - if zone: - filters["zone"] = zone - if side: - filters["side"] = side - if size_bucket: - filters["size_bucket"] = size_bucket.split(",") - if diameter_min is not None: - filters["diameter_min"] = diameter_min - if diameter_max is not None: - filters["diameter_max"] = diameter_max - - req = GraphRequest( - vis_model=vis_model, - search_model=search_model, - feature_set=feature_set, - k=k, - mode=mode, - scope=scope, - color_by=color_by, - filters=filters if filters else None, - ) - return get_graph(req) - - # ── Node detail ───────────────────────────────────────────────────── - @app.get("/api/node/{node_id}") - def get_node( - node_id: str, - model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - ): - ds = get_store() - try: - return ds.get_node_detail(node_id, model, feature_set) - except KeyError: - raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") - - # ── Axial thumbnail ──────────────────────────────────────────────── - @app.get("/api/node/{node_id}/axial_thumbnail") - def get_axial_thumbnail( - node_id: str, - model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - ): - from fastapi.responses import Response - - ds = get_store() - try: - png_bytes = ds.get_axial_thumbnail(node_id, model, feature_set) - except KeyError: - raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") - if png_bytes is None: - raise HTTPException( - status_code=404, detail="Thumbnail unavailable: CT or mask not found" - ) - return Response(content=png_bytes, media_type="image/png") - - # ── Neighbors ─────────────────────────────────────────────────────── - @app.get("/api/node/{node_id}/neighbors") - def get_neighbors( - node_id: str, - model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - k: int = 10, - scope: str = "cross_dataset", - datasets: str | None = None, - balance_by_dataset: bool = False, - search_backend: str = "weighted", - debug: int = 0, - ): - import time as _time - - ds = get_store() - canon_model = ds._canon(model) - ds_list = datasets.split(",") if datasets else None - t0 = _time.perf_counter() - try: - results = ds.query_neighbors( - node_id=node_id, - model_name=model, - feature_set=feature_set, - k=k, - scope=scope, - datasets=ds_list, - balance_by_dataset=balance_by_dataset, - search_backend=search_backend, - ) - elapsed = _time.perf_counter() - t0 - resp: dict = { - "query_node_id": node_id, - "k": k, - "scope": scope, - "neighbors": results, - } - if debug: - emb = ds.get_embeddings(canon_model, feature_set) - resp["_debug"] = { - "model_requested": model, - "model_canonical": canon_model, - "feature_set": feature_set, - "embedding_dim": int(emb.shape[1]), - "n_embeddings": int(emb.shape[0]), - "elapsed_ms": round(elapsed * 1000, 2), - "n_results": len(results), - } - return resp - except KeyError: - raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") - - # ── Export ────────────────────────────────────────────────────────── - @app.post("/api/export") - def export_data(req: ExportRequest): - ds = get_store() - try: - query_node = ds.get_node(req.node_id, req.model, req.feature_set) - neighbors = ds.query_neighbors( - node_id=req.node_id, - model_name=req.model, - feature_set=req.feature_set, - k=req.k, - scope=req.scope, - ) - - if req.format == "donors": - path = exporter.export_candidate_donors(neighbors) - else: - path = exporter.export_neighbors( - query_node=query_node, - neighbors=neighbors, - model_name=req.model, - feature_set=req.feature_set, - k=req.k, - scope=req.scope, - fmt=req.format, - ) - return {"status": "ok", "path": path} - except KeyError: - raise HTTPException(status_code=404, detail=f"Node not found: {req.node_id}") - - # ── Debug endpoints ─────────────────────────────────────────────── - @app.get("/debug/layout") - def debug_layout( - model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - limit: int = 5, - ): - """Return first *limit* 2D positions + node_ids for quick sanity-check.""" - ds = get_store() - try: - pos = ds.get_positions(model, feature_set) - meta = ds.get_metadata(model, feature_set) - ids = meta["node_id"].values[:limit].tolist() - coords = pos[:limit].tolist() - return { - "model": model, - "feature_set": feature_set, - "n_total": len(pos), - "samples": [{"node_id": i, "x": c[0], "y": c[1]} for i, c in zip(ids, coords)], - } - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) - - @app.get("/debug/search") - def debug_search( - node_id: str = "", - model: str = "UMAP_2D", - feature_set: str = "reinsertion_core", - k: int = 3, - ): - """Quick neighbor probe with debug info (embedding dim, index type, timing).""" - import time as _time - - ds = get_store() - if not node_id: - # return first available node_id so the user can try - meta = ds.get_metadata(model, feature_set) - node_id = meta["node_id"].values[0] - try: - emb = ds.get_embeddings(model, feature_set) - t0 = _time.perf_counter() - results = ds.query_neighbors( - node_id=node_id, - model_name=model, - feature_set=feature_set, - k=k, - ) - elapsed = _time.perf_counter() - t0 - return { - "query_node_id": node_id, - "model": model, - "embedding_dim": int(emb.shape[1]), - "n_embeddings": int(emb.shape[0]), - "k": k, - "elapsed_ms": round(elapsed * 1000, 2), - "neighbors": [ - { - "node_id": r["node_id"], - "distance": r["distance"], - "similarity": r["similarity"], - } - for r in results - ], - } - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) - - @app.get("/debug/alignment") - def debug_alignment(feature_set: str = "reinsertion_core"): - """Check node_id alignment across all models for a given feature set.""" - ds = get_store() - report: dict = {"feature_set": feature_set, "models": {}} - ref_ids = None - ref_name = None - for m in ds.available_models: - if m["feature_set"] != feature_set: - continue - mn = m["model_name"] - try: - meta = ds.get_metadata(mn, feature_set) - ids = meta["node_id"].values - entry = {"n_nodes": len(ids), "first_5": ids[:5].tolist(), "aligned": True} - if ref_ids is None: - ref_ids = ids - ref_name = mn - elif len(ids) != len(ref_ids) or not (ids == ref_ids).all(): - entry["aligned"] = False - entry["ref_model"] = ref_name - report["models"][mn] = entry - except Exception as e: - report["models"][mn] = {"error": str(e)} - return report - - # ── Static frontend ───────────────────────────────────────────────── - if _STATIC_DIR.exists(): - app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static") - - @app.get("/", response_class=HTMLResponse) - def serve_frontend(): - index = _STATIC_DIR / "index.html" - if index.exists(): - content = index.read_text() - return HTMLResponse( - content=content, - headers={ - "Cache-Control": "no-cache, no-store, must-revalidate", - "Pragma": "no-cache", - "Expires": "0", - }, - ) - return "

NoduleMap frontend not found

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

NoduleMap — frontend not built. Static dir: {}

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

iTrialSpace · NoduleMap

-
Tushar Lab · Dept. of Radiology & Imaging Sciences · University of Arizona
-

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

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

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

-

Repository: - github.com/tusharlabratory/itrialspace

-

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

-
⚠ Research use only. NoduleMap and the synthetic data it - explores are for research and method development. Not for clinical use and not a - medical device.
-
- -
-
-
- - - - - - - - - - - diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__init__.py deleted file mode 100644 index f7eb7ec58c8f7b83db7132a764bdec2018b54477..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: utf-8 -*- -""" -nodulemap.neighbors — KNN index + edge list computation. -""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 7b74ba2a63da33f36d137e83bab6e2c12378b91e..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/build_edges.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/build_edges.cpython-310.pyc deleted file mode 100644 index 1d99ff9e929e346a4da0837f75137d87fe9bc007..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/build_edges.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/search_space.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/search_space.cpython-310.pyc deleted file mode 100644 index 3753d798a5bcfbc6f4bd1b9a36d41e55af5ad1d4..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/search_space.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/build_edges.py b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/build_edges.py deleted file mode 100644 index 869261d24428d9dceb19e730c29277ea32e33799..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/build_edges.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -""" -build_edges.py — compute KNN edge lists for the NoduleMap graph. - -Edges encode *similarity in the SEARCH space*, not the 2D layout. The space is selectable -(see neighbors/search_space.py): - - - ``weighted`` (default) clinical donor-matching metric (L1), matches ReinsertionMatcher - - ``feature_l2`` exact L2 on the standardized full feature vector - - ``embedding`` L2 on the reduced embedding (legacy; comparison only) - -Edge files keep the per-(feature_set, model) name the DataStore expects; only their *content* -changes with ``--space``. Uses FAISS (exact) or sklearn fallback. - -Usage (CLI): - itrialspace-nodulemap edges --model UMAP_2D --feature-set reinsertion_core \\ - --k 5 --space weighted --outdir ./nodulemap_artifacts -""" -from __future__ import annotations - -import time -from pathlib import Path -from typing import Literal - -import numpy as np -import pandas as pd - -from itrialspace.apps.nodulemap.neighbors import search_space - - -class EdgeBuilder: - """Build KNN edge lists from saved artifacts, in a selectable search space.""" - - def __init__(self, artifact_dir: str, verbose: bool = True): - self._dir = Path(artifact_dir) - self._verbose = verbose - - def _log(self, msg: str) -> None: - if self._verbose: - print(f" [{time.strftime('%H:%M:%S')}] {msg}") - - def build( - self, - model_name: str, - feature_set: str = "reinsertion_core", - k: int = 5, - mode: Literal["closest", "farthest"] = "closest", - scope: Literal["cross_dataset", "within_dataset"] = "cross_dataset", - space: str = "weighted", - ) -> str: - """Build edge list and save to parquet. Returns output path.""" - tag = f"{feature_set}__{model_name}" - - # Metadata (node_id, dataset + reinsertion_* needed by the weighted space) - meta_path = self._dir / f"metadata_{tag}.parquet" - if not meta_path.exists(): - raise FileNotFoundError(f"Metadata not found: {meta_path}") - meta = pd.read_parquet(meta_path) - - matrix = search_space.build_search_matrix(space, self._dir, feature_set, model_name, meta) - metric = search_space.metric_for(space) - assert len(meta) == matrix.shape[0], "Metadata/matrix length mismatch" - self._log(f"Search space '{space}' (metric={metric}) matrix: {matrix.shape}") - - if scope == "within_dataset": - edges = self._build_within_dataset(matrix, meta, k, mode, metric) - else: - edges = self._build_cross_dataset(matrix, meta, k, mode, metric) - - out_name = f"edges_{tag}_k{k}_{mode}_{scope}.parquet" - out_path = self._dir / out_name - edges.to_parquet(out_path, index=False) - self._log(f"Saved {len(edges)} edges → {out_path}") - return str(out_path) - - def _build_cross_dataset(self, matrix, meta, k, mode, metric) -> pd.DataFrame: - """All-vs-all KNN search.""" - n = matrix.shape[0] - actual_k = min(k + 1, n) # +1 because the query includes self - self._log(f"Cross-dataset KNN (k={k}, mode={mode}, n={n}) …") - t0 = time.time() - if mode == "farthest": - distances, indices = self._farthest_neighbors_brute(matrix, actual_k, metric) - else: - distances, indices = search_space.knn(matrix, matrix, actual_k, metric) - self._log(f"KNN search done in {time.time() - t0:.1f}s") - return self._to_edge_df(meta, indices, distances, k, mode) - - def _build_within_dataset(self, matrix, meta, k, mode, metric) -> pd.DataFrame: - """Per-dataset KNN search.""" - all_edges = [] - for ds in meta["dataset"].unique(): - mask = meta["dataset"].values == ds - idx_map = np.where(mask)[0] - sub = matrix[mask] - n = len(sub) - if n <= 1: - continue - actual_k = min(k + 1, n) - self._log(f" {ds}: {n} nodes, k={min(k, n - 1)}") - if mode == "farthest": - dists, inds = self._farthest_neighbors_brute(sub, actual_k, metric) - else: - dists, inds = search_space.knn(sub, sub, actual_k, metric) - sub_meta = meta.iloc[idx_map].reset_index(drop=True) - all_edges.append(self._to_edge_df(sub_meta, inds, dists, min(k, n - 1), mode)) - if not all_edges: - return pd.DataFrame(columns=["src_id", "dst_id", "distance", "similarity", "rank"]) - return pd.concat(all_edges, ignore_index=True) - - def _farthest_neighbors_brute(self, matrix, k, metric): - """Brute-force farthest-neighbor search (true distances).""" - from sklearn.metrics import pairwise_distances - - skm = "manhattan" if metric == "l1" else "euclidean" - n = matrix.shape[0] - batch = 2000 - all_d = np.zeros((n, k), dtype=np.float32) - all_i = np.zeros((n, k), dtype=np.int64) - for s in range(0, n, batch): - e = min(s + batch, n) - D = pairwise_distances(matrix[s:e], matrix, metric=skm) - top_k = np.argpartition(-D, min(k, D.shape[1] - 1), axis=1)[:, :k] - for i in range(e - s): - order = top_k[i][np.argsort(-D[i, top_k[i]])] - all_i[s + i] = order - all_d[s + i] = D[i, order] - return all_d, all_i - - def _to_edge_df(self, meta, indices, distances, k, mode) -> pd.DataFrame: - """Convert KNN output (true distances) to an edge DataFrame.""" - rows = [] - node_ids = meta["node_id"].values - for i in range(len(meta)): - rank = 0 - for j in range(indices.shape[1]): - nb = indices[i, j] - if nb == i: - continue - dist = float(max(distances[i, j], 0.0)) - rank += 1 - rows.append( - { - "src_id": node_ids[i], - "dst_id": node_ids[nb], - "distance": round(dist, 6), - "similarity": round(float(np.exp(-dist)), 6), - "rank": rank, - } - ) - if rank >= k: - break - return pd.DataFrame(rows) - - def build_multiple_k( - self, - model_name: str, - feature_set: str = "reinsertion_core", - k_values: list[int] | None = None, - mode: str = "closest", - space: str = "weighted", - ) -> list[str]: - """Build edges for multiple K values.""" - if k_values is None: - k_values = [3, 5, 10, 25] - return [self.build(model_name, feature_set, k=k, mode=mode, space=space) for k in k_values] diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/search_space.py b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/search_space.py deleted file mode 100644 index 6549006ed4adf4522b835a5226731fead48f3cfe..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/search_space.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- -""" -search_space.py — similarity/search backends for NoduleMap. - -The map's *layout* (2D embeddings) and its *search* (donor ranking / k-NN) are -deliberately decoupled. Search must run on a faithful, reduced-free space — never on a -2D/16D embedding. Three backends are provided: - - - ``weighted`` (default) — reproduces the clinical donor-matching metric of - :class:`itrialspace.query.matcher.ReinsertionMatcher` *exactly* as an - L1 (Manhattan) distance on a weighted feature matrix, so NoduleMap's - "similar donors" agree with the reinsertion pipeline. - - ``feature_l2`` — exact L2 on the standardized full feature vector - (``features_.npy``). - - ``embedding`` — L2 on the reduced embedding (legacy; kept for comparison only). - -Why L1 for ``weighted``: the matcher score is -``w_cc·|Δcc|/100 + w_pleural·|Δpleural|/max_p + w_diam·|Δdiam|/max_d + lobe_penalty·𝟙[lobe≠]`` -— a weighted sum of absolute differences plus a lobe indicator. Encoding each numeric as a -scaled column and the lobe as a one-hot scaled by ``lobe_penalty/2`` makes the **L1 distance -between two rows equal the matcher score** (a one-hot lobe mismatch differs in two positions -→ ``2·(lobe_penalty/2) = lobe_penalty``). -""" -from __future__ import annotations - -from pathlib import Path - -import numpy as np -import pandas as pd - -from itrialspace.query.matcher import ReinsertionMatcher - -DEFAULT_WEIGHTS = dict(ReinsertionMatcher.DEFAULT_WEIGHTS) -BACKENDS = ("weighted", "feature_l2", "embedding") - - -def metric_for(backend: str) -> str: - """Distance metric a backend uses: 'l1' for weighted, 'l2' otherwise.""" - return "l1" if backend == "weighted" else "l2" - - -def weighted_matrix(meta: pd.DataFrame, weights: dict | None = None) -> np.ndarray: - """Build the weighted feature matrix whose L1 distance == ReinsertionMatcher score. - - Uses the reinsertion_* columns present in NoduleMap metadata. ``max_p``/``max_d`` are - taken over the whole set (matching the matcher's normalisation). - """ - w = {**DEFAULT_WEIGHTS, **(weights or {})} - - cc = pd.to_numeric(meta["reinsertion_lobe_cc_pct"], errors="coerce").to_numpy(float) - pl = pd.to_numeric(meta["reinsertion_pleural_dist_mm"], errors="coerce").to_numpy(float) - dm = pd.to_numeric(meta["reinsertion_nodule_diam_mm"], errors="coerce").to_numpy(float) - - finite_p = pl[np.isfinite(pl)] - finite_d = dm[np.isfinite(dm)] - max_p = max(float(finite_p.max()) if finite_p.size else 1.0, 1.0) - max_d = max(float(finite_d.max()) if finite_d.size else 1.0, 1.0) - - cc_fill = float(np.nanmedian(cc)) if np.isfinite(np.nanmedian(cc)) else 0.0 - cc = np.nan_to_num(cc, nan=cc_fill) - pl = np.nan_to_num(pl, nan=max_p) - dm = np.nan_to_num(dm, nan=0.0) - - cols = [ - (w["w_cc"] / 100.0) * cc, - (w["w_pleural"] / max_p) * pl, - (w["w_diam"] / max_d) * dm, - ] - lobe = pd.get_dummies(meta["reinsertion_lobe"].astype(str)) - lobe_mat = lobe.to_numpy(float) * (w["lobe_penalty"] / 2.0) - - return np.column_stack(cols + [lobe_mat]).astype(np.float32) - - -def build_search_matrix( - backend: str, - artifact_dir: str | Path, - feature_set: str, - model_name: str, - meta: pd.DataFrame, - weights: dict | None = None, -) -> np.ndarray: - """Return the (n, d) matrix to run k-NN on for the given backend.""" - artifact_dir = Path(artifact_dir) - if backend == "weighted": - return weighted_matrix(meta, weights) - if backend in ("feature_l2", "features"): - p = artifact_dir / f"features_{feature_set}.npy" - if not p.exists(): - raise FileNotFoundError( - f"Feature matrix not found: {p}. Rebuild embeddings to generate it " - f"(its-nodulemap build ...)." - ) - return np.load(p).astype(np.float32) - if backend == "embedding": - p = artifact_dir / f"embeddings_{feature_set}__{model_name}.npy" - if not p.exists(): - raise FileNotFoundError(f"Embeddings not found: {p}") - return np.load(p).astype(np.float32) - raise ValueError(f"Unknown search backend '{backend}'. Choose from {BACKENDS}.") - - -def knn(base: np.ndarray, queries: np.ndarray, k: int, metric: str = "l2"): - """k-NN of ``queries`` against ``base``. Returns (true_distances, indices), (m, k). - - Uses FAISS when available (exact IndexFlat), else sklearn. Distances are returned as - true (non-squared) distances in both cases. - """ - base = np.ascontiguousarray(base, dtype=np.float32) - queries = np.ascontiguousarray(queries, dtype=np.float32) - k = int(min(k, base.shape[0])) - try: - import faiss - - d = base.shape[1] - index = faiss.IndexFlat(d, faiss.METRIC_L1) if metric == "l1" else faiss.IndexFlatL2(d) - index.add(base) - dists, inds = index.search(queries, k) - if metric != "l1": - dists = np.sqrt(np.maximum(dists, 0.0)) - return dists, inds - except ImportError: - from sklearn.neighbors import NearestNeighbors - - nn = NearestNeighbors( - n_neighbors=k, metric=("manhattan" if metric == "l1" else "euclidean") - ) - nn.fit(base) - return nn.kneighbors(queries) diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index abc5b794be69a01ad6065b5a761c2b35f258cfd3..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/rebuild_artifacts.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/rebuild_artifacts.cpython-310.pyc deleted file mode 100644 index aca038694940c9f7541d5e67a64fc9023b860d66..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/rebuild_artifacts.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/similarity_report.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/similarity_report.cpython-310.pyc deleted file mode 100644 index 2a8e246ab79f8b2abe46de8ea0c495d355faed5a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/similarity_report.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/verify_purge.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/verify_purge.cpython-310.pyc deleted file mode 100644 index 102479d5a3ee0bb690156e4588ca2daa657994d1..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/verify_purge.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py deleted file mode 100644 index 68e057e5f01c5c6c77136461962ddadd470e53fc..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python3 -""" -rebuild_artifacts.py -- delete stale NoduleMap artifacts and rebuild from scratch. - -This ensures no NLST3D data remains in embeddings, metadata, or edge lists. - -Usage: - python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean - python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --outdir ./nodulemap_artifacts - python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --models PCA_2D UMAP_2D - python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --skip-edges # faster: only embeddings -""" -from __future__ import annotations - -import argparse -import glob -import os -import sys -import time -from pathlib import Path - -# Ensure project root is importable -PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent -sys.path.insert(0, str(PROJECT_ROOT)) - -DEFAULT_ARTIFACT_DIR = str(PROJECT_ROOT / "nodulemap_artifacts") - -ARTIFACT_PATTERNS = [ - "embeddings_*.npy", - "features_*.npy", - "metadata_*.parquet", - "edges_*.parquet", - "preprocessor_*.pkl", - "info_*.yaml", - "id_map*", - "positions_*", - "*.faiss", - "*.duckdb", - "*.duckdb.wal", -] - - -def clean_artifacts(artifact_dir: str) -> int: - """Delete all existing artifacts. Returns count of files deleted.""" - deleted = 0 - for pattern in ARTIFACT_PATTERNS: - for f in glob.glob(os.path.join(artifact_dir, pattern)): - os.remove(f) - deleted += 1 - return deleted - - -def rebuild( - artifact_dir: str, - models: list[str] | None = None, - feature_set: str = "reinsertion_core", - skip_edges: bool = False, - space: str = "weighted", - verbose: bool = True, -) -> dict: - """Rebuild all artifacts from scratch.""" - from itrialspace.apps.nodulemap.embeddings.build_embeddings import EmbeddingBuilder - from itrialspace.apps.nodulemap.neighbors.build_edges import EdgeBuilder - - if verbose: - print(f"\n{'=' * 60}") - print(" NoduleMap Artifact Rebuild") - print(f"{'=' * 60}\n") - - # Build NoduleIndex - builder = EmbeddingBuilder.from_defaults(verbose=verbose) - - # Check NLST3D is absent - datasets = sorted(builder._df["dataset"].unique().tolist()) - if "NLST3D" in datasets: - print("FATAL: NLST3D is still present in NoduleIndex!") - print("Fix datasets.yaml and profile CSVs before rebuilding.") - sys.exit(1) - - if verbose: - print(f"\n Datasets in index: {datasets}") - print(f" Total nodules: {len(builder._df):,}") - print() - - if models is None: - models = builder.list_models() - - results = {} - for model in models: - if verbose: - print(f"\n{'=' * 60}\n Building {model} ...\n{'=' * 60}") - t0 = time.time() - result = builder.build(model, feature_set, artifact_dir) - elapsed = time.time() - t0 - results[model] = result - if verbose: - print(f" {model}: {result['embeddings_shape']} ({elapsed:.1f}s)") - - # Build edges - if not skip_edges: - eb = EdgeBuilder(artifact_dir, verbose=verbose) - for model in models: - if verbose: - print(f"\n Building edges for {model} (space={space}) ...") - eb.build_multiple_k(model, feature_set, space=space) - - # Print dataset inventory from rebuilt metadata - if verbose: - print(f"\n{'=' * 60}") - print(" Post-Rebuild Dataset Inventory") - print(f"{'=' * 60}\n") - - import pandas as pd - - # Use any metadata file - meta_path = os.path.join(artifact_dir, f"metadata_{feature_set}__{models[0]}.parquet") - if os.path.exists(meta_path): - meta = pd.read_parquet(meta_path) - print(f" Total nodes: {len(meta):,}") - print(f" Datasets: {sorted(meta['dataset'].unique().tolist())}") - print() - print(f" {'Dataset':<10} {'Count':>8}") - print(" " + "-" * 20) - for ds, cnt in meta["dataset"].value_counts().sort_index().items(): - print(f" {ds:<10} {cnt:>8,}") - print() - if "NLST3D" in meta["dataset"].values: - print(" FAIL: NLST3D found in rebuilt artifacts!") - sys.exit(1) - else: - print(" NLST3D absent: CONFIRMED") - - return results - - -def main(): - parser = argparse.ArgumentParser(description="Rebuild NoduleMap artifacts") - parser.add_argument( - "--clean", - action="store_true", - required=True, - help="Delete existing artifacts before rebuild (required)", - ) - parser.add_argument( - "--outdir", - default=DEFAULT_ARTIFACT_DIR, - help=f"Artifact directory (default: {DEFAULT_ARTIFACT_DIR})", - ) - parser.add_argument( - "--models", nargs="*", default=None, help="Model names to build (default: all)" - ) - parser.add_argument( - "--feature-set", default="reinsertion_core", help="Feature set (default: reinsertion_core)" - ) - parser.add_argument( - "--skip-edges", action="store_true", help="Skip edge list computation (faster)" - ) - parser.add_argument( - "--space", - choices=["weighted", "feature_l2", "embedding"], - default="weighted", - help="Search space for edges (default: weighted = clinical ReinsertionMatcher metric)", - ) - args = parser.parse_args() - - artifact_dir = args.outdir - os.makedirs(artifact_dir, exist_ok=True) - - if args.clean: - n = clean_artifacts(artifact_dir) - print(f"Cleaned {n} stale artifact files from {artifact_dir}") - - rebuild( - artifact_dir=artifact_dir, - models=args.models, - feature_set=args.feature_set, - skip_edges=args.skip_edges, - space=args.space, - ) - - print("\nDone.") - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/similarity_report.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/similarity_report.py deleted file mode 100644 index 57d88eded2413dcf6d03024b8496c958e95a758b..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/tools/similarity_report.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- coding: utf-8 -*- -""" -similarity_report.py — measure NoduleMap search quality across backends. - -Quantifies two things so design choices are *measured*, not asserted: - -1. **k-NN concordance** — for a random sample of query nodes, the average fraction of the - top-k neighbours that share the query's lobe / size-bucket / side / (known) malignancy - label. Higher = more anatomically/clinically coherent neighbourhoods. Compared across - search backends: ``weighted`` (clinical metric) vs ``feature_l2`` (full feature space) - vs ``embedding`` (the reduced 2D/16D space — what was used before). -2. **Layout trustworthiness** — sklearn trustworthiness of each 2D embedding w.r.t. the full - feature space (are *displayed* neighbourhoods faithful?). - -Usage: - python -m itrialspace.apps.nodulemap.tools.similarity_report \\ - --artifact-dir "$NODULEMAP_ARTIFACTS" --k 10 --sample 1000 -""" -from __future__ import annotations - -import argparse -import json -from pathlib import Path - -import numpy as np -import pandas as pd - -from itrialspace.apps.nodulemap.neighbors import search_space - -_CONCORDANCE_COLS = { - "lobe": "reinsertion_lobe", - "size_bucket": "size_bucket", - "side": "reinsertion_lung_side", -} - - -def _list_models(artifact_dir: Path, feature_set: str) -> list[tuple[str, int]]: - out = [] - for f in sorted(artifact_dir.glob(f"embeddings_{feature_set}__*.npy")): - model = f.stem.replace(f"embeddings_{feature_set}__", "") - nd = np.load(f, mmap_mode="r").shape[1] - out.append((model, nd)) - return out - - -def _concordance(meta: pd.DataFrame, matrix: np.ndarray, metric: str, sample_idx, k: int) -> dict: - queries = matrix[sample_idx] - dists, inds = search_space.knn(matrix, queries, k + 1, metric) - scores = {key: [] for key in _CONCORDANCE_COLS} - scores["label"] = [] - for qi, row_inds in zip(sample_idx, inds): - nbrs = [j for j in row_inds if j != qi][:k] - if not nbrs: - continue - for key, col in _CONCORDANCE_COLS.items(): - if col in meta.columns: - qv = meta.iloc[qi][col] - share = np.mean([meta.iloc[j][col] == qv for j in nbrs]) - scores[key].append(float(share)) - # malignancy concordance only over labelled query+neighbours - if "label" in meta.columns: - ql = meta.iloc[qi]["label"] - if pd.notna(ql): - lab = [meta.iloc[j]["label"] for j in nbrs if pd.notna(meta.iloc[j]["label"])] - if lab: - scores["label"].append(float(np.mean([v == ql for v in lab]))) - return {key: (round(float(np.mean(v)), 4) if v else None) for key, v in scores.items()} - - -def main(): - ap = argparse.ArgumentParser(description="NoduleMap search-quality report") - ap.add_argument("--artifact-dir", default=None) - ap.add_argument("--feature-set", default="reinsertion_core") - ap.add_argument("--k", type=int, default=10) - ap.add_argument("--sample", type=int, default=1000, help="query nodes for concordance") - ap.add_argument("--trust-sample", type=int, default=2000, help="nodes for trustworthiness") - ap.add_argument("--seed", type=int, default=42) - args = ap.parse_args() - - from itrialspace.config import settings - - art = Path(args.artifact_dir or settings.nodulemap_artifacts_dir()) - fs = args.feature_set - models = _list_models(art, fs) - if not models: - raise SystemExit(f"No embeddings found in {art} for feature_set '{fs}'.") - - # Metadata is identical across models; use the first. - meta = pd.read_parquet(art / f"metadata_{fs}__{models[0][0]}.parquet") - n = len(meta) - rng = np.random.default_rng(args.seed) - sample_idx = rng.choice(n, size=min(args.sample, n), replace=False) - - # ── k-NN concordance per backend ─────────────────────────────────── - rows = [] - # model-independent backends - for backend in ("weighted", "feature_l2"): - M = search_space.build_search_matrix(backend, art, fs, models[0][0], meta) - c = _concordance(meta, M, search_space.metric_for(backend), sample_idx, args.k) - rows.append({"backend": backend, "space": backend, **c}) - # embedding backend — per model (this is the "search in reduced space" being replaced) - for model, nd in models: - M = search_space.build_search_matrix("embedding", art, fs, model, meta) - c = _concordance(meta, M, "l2", sample_idx, args.k) - rows.append({"backend": "embedding", "space": f"{model}({nd}D)", **c}) - conc = pd.DataFrame(rows) - - # ── Layout trustworthiness (2D models vs full feature space) ──────── - from sklearn.manifold import trustworthiness - - feat = np.load(art / f"features_{fs}.npy").astype(np.float32) - t_idx = rng.choice(n, size=min(args.trust_sample, n), replace=False) - trust = [] - for model, nd in models: - if nd != 2: - continue - emb = np.load(art / f"embeddings_{fs}__{model}.npy").astype(np.float32) - tw = trustworthiness(feat[t_idx], emb[t_idx, :2], n_neighbors=args.k) - trust.append({"model": model, "trustworthiness": round(float(tw), 4)}) - - # ── Emit ──────────────────────────────────────────────────────────── - report = { - "feature_set": fs, - "n_nodes": int(n), - "k": args.k, - "n_query_sample": int(len(sample_idx)), - "concordance": conc.to_dict(orient="records"), - "trustworthiness": trust, - "notes": [ - "Concordance = mean fraction of top-k neighbours sharing the query's attribute.", - "weighted = clinical ReinsertionMatcher metric (L1); feature_l2 = full 22-D space; " - "embedding = reduced layout space (legacy search).", - "Higher concordance = more coherent donor neighbourhoods for reinsertion.", - ], - } - (art / "nodulemap_similarity_report.json").write_text(json.dumps(report, indent=2)) - - md = ["# NoduleMap search-quality report", ""] - md.append( - f"- feature_set: `{fs}` · nodes: {n:,} · k={args.k} · " f"query sample={len(sample_idx)}" - ) - md.append("") - md.append("## k-NN concordance (fraction of top-k neighbours sharing attribute)") - md.append("") - md.append("| backend | space | lobe | size_bucket | side | malignancy |") - md.append("|---|---|---|---|---|---|") - for r in rows: - md.append( - f"| {r['backend']} | {r['space']} | {r.get('lobe')} | " - f"{r.get('size_bucket')} | {r.get('side')} | {r.get('label')} |" - ) - md.append("") - md.append("## Layout trustworthiness (2D embedding vs full feature space)") - md.append("") - md.append("| layout model | trustworthiness |") - md.append("|---|---|") - for t in trust: - md.append(f"| {t['model']} | {t['trustworthiness']} |") - md.append("") - md.append( - "> weighted/feature_l2 are the recommended **search** backends; 2D embeddings " - "are **layout only**. Higher concordance for weighted/feature_l2 vs embedding " - "confirms search should not run in the reduced space." - ) - (art / "nodulemap_similarity_report.md").write_text("\n".join(md)) - - print("\n".join(md)) - print(f"\nWrote {art/'nodulemap_similarity_report.md'} and .json") - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/verify_purge.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/verify_purge.py deleted file mode 100644 index 1af41ca1afbea01de9e0c24707a9eb373b9c3639..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/nodulemap/tools/verify_purge.py +++ /dev/null @@ -1,148 +0,0 @@ -#!/usr/bin/env python3 -""" -verify_purge.py — Post-rebuild verification that NLST3D is fully absent -from every NoduleMap artifact. - -Checks: - 1. Metadata parquets: no rows with dataset == "NLST3D" - 2. Info YAMLs: n_samples matches metadata row count - 3. Embeddings: .npy row count matches metadata - 4. Edge parquets: no src_id / dst_id starting with "NLST3D_" - 5. Preprocessor PKLs: exist and are loadable - 6. Node count: consistent across all models - -Exit code: - 0 = all checks passed - 1 = at least one check failed - -Usage: - python -m itrialspace.apps.nodulemap.tools.verify_purge --artifact-dir ./nodulemap_artifacts -""" -from __future__ import annotations - -import argparse -import pickle -import sys -from pathlib import Path - -import numpy as np -import pandas as pd -import yaml - - -def verify(artifact_dir: str) -> bool: - """Run all checks. Returns True if clean.""" - art = Path(artifact_dir) - ok = True - n_nodes_set: set[int] = set() - - print(f"\n{'=' * 64}") - print(" NoduleMap NLST3D Purge Verification") - print(f" Artifact dir: {art}") - print(f"{'=' * 64}\n") - - # ── 1. Metadata parquets ───────────────────────────────────────── - meta_files = sorted(art.glob("metadata_*.parquet")) - if not meta_files: - _fail("No metadata parquets found") - return False - - for mf in meta_files: - df = pd.read_parquet(mf) - tag = mf.stem.replace("metadata_", "") - datasets = sorted(df["dataset"].unique()) - n = len(df) - n_nodes_set.add(n) - - if "NLST3D" in datasets: - nlst_n = (df["dataset"] == "NLST3D").sum() - _fail(f"{mf.name}: NLST3D found ({nlst_n} rows)") - ok = False - else: - _pass(f"{mf.name}: {n:,} rows, {len(datasets)} datasets — no NLST3D") - - # Check for NLST3D in node_id - if "node_id" in df.columns: - nlst_ids = df["node_id"].str.startswith("NLST3D_").sum() - if nlst_ids > 0: - _fail(f"{mf.name}: {nlst_ids} node_ids start with NLST3D_") - ok = False - - # ── 2. Embeddings .npy ─────────────────────────────────────────── - emb_files = sorted(art.glob("embeddings_*.npy")) - for ef in emb_files: - arr = np.load(ef) - tag = ef.stem.replace("embeddings_", "") - n_nodes_set.add(arr.shape[0]) - _pass(f"{ef.name}: {arr.shape} float32") - - # ── 3. Info YAMLs ──────────────────────────────────────────────── - info_files = sorted(art.glob("info_*.yaml")) - for yf in info_files: - with open(yf) as f: - info = yaml.safe_load(f) - n_yaml = info.get("n_samples", -1) - n_nodes_set.add(n_yaml) - _pass(f"{yf.name}: n_samples={n_yaml}") - - # ── 4. Edge parquets ───────────────────────────────────────────── - edge_files = sorted(art.glob("edges_*.parquet")) - for ef in edge_files: - edf = pd.read_parquet(ef) - tag = ef.stem.replace("edges_", "") - bad_src = edf["src_id"].str.startswith("NLST3D_").sum() - bad_dst = edf["dst_id"].str.startswith("NLST3D_").sum() - if bad_src > 0 or bad_dst > 0: - _fail(f"{ef.name}: NLST3D references ({bad_src} src, {bad_dst} dst)") - ok = False - else: - _pass(f"{ef.name}: {len(edf):,} edges — no NLST3D refs") - - # ── 5. Preprocessor PKLs ──────────────────────────────────────── - pkl_files = sorted(art.glob("preprocessor_*.pkl")) - for pf in pkl_files: - try: - with open(pf, "rb") as f: - pickle.load(f) - _pass(f"{pf.name}: loadable") - except Exception as e: - _fail(f"{pf.name}: cannot load — {e}") - ok = False - - # ── 6. Cross-model consistency ─────────────────────────────────── - if len(n_nodes_set) == 1: - _pass(f"All artifacts have consistent node count: {n_nodes_set.pop():,}") - else: - _fail(f"Inconsistent node counts across artifacts: {n_nodes_set}") - ok = False - - # ── Summary ────────────────────────────────────────────────────── - print(f"\n{'=' * 64}") - if ok: - print(" RESULT: ALL CHECKS PASSED — NLST3D fully purged") - else: - print(" RESULT: CHECKS FAILED — NLST3D contamination detected") - print(f"{'=' * 64}\n") - - return ok - - -def _pass(msg: str) -> None: - print(f" [PASS] {msg}") - - -def _fail(msg: str) -> None: - print(f" [FAIL] {msg}") - - -def main(): - parser = argparse.ArgumentParser(description="Verify NLST3D purge from NoduleMap artifacts") - parser.add_argument("--artifact-dir", required=True, help="Path to artifact directory") - args = parser.parse_args() - - clean = verify(args.artifact_dir) - sys.exit(0 if clean else 1) - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/apps/retriever/__init__.py b/itrialspace/src/itrialspace/apps/retriever/__init__.py deleted file mode 100644 index 97e8f89e84c79a5a51237a23e1d6a8fa0c55fcbf..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -""" -iTrialSpace Retriever — interactive retrieval + visualization framework. - -Three deployment modes: - 1. Full Web App: Streamlit + FastAPI backend - 2. Headless: FastAPI backend + Jupyter notebook client - 3. Library + CLI: Pure Python API + command-line tools - -Quick start (library mode): - from itrialspace.apps.retriever import RetrieverEngine - engine = RetrieverEngine.from_defaults() - results = engine.search(datasets=["DLCS24"], label=1, diameter_range=(5, 20)) - similar = engine.find_similar("DLCS24_n0001", k=10) -""" - -__version__ = "0.1.0" - -from itrialspace.apps.retriever.engine import RetrieverEngine -from itrialspace.apps.retriever.search import FacetedSearch, SearchFilters -from itrialspace.apps.retriever.similarity import SimilarityEngine -from itrialspace.apps.retriever.slicer import NIfTISlicer diff --git a/itrialspace/src/itrialspace/apps/retriever/__main__.py b/itrialspace/src/itrialspace/apps/retriever/__main__.py deleted file mode 100644 index 0410bb32ada31cbb45c104dd79e285fba548d8a7..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/__main__.py +++ /dev/null @@ -1,7 +0,0 @@ -""" -__main__.py — allow `python -m itrialspace.apps.retriever` to invoke the CLI. -""" - -from itrialspace.apps.retriever.cli import main - -main() diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 0c9e43eeff0c4a1104049331f435e9338f686cd2..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/__main__.cpython-310.pyc deleted file mode 100644 index 8ec065a2030c729eba1a77604fcb94de496a87bf..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/__main__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/cli.cpython-310.pyc deleted file mode 100644 index a49035154f06390e7b1f9feb0eb5f47741a1ab96..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/cli.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/engine.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/engine.cpython-310.pyc deleted file mode 100644 index c94607ef6eb06868b22df04d3050add3fbd8ac4c..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/engine.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/notebook.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/notebook.cpython-310.pyc deleted file mode 100644 index 9b338e92e8d29b03bf7f29ab2971a77e16ee40e9..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/notebook.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/search.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/search.cpython-310.pyc deleted file mode 100644 index e8db0d84d4ae7a11aca02f98a8b32e2a2760e022..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/search.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/similarity.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/similarity.cpython-310.pyc deleted file mode 100644 index 5523ae4684daae62ce3b7fa55d2f9ee39a9e0f6a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/similarity.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/slicer.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/slicer.cpython-310.pyc deleted file mode 100644 index 0da132ba6c7bbd9dfb6121b4ba5a0004710fe844..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/__pycache__/slicer.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__init__.py b/itrialspace/src/itrialspace/apps/retriever/api/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index d4464181b08ec7dd69fbc062ba9b71a5017f5af5..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/app.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/app.cpython-310.pyc deleted file mode 100644 index 433f5084637ab288acb46097bbdf80256a536d36..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/app.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/models.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/models.cpython-310.pyc deleted file mode 100644 index 87bddf8fcd5853685470754fe02fc1de16fb3e8a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/models.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/app.py b/itrialspace/src/itrialspace/apps/retriever/api/app.py deleted file mode 100644 index e9196b7b7d93885626ebf43b8d4f81e2618c4d0d..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/api/app.py +++ /dev/null @@ -1,369 +0,0 @@ -""" -FastAPI backend for the iTrialSpace Retriever. - -Endpoints: - GET /health — service health + stats - GET /filters — available filter values - POST /search — faceted search - POST /similar — query-by-example similarity - POST /matcher — reinsertion anatomy matching - GET /nodule/{id} — full nodule detail - GET /ct/slice — extract a 2-D CT slice (PNG) - GET /ct/nodule-view — CT slice at nodule centre (PNG) - GET /ct/info — volume metadata - POST /export — export search results (CSV/JSON download) - -Launch: - uvicorn retriever.api.app:create_app --factory --host 0.0.0.0 --port 8421 -""" - -from __future__ import annotations - -import os -import tempfile -from typing import Optional - -import numpy as np -import pandas as pd -from fastapi import FastAPI, HTTPException, Response -from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse - -from itrialspace.apps.retriever.api.models import ( - ExportRequest, - FiltersInfoResponse, - HealthResponse, - MatchedNodule, - MatcherRequest, - MatcherResponse, - NoduleDetailResponse, - NoduleSummary, - SearchRequest, - SearchResponse, - SimilarityRequest, - SimilarityResponse, - SimilarNodule, - VolumeInfoResponse, -) -from itrialspace.apps.retriever.engine import RetrieverEngine -from itrialspace.apps.retriever.search import SearchFilters - -# --------------------------------------------------------------------------- -# App factory -# --------------------------------------------------------------------------- - -_engine: Optional[RetrieverEngine] = None - - -def get_engine() -> RetrieverEngine: - """Lazy singleton engine loader.""" - global _engine - if _engine is None: - print("[Retriever API] Loading NoduleIndex …") - _engine = RetrieverEngine.from_defaults(verbose=True) - print(f"[Retriever API] Ready — {_engine.n_nodules:,} nodules loaded") - return _engine - - -def create_app( - engine: Optional[RetrieverEngine] = None, -) -> FastAPI: - """ - Create and configure the FastAPI application. - - Args: - engine: optional pre-built engine (for testing or Jupyter embedding). - """ - global _engine - if engine is not None: - _engine = engine - - app = FastAPI( - title="iTrialSpace Retriever", - description="Interactive retrieval + visualization for 13k+ lung nodules across 7 datasets.", - version="0.1.0", - ) - - app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], - ) - - # ── Health ──────────────────────────────────────────────────────────────── - - @app.get("/health", response_model=HealthResponse) - def health(): - eng = get_engine() - return HealthResponse( - version="0.1.0", - n_nodules=eng.n_nodules, - datasets=eng.datasets, - ) - - # ── Filters info ────────────────────────────────────────────────────────── - - @app.get("/filters", response_model=FiltersInfoResponse) - def filters_info(): - eng = get_engine() - af = eng.available_filters - return FiltersInfoResponse(**af) - - # ── Faceted search ──────────────────────────────────────────────────────── - - @app.post("/search", response_model=SearchResponse) - def search(req: SearchRequest): - eng = get_engine() - sf = SearchFilters(**req.model_dump()) - result = eng.search(sf) - summaries = _df_to_summaries(result.df) - return SearchResponse( - total_matching=result.total_matching, - returned=len(summaries), - results=summaries, - facet_counts=result.facet_counts, - ) - - # ── Similarity ──────────────────────────────────────────────────────────── - - @app.post("/similar", response_model=SimilarityResponse) - def similar(req: SimilarityRequest): - eng = get_engine() - try: - results = eng.find_similar( - annotation_id=req.annotation_id, - k=req.k, - exclude_same_patient=req.exclude_same_patient, - include_datasets=req.include_datasets, - exclude_datasets=req.exclude_datasets, - label=req.label, - ) - except KeyError as e: - raise HTTPException(404, detail=str(e)) - - items = [] - for r in results: - row = r.row - items.append( - SimilarNodule( - annotation_id=r.annotation_id, - dataset=r.dataset, - distance=round(r.distance, 4), - rank=r.rank, - lobe_name=str(row.get("lobe_name", "")), - nodule_mean_diam_mm=float(row.get("nodule_mean_diam_mm", 0)), - label=int(row["label"]) if pd.notna(row.get("label")) else None, - feature_deltas={k: round(v, 4) for k, v in r.feature_deltas.items()}, - ) - ) - return SimilarityResponse( - reference_id=req.annotation_id, - k=req.k, - results=items, - ) - - # ── Reinsertion matcher ─────────────────────────────────────────────────── - - @app.post("/matcher", response_model=MatcherResponse) - def matcher(req: MatcherRequest): - eng = get_engine() - results = eng.find_reinsertion_match( - lobe=req.lobe, - lobe_cc_pct=req.lobe_cc_pct, - pleural_dist_mm=req.pleural_dist_mm, - diameter_mm=req.diameter_mm, - label=req.label, - lung_zone=req.lung_zone, - lung_side=req.lung_side, - include_datasets=req.include_datasets, - exclude_datasets=req.exclude_datasets, - k=req.k, - ) - items = [ - MatchedNodule( - annotation_id=m.annotation_id, - dataset=m.dataset, - ct_path=m.ct_path, - score=round(m.score, 4), - lobe=m.lobe, - diameter_mm=round(m.diameter_mm, 2), - pleural_mm=round(m.pleural_mm, 2) if m.pleural_mm is not None else None, - lobe_cc_pct=round(m.lobe_cc_pct, 2), - label=m.label, - ) - for m in results - ] - return MatcherResponse( - target_lobe=req.lobe, - k=req.k, - results=items, - ) - - # ── Nodule detail ───────────────────────────────────────────────────────── - - @app.get("/nodule/{annotation_id}", response_model=NoduleDetailResponse) - def nodule_detail(annotation_id: str): - eng = get_engine() - try: - detail = eng.get_nodule_detail(annotation_id) - except KeyError as e: - raise HTTPException(404, detail=str(e)) - - paths = detail.pop("_paths", {}) - paths_exist = { - k.replace("_exists_", ""): v for k, v in detail.items() if k.startswith("_exists_") - } - for k in list(detail.keys()): - if k.startswith("_exists_"): - del detail[k] - - # Convert NaN/NaT to None for JSON serialisation - cleaned = {} - for k, v in detail.items(): - if isinstance(v, float) and np.isnan(v): - cleaned[k] = None - elif pd.isna(v): - cleaned[k] = None - else: - cleaned[k] = v - - return NoduleDetailResponse( - annotation_id=str(cleaned.get("annotation_id", annotation_id)), - dataset=str(cleaned.get("dataset", "")), - patient_id=str(cleaned.get("patient_id", "")), - label=cleaned.get("label"), - detail=cleaned, - paths=paths, - paths_exist=paths_exist, - ) - - # ── CT slice viewer ─────────────────────────────────────────────────────── - - @app.get("/ct/slice") - def ct_slice( - ct_path: str, - axis: str = "axial", - index: Optional[int] = None, - mask_path: Optional[str] = None, - window: str = "lung", - ): - eng = get_engine() - try: - sl = eng.get_slice( - ct_path=ct_path, - axis=axis, - index=index, - mask_path=mask_path, - window=window, - ) - png = sl.to_png_bytes() - except FileNotFoundError as e: - raise HTTPException(404, detail=str(e)) - except Exception as e: - raise HTTPException(500, detail=str(e)) - - return Response(content=png, media_type="image/png") - - @app.get("/ct/nodule-view") - def ct_nodule_view( - annotation_id: str, - axis: str = "axial", - window: str = "lung", - show_mask: bool = True, - ): - eng = get_engine() - try: - sl = eng.get_nodule_view(annotation_id, axis=axis, window=window, show_mask=show_mask) - png = sl.to_png_bytes() - except (KeyError, FileNotFoundError) as e: - raise HTTPException(404, detail=str(e)) - except Exception as e: - raise HTTPException(500, detail=str(e)) - - return Response(content=png, media_type="image/png") - - @app.get("/ct/info", response_model=VolumeInfoResponse) - def ct_info(ct_path: str): - eng = get_engine() - try: - shape = eng.volume_shape(ct_path) - spacing = eng._slicer.voxel_spacing(ct_path) - except FileNotFoundError as e: - raise HTTPException(404, detail=str(e)) - return VolumeInfoResponse( - shape=list(shape), - spacing_mm=[round(s, 3) for s in spacing], - ) - - # ── Export ──────────────────────────────────────────────────────────────── - - @app.post("/export") - def export(req: ExportRequest): - eng = get_engine() - sf = SearchFilters(**req.filters.model_dump()) - - ext = "csv" if req.format == "csv" else "json" - fname = req.filename or f"itrialspace_export.{ext}" - - tmp = tempfile.NamedTemporaryFile(suffix=f".{ext}", delete=False, prefix="retriever_") - tmp.close() - - try: - if req.format == "csv": - eng.export_search_csv(sf, tmp.name, include_paths=req.include_paths) - else: - eng.export_search_json(sf, tmp.name, include_paths=req.include_paths) - except Exception as e: - os.unlink(tmp.name) - raise HTTPException(500, detail=str(e)) - - media = "text/csv" if ext == "csv" else "application/json" - return FileResponse( - tmp.name, - media_type=media, - filename=fname, - background=None, - ) - - return app - - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - - -def _df_to_summaries(df: pd.DataFrame) -> list[NoduleSummary]: - """Convert a results DataFrame to NoduleSummary list.""" - summaries = [] - for _, row in df.iterrows(): - summaries.append( - NoduleSummary( - annotation_id=str(row.get("annotation_id", "")), - dataset=str(row.get("dataset", "")), - patient_id=str(row.get("patient_id", "")), - ct_path=str(row.get("ct_path", "")), - label=int(row["label"]) if pd.notna(row.get("label")) else None, - lobe_name=str(row.get("lobe_name", "")), - lung_side=str(row.get("lung_side", "")), - lung_zone=str(row.get("lung_zone", "")), - central_peripheral=str(row.get("central_peripheral", "")), - nodule_mean_diam_mm=float(row.get("nodule_mean_diam_mm", 0)), - pleural_distance_mm=( - float(row["pleural_distance_mm"]) - if pd.notna(row.get("pleural_distance_mm")) - else None - ), - reinsertion_lobe=str(row.get("reinsertion_lobe", "")), - reinsertion_nodule_diam_mm=float(row.get("reinsertion_nodule_diam_mm", 0)), - reinsertion_pleural_dist_mm=( - float(row["reinsertion_pleural_dist_mm"]) - if pd.notna(row.get("reinsertion_pleural_dist_mm")) - else None - ), - reinsertion_lobe_cc_pct=float(row.get("reinsertion_lobe_cc_pct", 0)), - ) - ) - return summaries diff --git a/itrialspace/src/itrialspace/apps/retriever/api/models.py b/itrialspace/src/itrialspace/apps/retriever/api/models.py deleted file mode 100644 index c890fb1cafb68a9c9f34716368151572c5f7dafe..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/api/models.py +++ /dev/null @@ -1,243 +0,0 @@ -""" -Pydantic request / response models for the FastAPI backend. -""" - -from __future__ import annotations - -from typing import Optional - -from pydantic import BaseModel, Field - -# --------------------------------------------------------------------------- -# Search -# --------------------------------------------------------------------------- - - -class SearchRequest(BaseModel): - """POST /search request body.""" - - datasets: Optional[list[str]] = None - exclude_datasets: Optional[list[str]] = None - label: Optional[int] = Field(None, ge=0, le=1) - lobe: Optional[list[str]] = None - lung_zone: Optional[list[str]] = None - lung_side: Optional[str] = None - central_peripheral: Optional[str] = None - diameter_min: Optional[float] = None - diameter_max: Optional[float] = None - pleural_distance_min: Optional[float] = None - pleural_distance_max: Optional[float] = None - airway_distance_min: Optional[float] = None - airway_distance_max: Optional[float] = None - reinsertion_lobe: Optional[list[str]] = None - reinsertion_zone: Optional[list[str]] = None - reinsertion_side: Optional[str] = None - reinsertion_diameter_min: Optional[float] = None - reinsertion_diameter_max: Optional[float] = None - reinsertion_pleural_min: Optional[float] = None - reinsertion_pleural_max: Optional[float] = None - reinsertion_cc_pct_min: Optional[float] = None - reinsertion_cc_pct_max: Optional[float] = None - n_nodules_min: Optional[int] = None - n_nodules_max: Optional[int] = None - population_type: Optional[str] = None - label_source: Optional[str] = None - limit: Optional[int] = Field(50, ge=1, le=5000) - offset: int = Field(0, ge=0) - sample_n: Optional[int] = None - sample_seed: Optional[int] = None - sort_by: Optional[str] = None - sort_ascending: bool = True - - -class NoduleSummary(BaseModel): - """Compact nodule representation for search results.""" - - annotation_id: str - dataset: str - patient_id: str - ct_path: str - label: Optional[int] = None - lobe_name: str = "" - lung_side: str = "" - lung_zone: str = "" - central_peripheral: str = "" - nodule_mean_diam_mm: float = 0.0 - pleural_distance_mm: Optional[float] = None - reinsertion_lobe: str = "" - reinsertion_nodule_diam_mm: float = 0.0 - reinsertion_pleural_dist_mm: Optional[float] = None - reinsertion_lobe_cc_pct: float = 0.0 - - -class SearchResponse(BaseModel): - """POST /search response.""" - - total_matching: int - returned: int - results: list[NoduleSummary] - facet_counts: Optional[dict] = None - - -# --------------------------------------------------------------------------- -# Similarity -# --------------------------------------------------------------------------- - - -class SimilarityRequest(BaseModel): - """POST /similar request body.""" - - annotation_id: str - k: int = Field(10, ge=1, le=500) - exclude_same_patient: bool = True - include_datasets: Optional[list[str]] = None - exclude_datasets: Optional[list[str]] = None - label: Optional[int] = None - - -class SimilarNodule(BaseModel): - """Single similar nodule result.""" - - annotation_id: str - dataset: str - distance: float - rank: int - lobe_name: str = "" - nodule_mean_diam_mm: float = 0.0 - label: Optional[int] = None - feature_deltas: dict = {} - - -class SimilarityResponse(BaseModel): - """POST /similar response.""" - - reference_id: str - k: int - results: list[SimilarNodule] - - -# --------------------------------------------------------------------------- -# Reinsertion matcher -# --------------------------------------------------------------------------- - - -class MatcherRequest(BaseModel): - """POST /matcher request body.""" - - lobe: str - lobe_cc_pct: Optional[float] = None - pleural_dist_mm: Optional[float] = None - diameter_mm: Optional[float] = None - label: Optional[int] = None - lung_zone: Optional[str] = None - lung_side: Optional[str] = None - include_datasets: Optional[list[str]] = None - exclude_datasets: Optional[list[str]] = None - k: int = Field(10, ge=1, le=500) - - -class MatchedNodule(BaseModel): - """A single match result.""" - - annotation_id: str - dataset: str - ct_path: str - score: float - lobe: str - diameter_mm: float - pleural_mm: Optional[float] = None - lobe_cc_pct: float = 0.0 - label: Optional[int] = None - - -class MatcherResponse(BaseModel): - """POST /matcher response.""" - - target_lobe: str - k: int - results: list[MatchedNodule] - - -# --------------------------------------------------------------------------- -# CT slice viewer -# --------------------------------------------------------------------------- - - -class SliceRequest(BaseModel): - """GET /ct/slice query params.""" - - ct_path: str - axis: str = "axial" - index: Optional[int] = None - mask_path: Optional[str] = None - window: str = "lung" - - -class NoduleViewRequest(BaseModel): - """GET /ct/nodule-view query params.""" - - annotation_id: str - axis: str = "axial" - window: str = "lung" - - -class VolumeInfoResponse(BaseModel): - """GET /ct/info response.""" - - shape: list[int] - spacing_mm: list[float] - - -# --------------------------------------------------------------------------- -# Export -# --------------------------------------------------------------------------- - - -class ExportRequest(BaseModel): - """POST /export request body.""" - - filters: SearchRequest - format: str = "csv" # "csv" or "json" - include_paths: bool = True - filename: Optional[str] = None - - -# --------------------------------------------------------------------------- -# Nodule detail -# --------------------------------------------------------------------------- - - -class NoduleDetailResponse(BaseModel): - """GET /nodule/{annotation_id} response.""" - - annotation_id: str - dataset: str - patient_id: str - label: Optional[int] = None - detail: dict - paths: dict = {} - paths_exist: dict = {} - - -# --------------------------------------------------------------------------- -# General -# --------------------------------------------------------------------------- - - -class HealthResponse(BaseModel): - version: str - n_nodules: int - datasets: list[str] - - -class FiltersInfoResponse(BaseModel): - """GET /filters response — available facet values.""" - - datasets: list[str] - lobes: list[str] - zones: list[str] - sides: list[str] - labels: list - central_peripheral: list[str] - population_types: list[str] - label_sources: list[str] diff --git a/itrialspace/src/itrialspace/apps/retriever/cli.py b/itrialspace/src/itrialspace/apps/retriever/cli.py deleted file mode 100644 index 28562c84f30a839e358fa398726dad5611b3acab..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/cli.py +++ /dev/null @@ -1,337 +0,0 @@ -#!/usr/bin/env python3 -""" -iTrialSpace Retriever CLI — command-line interface. - -Usage: - python -m itrialspace.apps.retriever.cli search --label 1 --lobe right_lung_upper_lobe --limit 20 - python -m itrialspace.apps.retriever.cli similar --id DLCS24_n0001 --k 10 - python -m itrialspace.apps.retriever.cli match --lobe left_lung_lower_lobe --diameter 12 --k 5 - python -m itrialspace.apps.retriever.cli export --label 1 --format csv -o results.csv - python -m itrialspace.apps.retriever.cli info - python -m itrialspace.apps.retriever.cli serve --port 8421 -""" -from __future__ import annotations - -import argparse -import json -import sys - -import pandas as pd - -# --------------------------------------------------------------------------- -# Lazy engine loader -# --------------------------------------------------------------------------- - -_engine = None - - -def _get_engine(): - global _engine - if _engine is None: - from itrialspace.apps.retriever.engine import RetrieverEngine - - print("Loading NoduleIndex …", file=sys.stderr) - _engine = RetrieverEngine.from_defaults(verbose=True) - print(f"Ready — {_engine.n_nodules:,} nodules.\n", file=sys.stderr) - return _engine - - -# --------------------------------------------------------------------------- -# Commands -# --------------------------------------------------------------------------- - - -def cmd_search(args): - engine = _get_engine() - from itrialspace.apps.retriever.search import SearchFilters - - kwargs = {} - if args.datasets: - kwargs["datasets"] = args.datasets - if args.label is not None: - kwargs["label"] = args.label - if args.lobe: - kwargs["lobe"] = args.lobe - if args.zone: - kwargs["lung_zone"] = args.zone - if args.side: - kwargs["lung_side"] = args.side - if args.diam_min is not None: - kwargs["diameter_min"] = args.diam_min - if args.diam_max is not None: - kwargs["diameter_max"] = args.diam_max - if args.pleural_min is not None: - kwargs["pleural_distance_min"] = args.pleural_min - if args.pleural_max is not None: - kwargs["pleural_distance_max"] = args.pleural_max - if args.population: - kwargs["population_type"] = args.population - if args.label_source: - kwargs["label_source"] = args.label_source - kwargs["limit"] = args.limit - if args.sort: - kwargs["sort_by"] = args.sort - kwargs["sort_ascending"] = not args.desc - - sf = SearchFilters(**kwargs) - result = engine.search(sf) - - print(f"Total matching: {result.total_matching:,}") - print(f"Showing: {len(result.df)}\n") - - display_cols = [ - "annotation_id", - "dataset", - "label", - "lobe_name", - "nodule_mean_diam_mm", - "pleural_distance_mm", - ] - cols = [c for c in display_cols if c in result.df.columns] - print(result.df[cols].to_string(index=False)) - - -def cmd_similar(args): - engine = _get_engine() - - kwargs = {} - if args.label is not None: - kwargs["label"] = args.label - if args.datasets: - kwargs["include_datasets"] = args.datasets - - results = engine.find_similar( - annotation_id=args.id, - k=args.k, - exclude_same_patient=not args.allow_same_patient, - **kwargs, - ) - - if not results: - print("No similar nodules found.") - return - - print(f"Top-{args.k} similar to {args.id}:\n") - rows = [] - for r in results: - rows.append( - { - "rank": r.rank, - "annotation_id": r.annotation_id, - "dataset": r.dataset, - "distance": f"{r.distance:.4f}", - } - ) - print(pd.DataFrame(rows).to_string(index=False)) - - -def cmd_match(args): - engine = _get_engine() - - kwargs = {} - if args.cc_pct is not None: - kwargs["lobe_cc_pct"] = args.cc_pct - if args.pleural is not None: - kwargs["pleural_dist_mm"] = args.pleural - if args.diameter is not None: - kwargs["diameter_mm"] = args.diameter - if args.label is not None: - kwargs["label"] = args.label - if args.datasets: - kwargs["include_datasets"] = args.datasets - - results = engine.find_reinsertion_match(lobe=args.lobe, k=args.k, **kwargs) - - if not results: - print("No matches found.") - return - - print(f"Top-{args.k} reinsertion matches for {args.lobe}:\n") - rows = [] - for m in results: - label_str = {0: "benign", 1: "malignant", None: "?"}[m.label] - rows.append( - { - "annotation_id": m.annotation_id, - "dataset": m.dataset, - "score": f"{m.score:.4f}", - "diameter_mm": f"{m.diameter_mm:.1f}", - "lobe_cc_pct": f"{m.lobe_cc_pct:.1f}", - "label": label_str, - } - ) - print(pd.DataFrame(rows).to_string(index=False)) - - -def cmd_export(args): - engine = _get_engine() - from itrialspace.apps.retriever.search import SearchFilters - - kwargs = {} - if args.datasets: - kwargs["datasets"] = args.datasets - if args.label is not None: - kwargs["label"] = args.label - if args.lobe: - kwargs["lobe"] = args.lobe - if args.diam_min is not None: - kwargs["diameter_min"] = args.diam_min - if args.diam_max is not None: - kwargs["diameter_max"] = args.diam_max - - sf = SearchFilters(**kwargs) - - if args.format == "csv": - path = engine.export_search_csv(sf, args.output, include_paths=args.include_paths) - else: - path = engine.export_search_json(sf, args.output, include_paths=args.include_paths) - - print(f"Exported to {path}") - - -def cmd_info(args): - engine = _get_engine() - summary = engine.summary() - print("iTrialSpace Retriever v0.1.0") - print(f"Nodules: {summary['n_nodules']:,}") - print(f"Datasets: {', '.join(summary['datasets'])}") - print() - stats_df = pd.DataFrame(summary["stats"]).T - print(stats_df.to_string()) - - -def cmd_detail(args): - engine = _get_engine() - detail = engine.get_nodule_detail(args.id) - - if args.json: - # Serialise NaN-safe - cleaned = {} - for k, v in detail.items(): - if isinstance(v, float) and pd.isna(v): - cleaned[k] = None - elif isinstance(v, pd.Series): - cleaned[k] = v.to_dict() - else: - cleaned[k] = v - print(json.dumps(cleaned, indent=2, default=str)) - else: - for k, v in detail.items(): - if not str(k).startswith("_"): - print(f" {k:40s} {v}") - - -def cmd_serve(args): - """Launch the FastAPI server.""" - try: - import uvicorn - except ImportError: - print("uvicorn is required: pip install uvicorn", file=sys.stderr) - sys.exit(1) - - print(f"Starting retriever API on {args.host}:{args.port}") - uvicorn.run( - "itrialspace.apps.retriever.api.app:create_app", - factory=True, - host=args.host, - port=args.port, - reload=args.reload, - ) - - -# --------------------------------------------------------------------------- -# Argument parser -# --------------------------------------------------------------------------- - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog="retriever", - description="iTrialSpace Retriever CLI — search, similarity, matching, export.", - ) - sub = parser.add_subparsers(dest="command", required=True) - - # -- search --- - p_search = sub.add_parser("search", help="Faceted search") - p_search.add_argument("--datasets", nargs="+", default=None) - p_search.add_argument("--label", type=int, choices=[0, 1], default=None) - p_search.add_argument("--lobe", nargs="+", default=None) - p_search.add_argument("--zone", nargs="+", default=None) - p_search.add_argument("--side", default=None) - p_search.add_argument("--diam-min", type=float, default=None) - p_search.add_argument("--diam-max", type=float, default=None) - p_search.add_argument("--pleural-min", type=float, default=None) - p_search.add_argument("--pleural-max", type=float, default=None) - p_search.add_argument("--population", choices=["screening", "diagnostic"], default=None) - p_search.add_argument("--label-source", choices=["histopathology", "radiology"], default=None) - p_search.add_argument("--limit", type=int, default=50) - p_search.add_argument("--sort", default=None) - p_search.add_argument("--desc", action="store_true") - p_search.set_defaults(func=cmd_search) - - # -- similar --- - p_sim = sub.add_parser("similar", help="Find similar nodules") - p_sim.add_argument("--id", required=True, help="Reference annotation_id") - p_sim.add_argument("--k", type=int, default=10) - p_sim.add_argument("--label", type=int, choices=[0, 1], default=None) - p_sim.add_argument("--datasets", nargs="+", default=None) - p_sim.add_argument("--allow-same-patient", action="store_true") - p_sim.set_defaults(func=cmd_similar) - - # -- match --- - p_match = sub.add_parser("match", help="Reinsertion anatomy matching") - p_match.add_argument("--lobe", required=True) - p_match.add_argument("--k", type=int, default=10) - p_match.add_argument("--cc-pct", type=float, default=None) - p_match.add_argument("--pleural", type=float, default=None) - p_match.add_argument("--diameter", type=float, default=None) - p_match.add_argument("--label", type=int, choices=[0, 1], default=None) - p_match.add_argument("--datasets", nargs="+", default=None) - p_match.set_defaults(func=cmd_match) - - # -- export --- - p_export = sub.add_parser("export", help="Export search results") - p_export.add_argument("-o", "--output", required=True) - p_export.add_argument("--format", choices=["csv", "json"], default="csv") - p_export.add_argument("--datasets", nargs="+", default=None) - p_export.add_argument("--label", type=int, choices=[0, 1], default=None) - p_export.add_argument("--lobe", nargs="+", default=None) - p_export.add_argument("--diam-min", type=float, default=None) - p_export.add_argument("--diam-max", type=float, default=None) - p_export.add_argument("--include-paths", action="store_true", default=True) - p_export.add_argument("--no-paths", dest="include_paths", action="store_false") - p_export.set_defaults(func=cmd_export) - - # -- info --- - p_info = sub.add_parser("info", help="Index summary statistics") - p_info.set_defaults(func=cmd_info) - - # -- detail --- - p_detail = sub.add_parser("detail", help="Full detail for a nodule") - p_detail.add_argument("--id", required=True, help="annotation_id") - p_detail.add_argument("--json", action="store_true", help="Output as JSON") - p_detail.set_defaults(func=cmd_detail) - - # -- serve --- - p_serve = sub.add_parser("serve", help="Start FastAPI server") - p_serve.add_argument("--host", default="0.0.0.0") - p_serve.add_argument("--port", type=int, default=8421) - p_serve.add_argument("--reload", action="store_true") - p_serve.set_defaults(func=cmd_serve) - - return parser - - -# --------------------------------------------------------------------------- -# Main -# --------------------------------------------------------------------------- - - -def main(): - parser = build_parser() - args = parser.parse_args() - args.func(args) - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/apps/retriever/engine.py b/itrialspace/src/itrialspace/apps/retriever/engine.py deleted file mode 100644 index a65713fca8aef0021297a8f5b11de8509cadc677..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/engine.py +++ /dev/null @@ -1,351 +0,0 @@ -""" -RetrieverEngine — top-level façade for the iTrialSpace Retriever. - -Composes FacetedSearch, SimilarityEngine, ReinsertionMatcher, PathResolver, -and NIfTISlicer into a single object for all three deployment modes. -""" - -from __future__ import annotations - -import os -from pathlib import Path -from typing import Optional - -import pandas as pd - -from itrialspace import ( - MatchResult, - NoduleIndex, - ReinsertionMatcher, - ReinsertionTarget, -) -from itrialspace.apps.retriever.search import FacetedSearch, SearchFilters, SearchResult -from itrialspace.apps.retriever.similarity import SimilarityEngine, SimilarityResult -from itrialspace.apps.retriever.slicer import NIfTISlicer, SliceAxis, SliceResult -from itrialspace.io.registry import DatasetRegistry -from itrialspace.site.path_resolver import PathResolver - -# Default paths -_ITRIALSPACE_PKG = Path(__file__).resolve().parent.parent / "itrialspace" -_DEFAULT_DATASETS_YAML = _ITRIALSPACE_PKG / "config" / "datasets.yaml" -_DEFAULT_PATHS_YAML = _ITRIALSPACE_PKG / "site" / "config" / "paths.yaml" - - -class RetrieverEngine: - """ - Unified façade: search + similarity + matching + NIfTI viewing + export. - - Usage: - engine = RetrieverEngine.from_defaults() - results = engine.search(SearchFilters(label=1, diameter_min=5)) - similar = engine.find_similar("DLCS24_n0001", k=10) - match = engine.find_reinsertion_match(lobe="right_lung_upper_lobe", ...) - sl = engine.get_slice("DLCS24", "DLCS_0001", axis="axial", index=128) - """ - - def __init__( - self, - index: NoduleIndex, - path_resolver: PathResolver, - similarity_weights: Optional[dict] = None, - matcher_weights: Optional[dict] = None, - per_dataset_norm: bool = False, - ): - self._index = index - self._resolver = path_resolver - self._search = FacetedSearch(index) - self._similarity = SimilarityEngine( - index, weights=similarity_weights, per_dataset_norm=per_dataset_norm - ) - self._matcher = ReinsertionMatcher(index, weights=matcher_weights) - self._slicer = NIfTISlicer() - - # ── Factory ─────────────────────────────────────────────────────────────── - - @classmethod - def from_defaults( - cls, - datasets_yaml: Optional[str] = None, - paths_yaml: Optional[str] = None, - base_dir: Optional[str] = None, - verbose: bool = True, - ) -> "RetrieverEngine": - """Load the full NoduleIndex from the default registry.""" - ds_yaml = datasets_yaml or str(_DEFAULT_DATASETS_YAML) - p_yaml = paths_yaml or str(_DEFAULT_PATHS_YAML) - - if verbose: - print(f"Loading registry from {ds_yaml}") - registry = DatasetRegistry.from_yaml(ds_yaml) - index = NoduleIndex.from_registry(registry, verbose=verbose) - resolver = PathResolver(config_path=p_yaml, base_dir=base_dir) - - return cls(index=index, path_resolver=resolver) - - @classmethod - def from_index( - cls, - index: NoduleIndex, - paths_yaml: Optional[str] = None, - base_dir: Optional[str] = None, - ) -> "RetrieverEngine": - """Build from a pre-loaded NoduleIndex.""" - p_yaml = paths_yaml or str(_DEFAULT_PATHS_YAML) - resolver = PathResolver(config_path=p_yaml, base_dir=base_dir) - return cls(index=index, path_resolver=resolver) - - # ── Properties ──────────────────────────────────────────────────────────── - - @property - def index(self) -> NoduleIndex: - return self._index - - @property - def resolver(self) -> PathResolver: - return self._resolver - - @property - def n_nodules(self) -> int: - return len(self._index) - - @property - def datasets(self) -> list[str]: - return self._index.datasets - - # ── A. Faceted search ───────────────────────────────────────────────────── - - def search(self, filters: Optional[SearchFilters] = None, **kwargs) -> SearchResult: - """Run a faceted search. - - Accepts either a SearchFilters object or keyword args matching - SearchFilters fields. Returns SearchResult with matching DataFrame. - """ - if filters is None: - filters = SearchFilters(**kwargs) - return self._search.search(filters) - - @property - def available_filters(self) -> dict: - return self._search.available_filters - - @property - def facet_counts(self) -> dict: - """Return facet counts for the full (unfiltered) index.""" - return self._search._compute_facets(SearchFilters()) - - # ── B. Query-by-example similarity ──────────────────────────────────────── - - def find_similar( - self, - annotation_id: str, - k: int = 10, - exclude_same_patient: bool = True, - include_datasets: Optional[list[str]] = None, - exclude_datasets: Optional[list[str]] = None, - label: Optional[int] = None, - ) -> list[SimilarityResult]: - """Find the k most similar nodules to a reference.""" - return self._similarity.find_similar( - annotation_id=annotation_id, - k=k, - exclude_same_patient=exclude_same_patient, - include_datasets=include_datasets, - exclude_datasets=exclude_datasets, - label=label, - ) - - def get_feature_vector(self, annotation_id: str) -> dict[str, float]: - """Return the normalised feature vector for a nodule.""" - return self._similarity.get_feature_vector(annotation_id) - - # ── C. Anatomy-aware reinsertion matching ───────────────────────────────── - - def find_reinsertion_match( - self, - lobe: str, - lobe_cc_pct: Optional[float] = None, - pleural_dist_mm: Optional[float] = None, - diameter_mm: Optional[float] = None, - label: Optional[int] = None, - lung_zone: Optional[str] = None, - lung_side: Optional[str] = None, - include_datasets: Optional[list[str]] = None, - exclude_datasets: Optional[list[str]] = None, - k: int = 10, - ) -> list[MatchResult]: - """Find the best reinsertion-matched donor nodules.""" - target = ReinsertionTarget( - lobe=lobe, - lobe_cc_pct=lobe_cc_pct, - pleural_dist_mm=pleural_dist_mm, - diameter_mm=diameter_mm, - label=label, - lung_zone=lung_zone, - lung_side=lung_side, - include_datasets=include_datasets or [], - exclude_datasets=exclude_datasets or [], - ) - return self._matcher.find_top_k(target, k=k) - - # ── D. CT viewer / NIfTI slicing ────────────────────────────────────────── - - def resolve_paths(self, annotation_id: str) -> dict[str, str]: - """Resolve all file paths for a nodule.""" - mask = self._index.df["annotation_id"] == annotation_id - if not mask.any(): - raise KeyError(f"annotation_id '{annotation_id}' not found") - row = self._index.df.loc[mask.idxmax()] - return self._resolver.resolve_all_paths(row) - - def get_slice( - self, - ct_path: str, - axis: str = "axial", - index: Optional[int] = None, - mask_path: Optional[str] = None, - window: str = "lung", - ) -> SliceResult: - """Extract a 2-D slice from a CT or mask volume.""" - return self._slicer.get_slice( - ct_path=ct_path, - axis=SliceAxis(axis), - index=index, - mask_path=mask_path, - window=window, - ) - - def get_nodule_view( - self, - annotation_id: str, - axis: str = "axial", - window: str = "lung", - show_mask: bool = True, - ) -> SliceResult: - """Convenience: resolve paths and get the slice at the nodule centre.""" - mask = self._index.df["annotation_id"] == annotation_id - if not mask.any(): - raise KeyError(f"annotation_id '{annotation_id}' not found") - row = self._index.df.loc[mask.idxmax()] - paths = self._resolver.resolve_all_paths(row) - - ct_path = paths["ct_path"] - mask_path = paths.get("nodule_mask_path") if show_mask else None - coord_x = float(row.get("coordX", 0)) - coord_y = float(row.get("coordY", 0)) - coord_z = float(row.get("coordZ", 0)) - - return self._slicer.get_nodule_slice( - ct_path=ct_path, - mask_path=mask_path or "", - coord_x=coord_x, - coord_y=coord_y, - coord_z=coord_z, - axis=SliceAxis(axis), - window=window, - ) - - def volume_shape(self, ct_path: str) -> tuple[int, int, int]: - """Return the 3-D shape of a NIfTI volume.""" - return self._slicer.volume_shape(ct_path) - - # ── E. Export to CohortManifest format ──────────────────────────────────── - - def export_search_csv( - self, - filters: SearchFilters, - output_path: str, - include_paths: bool = True, - ) -> str: - """Run search and export results to CSV. - - If include_paths=True, resolved absolute paths are added. - Returns the output path. - """ - result = self.search(filters) - df = result.df.copy() - - if include_paths: - path_rows = [] - for _, row in df.iterrows(): - try: - p = self._resolver.resolve_all_paths(row) - path_rows.append(p) - except Exception: - path_rows.append({}) - paths_df = pd.DataFrame(path_rows) - df = pd.concat([df, paths_df], axis=1) - - os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) - df.to_csv(output_path, index=False) - return output_path - - def export_search_json( - self, - filters: SearchFilters, - output_path: str, - include_paths: bool = True, - ) -> str: - """Run search and export results to JSON.""" - import json - - result = self.search(filters) - df = result.df.copy() - - if include_paths: - path_rows = [] - for _, row in df.iterrows(): - try: - p = self._resolver.resolve_all_paths(row) - path_rows.append(p) - except Exception: - path_rows.append({}) - paths_df = pd.DataFrame(path_rows) - df = pd.concat([df, paths_df], axis=1) - - records = df.to_dict(orient="records") - os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) - with open(output_path, "w") as f: - json.dump( - { - "n_results": len(records), - "filters": filters.to_dict(), - "results": records, - }, - f, - indent=2, - default=str, - ) - return output_path - - # ── Nodule detail ───────────────────────────────────────────────────────── - - def get_nodule_detail(self, annotation_id: str) -> dict: - """Return full detail dict for a nodule (for UI detail panel).""" - mask = self._index.df["annotation_id"] == annotation_id - if not mask.any(): - raise KeyError(f"annotation_id '{annotation_id}' not found") - - row = self._index.df.loc[mask.idxmax()] - detail = row.to_dict() - - # Add resolved paths - try: - detail["_paths"] = self._resolver.resolve_all_paths(row) - except Exception: - detail["_paths"] = {} - - # Add path existence flags - for key, path in detail.get("_paths", {}).items(): - detail[f"_exists_{key}"] = os.path.isfile(str(path)) if path else False - - return detail - - # ── Summary stats ───────────────────────────────────────────────────────── - - def summary(self) -> dict: - """Return summary statistics about the index.""" - return { - "n_nodules": len(self._index), - "datasets": self._index.datasets, - "stats": self._index.stats().to_dict(orient="index"), - } diff --git a/itrialspace/src/itrialspace/apps/retriever/notebook.py b/itrialspace/src/itrialspace/apps/retriever/notebook.py deleted file mode 100644 index 167e8a79d999df42e584812d8f66d222643b0ca9..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/notebook.py +++ /dev/null @@ -1,344 +0,0 @@ -""" -Jupyter notebook client for the iTrialSpace Retriever. - -Two modes: - 1. **Direct mode** (default): Loads the engine in-process. - 2. **API mode**: Connects to a running FastAPI backend. - -Usage (direct): - from itrialspace.apps.retriever.notebook import RetrieverClient - client = RetrieverClient() - client.search(label=1, lobe=["right_lung_upper_lobe"]) - client.find_similar("DLCS24_n0001", k=10) - client.show_nodule("DLCS24_n0001") - -Usage (API mode): - client = RetrieverClient(api_url="http://localhost:8421") -""" - -from __future__ import annotations - -from typing import Optional - -import numpy as np -import pandas as pd - -try: - import matplotlib.pyplot as plt - - HAS_MPL = True -except ImportError: - HAS_MPL = False - -try: - from IPython.display import HTML, display - from IPython.display import Image as IPImage - - HAS_IPYTHON = True -except ImportError: - HAS_IPYTHON = False - - -class RetrieverClient: - """ - Interactive Jupyter client for the iTrialSpace Retriever. - """ - - def __init__( - self, - api_url: Optional[str] = None, - datasets_yaml: Optional[str] = None, - paths_yaml: Optional[str] = None, - verbose: bool = True, - ): - self._api_url = api_url - self._engine = None - - if api_url is None: - # Direct mode — load engine - from itrialspace.apps.retriever.engine import RetrieverEngine - - self._engine = RetrieverEngine.from_defaults( - datasets_yaml=datasets_yaml, - paths_yaml=paths_yaml, - verbose=verbose, - ) - if verbose: - print(f"RetrieverClient ready — {self._engine.n_nodules:,} nodules") - - # ── Properties ──────────────────────────────────────────────────────────── - - @property - def n_nodules(self) -> int: - if self._engine: - return self._engine.n_nodules - return self._api_get("/health")["n_nodules"] - - @property - def datasets(self) -> list[str]: - if self._engine: - return self._engine.datasets - return self._api_get("/health")["datasets"] - - # ── A. Search ───────────────────────────────────────────────────────────── - - def search(self, display_results: bool = True, **kwargs) -> pd.DataFrame: - """Run a faceted search. - - All kwargs map to SearchFilters fields: - datasets, label, lobe, lung_zone, lung_side, diameter_min, diameter_max, - pleural_distance_min, pleural_distance_max, population_type, label_source, - limit, sort_by, ... - - Returns: - DataFrame of results. - """ - if self._engine: - from itrialspace.apps.retriever.search import SearchFilters - - sf = SearchFilters(**kwargs) - result = self._engine.search(sf) - df = result.df - total = result.total_matching - else: - resp = self._api_post("/search", kwargs) - df = pd.DataFrame(resp["results"]) - total = resp["total_matching"] - - if display_results and HAS_IPYTHON: - display(HTML(f"{total:,} matching, showing {len(df)}")) - display(self._format_results(df)) - return df - - # ── B. Similarity ───────────────────────────────────────────────────────── - - def find_similar( - self, - annotation_id: str, - k: int = 10, - display_results: bool = True, - **kwargs, - ) -> pd.DataFrame: - """Find the k most similar nodules to a reference. - - Extra kwargs: exclude_same_patient, include_datasets, exclude_datasets, label. - """ - if self._engine: - results = self._engine.find_similar(annotation_id=annotation_id, k=k, **kwargs) - rows = [ - { - "rank": r.rank, - "annotation_id": r.annotation_id, - "dataset": r.dataset, - "distance": round(r.distance, 4), - } - for r in results - ] - df = pd.DataFrame(rows) - else: - body = {"annotation_id": annotation_id, "k": k, **kwargs} - resp = self._api_post("/similar", body) - df = pd.DataFrame(resp["results"]) - - if display_results and HAS_IPYTHON: - display(HTML(f"Top-{k} similar to {annotation_id}")) - display(df) - return df - - # ── C. Reinsertion matching ─────────────────────────────────────────────── - - def find_match( - self, - lobe: str, - k: int = 10, - display_results: bool = True, - **kwargs, - ) -> pd.DataFrame: - """Find best reinsertion-matched donor nodules. - - Extra kwargs: lobe_cc_pct, pleural_dist_mm, diameter_mm, label, lung_zone, ... - """ - if self._engine: - results = self._engine.find_reinsertion_match(lobe=lobe, k=k, **kwargs) - rows = [ - { - "annotation_id": m.annotation_id, - "dataset": m.dataset, - "score": round(m.score, 4), - "lobe": m.lobe, - "diameter_mm": round(m.diameter_mm, 2), - "label": m.label, - } - for m in results - ] - df = pd.DataFrame(rows) - else: - body = {"lobe": lobe, "k": k, **kwargs} - resp = self._api_post("/matcher", body) - df = pd.DataFrame(resp["results"]) - - if display_results and HAS_IPYTHON: - display(HTML(f"Top-{k} matches for {lobe}")) - display(df) - return df - - # ── D. CT viewer ────────────────────────────────────────────────────────── - - def show_nodule( - self, - annotation_id: str, - axis: str = "axial", - window: str = "lung", - figsize: tuple = (8, 8), - ): - """Display the CT slice at the nodule centre with mask overlay. - - Works in both direct mode (nibabel) and API mode (PNG download). - """ - if self._engine: - try: - sl = self._engine.get_nodule_view(annotation_id, axis=axis, window=window) - self._plot_slice(sl, title=f"{annotation_id} ({axis}, {window})", figsize=figsize) - except FileNotFoundError as e: - print(f"File not found: {e}") - except Exception as e: - print(f"Error: {e}") - else: - resp = self._api_get_bytes( - f"/ct/nodule-view?annotation_id={annotation_id}&axis={axis}&window={window}" - ) - if resp and HAS_IPYTHON: - display(IPImage(data=resp)) - - def show_slice( - self, - ct_path: str, - axis: str = "axial", - index: Optional[int] = None, - mask_path: Optional[str] = None, - window: str = "lung", - figsize: tuple = (8, 8), - ): - """Display an arbitrary CT slice.""" - if self._engine: - sl = self._engine.get_slice( - ct_path=ct_path, - axis=axis, - index=index, - mask_path=mask_path, - window=window, - ) - self._plot_slice(sl, title=f"{ct_path} (z={sl.slice_index})", figsize=figsize) - else: - params = f"ct_path={ct_path}&axis={axis}&window={window}" - if index is not None: - params += f"&index={index}" - if mask_path: - params += f"&mask_path={mask_path}" - resp = self._api_get_bytes(f"/ct/slice?{params}") - if resp and HAS_IPYTHON: - display(IPImage(data=resp)) - - # ── E. Export ───────────────────────────────────────────────────────────── - - def export_csv(self, output_path: str, include_paths: bool = True, **kwargs) -> str: - """Export search results to CSV.""" - if self._engine: - from itrialspace.apps.retriever.search import SearchFilters - - sf = SearchFilters(**kwargs) - return self._engine.export_search_csv(sf, output_path, include_paths=include_paths) - else: - # Download from API - body = {"filters": kwargs, "format": "csv", "include_paths": include_paths} - import requests - - resp = requests.post(f"{self._api_url}/export", json=body, timeout=60) - resp.raise_for_status() - with open(output_path, "wb") as f: - f.write(resp.content) - return output_path - - # ── F. Nodule detail ────────────────────────────────────────────────────── - - def detail(self, annotation_id: str, display_detail: bool = True) -> dict: - """Get full detail for a nodule.""" - if self._engine: - d = self._engine.get_nodule_detail(annotation_id) - else: - d = self._api_get(f"/nodule/{annotation_id}") - - if display_detail and HAS_IPYTHON: - info = d.get("detail", d) if isinstance(d, dict) else d - rows = [(k, v) for k, v in info.items() if not str(k).startswith("_")] - display(pd.DataFrame(rows, columns=["Field", "Value"])) - return d - - # ── G. Summary ──────────────────────────────────────────────────────────── - - def summary(self) -> dict: - if self._engine: - return self._engine.summary() - return self._api_get("/health") - - # ── Internals ───────────────────────────────────────────────────────────── - - def _plot_slice(self, sl, title: str = "", figsize: tuple = (8, 8)): - """Render a SliceResult with matplotlib.""" - if not HAS_MPL: - print("matplotlib required for inline plotting") - return - - fig, ax = plt.subplots(1, 1, figsize=figsize) - ax.imshow(sl.windowed, cmap="gray", aspect="auto") - - if sl.mask is not None and sl.mask.any(): - mask_rgba = np.zeros((*sl.mask.shape, 4), dtype=np.float32) - mask_rgba[sl.mask > 0] = [1, 0.2, 0.2, 0.4] - ax.imshow(mask_rgba, aspect="auto") - - ax.set_title(title, fontsize=10) - ax.axis("off") - plt.tight_layout() - plt.show() - - @staticmethod - def _format_results(df: pd.DataFrame) -> pd.DataFrame: - """Pick display columns for nice notebook rendering.""" - cols = [ - c - for c in [ - "annotation_id", - "dataset", - "label", - "lobe_name", - "nodule_mean_diam_mm", - "pleural_distance_mm", - "reinsertion_lobe", - "reinsertion_nodule_diam_mm", - ] - if c in df.columns - ] - return df[cols] if cols else df - - def _api_get(self, path: str) -> dict: - import requests - - resp = requests.get(f"{self._api_url}{path}", timeout=15) - resp.raise_for_status() - return resp.json() - - def _api_post(self, path: str, body: dict) -> dict: - import requests - - resp = requests.post(f"{self._api_url}{path}", json=body, timeout=30) - resp.raise_for_status() - return resp.json() - - def _api_get_bytes(self, path: str) -> Optional[bytes]: - import requests - - resp = requests.get(f"{self._api_url}{path}", timeout=30) - if resp.ok: - return resp.content - return None diff --git a/itrialspace/src/itrialspace/apps/retriever/search.py b/itrialspace/src/itrialspace/apps/retriever/search.py deleted file mode 100644 index e3cdc6ea95a00f6438570a0445baf909bcac2dd1..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/search.py +++ /dev/null @@ -1,300 +0,0 @@ -""" -FacetedSearch — multi-dimensional filtering over the NoduleIndex. - -Wraps itrialspace.NoduleQuery with a typed filter dataclass and -result-summary logic for the retriever UI layer. -""" - -from __future__ import annotations - -from dataclasses import asdict, dataclass -from typing import Optional - -import pandas as pd - -from itrialspace import ( - DATASET_NAMES, - LOBE_NAMES, - SIDE_NAMES, - ZONE_NAMES, - NoduleIndex, - NoduleQuery, -) - -# --------------------------------------------------------------------------- -# Filter specification -# --------------------------------------------------------------------------- - - -@dataclass -class SearchFilters: - """Typed, serialisable filter spec for faceted search.""" - - # Dataset selection - datasets: Optional[list[str]] = None # None = all - exclude_datasets: Optional[list[str]] = None - - # Label - label: Optional[int] = None # 0, 1, or None = any - - # Anatomy - lobe: Optional[list[str]] = None - lung_zone: Optional[list[str]] = None - lung_side: Optional[str] = None - central_peripheral: Optional[str] = None - - # Size (mm) - diameter_min: Optional[float] = None - diameter_max: Optional[float] = None - - # Distance (mm) - pleural_distance_min: Optional[float] = None - pleural_distance_max: Optional[float] = None - airway_distance_min: Optional[float] = None - airway_distance_max: Optional[float] = None - - # Reinsertion space (preferred for retrieval) - reinsertion_lobe: Optional[list[str]] = None - reinsertion_zone: Optional[list[str]] = None - reinsertion_side: Optional[str] = None - reinsertion_diameter_min: Optional[float] = None - reinsertion_diameter_max: Optional[float] = None - reinsertion_pleural_min: Optional[float] = None - reinsertion_pleural_max: Optional[float] = None - reinsertion_cc_pct_min: Optional[float] = None - reinsertion_cc_pct_max: Optional[float] = None - - # Multi-nodule - n_nodules_min: Optional[int] = None - n_nodules_max: Optional[int] = None - - # Population / label source - population_type: Optional[str] = None # "screening" | "diagnostic" - label_source: Optional[str] = None # "histopathology" | "radiology" - - # Pagination / sampling - limit: Optional[int] = None - offset: int = 0 - sample_n: Optional[int] = None - sample_seed: Optional[int] = None - - # Sort - sort_by: Optional[str] = None - sort_ascending: bool = True - - def to_dict(self) -> dict: - return {k: v for k, v in asdict(self).items() if v is not None} - - -# --------------------------------------------------------------------------- -# Search result container -# --------------------------------------------------------------------------- - - -@dataclass -class SearchResult: - """Wraps a DataFrame of matches + metadata.""" - - df: pd.DataFrame - total_matching: int - filters_applied: SearchFilters - facet_counts: Optional[dict] = None - - def __repr__(self) -> str: - shown = len(self.df) - return f"SearchResult({shown}/{self.total_matching} shown)" - - -# --------------------------------------------------------------------------- -# Faceted search engine -# --------------------------------------------------------------------------- - -# Label-source / population-type dataset maps (from spec.py) -_LABEL_SOURCE_MAP = { - "histopathology": ["DLCS24", "LUNA25", "NSCLCR", "IMDCT", "LUNGx"], - "radiology": ["LUNA16", "LNDbv4"], -} -_POPULATION_TYPE_MAP = { - "screening": ["DLCS24", "LUNA16", "LUNA25", "LNDbv4"], - "diagnostic": ["NSCLCR", "IMDCT", "LUNGx"], -} - - -class FacetedSearch: - """ - Apply SearchFilters to a NoduleIndex and return SearchResult. - - Builds a NoduleQuery chain from the filter dataclass, runs it, and - computes facet counts for the UI sidebar. - """ - - def __init__(self, index: NoduleIndex): - self._index = index - - @property - def index(self) -> NoduleIndex: - return self._index - - # ── Main entry ──────────────────────────────────────────────────────────── - - def search(self, filters: SearchFilters) -> SearchResult: - """Apply *filters* and return a SearchResult.""" - q = self._build_query(filters) - total = q.count() - - # Fetch (optionally sampled) results - if filters.sample_n is not None: - q = q.sample(filters.sample_n, seed=filters.sample_seed) - - df = q.fetch() - - # Sort - if filters.sort_by and filters.sort_by in df.columns: - df = df.sort_values(filters.sort_by, ascending=filters.sort_ascending).reset_index( - drop=True - ) - - # Paginate - if filters.limit is not None: - start = filters.offset - df = df.iloc[start : start + filters.limit].reset_index(drop=True) - - facets = self._compute_facets(filters) - - return SearchResult( - df=df, - total_matching=total, - filters_applied=filters, - facet_counts=facets, - ) - - # ── Facet counts ────────────────────────────────────────────────────────── - - def _compute_facets(self, filters: SearchFilters) -> dict: - """Compute value counts for each facet dimension. - - Uses the *unfiltered* index so users can see options outside - their current selection (like an e-commerce sidebar). - """ - df = self._index.df - facets: dict = {} - - facets["datasets"] = df["dataset"].value_counts().to_dict() - - if "lobe_name" in df.columns: - facets["lobes"] = df["lobe_name"].value_counts().to_dict() - - if "lung_zone" in df.columns: - facets["zones"] = df["lung_zone"].value_counts().to_dict() - - if "lung_side" in df.columns: - facets["sides"] = df["lung_side"].value_counts().to_dict() - - if "central_peripheral" in df.columns: - facets["central_peripheral"] = df["central_peripheral"].value_counts().to_dict() - - if "label" in df.columns: - label_counts: dict = {} - label_counts["malignant"] = int((df["label"] == 1).sum()) - label_counts["benign"] = int((df["label"] == 0).sum()) - label_counts["unlabelled"] = int(df["label"].isna().sum()) - facets["labels"] = label_counts - - # Size histogram bins - if "nodule_mean_diam_mm" in df.columns: - bins = [0, 5, 10, 15, 20, 30, 200] - lbls = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] - facets["size_buckets"] = ( - pd.cut(df["nodule_mean_diam_mm"], bins=bins, labels=lbls).value_counts().to_dict() - ) - - return facets - - # ── Query builder ───────────────────────────────────────────────────────── - - def _build_query(self, f: SearchFilters) -> NoduleQuery: - """Translate SearchFilters into a NoduleQuery chain.""" - q = self._index.query() - - # Dataset selection (label-source / population-type → dataset list) - effective_datasets = self._resolve_datasets(f) - if effective_datasets is not None: - q = q.datasets(effective_datasets) - if f.exclude_datasets: - q = q.exclude_datasets(f.exclude_datasets) - - # Label - if f.label is not None: - q = q.label(f.label) - - # Anatomy - if f.lobe: - q = q.lobe(f.lobe) - if f.lung_zone: - q = q.lung_zone(f.lung_zone) - if f.lung_side: - q = q.lung_side(f.lung_side) - if f.central_peripheral: - q = q.central_peripheral(f.central_peripheral) - - # Size - q = q.diameter(min=f.diameter_min, max=f.diameter_max) - - # Distances - q = q.pleural_distance(min=f.pleural_distance_min, max=f.pleural_distance_max) - q = q.airway_distance(min=f.airway_distance_min, max=f.airway_distance_max) - - # Reinsertion-space filters - if f.reinsertion_lobe: - q = q.reinsertion_lobe(f.reinsertion_lobe) - if f.reinsertion_zone: - q = q.reinsertion_zone(f.reinsertion_zone) - if f.reinsertion_side: - q = q.reinsertion_side(f.reinsertion_side) - q = q.reinsertion_diameter(min=f.reinsertion_diameter_min, max=f.reinsertion_diameter_max) - q = q.reinsertion_pleural(min=f.reinsertion_pleural_min, max=f.reinsertion_pleural_max) - q = q.reinsertion_cc_pct(min=f.reinsertion_cc_pct_min, max=f.reinsertion_cc_pct_max) - - # Multi-nodule - q = q.n_nodules_in_patient(min=f.n_nodules_min, max=f.n_nodules_max) - - return q - - @staticmethod - def _resolve_datasets(f: SearchFilters) -> Optional[list[str]]: - """Merge explicit datasets with label-source/population-type filters.""" - explicit = set(f.datasets) if f.datasets else None - - # Label source filter - ls_set = None - if f.label_source and f.label_source in _LABEL_SOURCE_MAP: - ls_set = set(_LABEL_SOURCE_MAP[f.label_source]) - - # Population type filter - pt_set = None - if f.population_type and f.population_type in _POPULATION_TYPE_MAP: - pt_set = set(_POPULATION_TYPE_MAP[f.population_type]) - - # Intersect all non-None sets - result = None - for s in [explicit, ls_set, pt_set]: - if s is not None: - result = s if result is None else result & s - - return list(result) if result is not None else None - - # ── Convenience: available options ──────────────────────────────────────── - - @property - def available_filters(self) -> dict: - """Return the valid values for each categorical filter.""" - return { - "datasets": DATASET_NAMES, - "lobes": LOBE_NAMES, - "zones": ZONE_NAMES, - "sides": SIDE_NAMES, - "labels": [0, 1, None], - "central_peripheral": ["central", "peripheral"], - "population_types": ["screening", "diagnostic", "all"], - "label_sources": ["histopathology", "radiology", "all"], - } diff --git a/itrialspace/src/itrialspace/apps/retriever/similarity.py b/itrialspace/src/itrialspace/apps/retriever/similarity.py deleted file mode 100644 index 089f7f9624e499980a985be737268873fd2a1c9e..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/similarity.py +++ /dev/null @@ -1,248 +0,0 @@ -""" -SimilarityEngine — query-by-example nearest-neighbour retrieval. - -Given a reference nodule (by annotation_id), find the k most similar -nodules using weighted Euclidean distance over the reinsertion feature -space with optional per-dataset z-score normalisation. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Optional - -import numpy as np -import pandas as pd - -from itrialspace import NoduleIndex - -# --------------------------------------------------------------------------- -# Feature definitions -# --------------------------------------------------------------------------- - -# The 12 reinsertion columns used as the similarity feature vector. -# Categorical columns are one-hot-encoded; numeric columns are z-normalised. -_NUMERIC_FEATURES = [ - "reinsertion_lobe_cc_pct", - "reinsertion_lobe_ml_pct", - "reinsertion_lobe_ap_pct", - "reinsertion_lung_cc_pct", - "reinsertion_lung_ml_pct", - "reinsertion_lung_ap_pct", - "reinsertion_pleural_dist_mm", - "reinsertion_airway_dist_mm", - "reinsertion_nodule_diam_mm", -] - -_CATEGORICAL_FEATURES = [ - "reinsertion_lobe", - "reinsertion_lung_side", - "reinsertion_lung_zone", -] - -# Default weights (higher = more important in distance calc) -DEFAULT_WEIGHTS = { - "reinsertion_lobe_cc_pct": 1.0, - "reinsertion_lobe_ml_pct": 0.8, - "reinsertion_lobe_ap_pct": 0.8, - "reinsertion_lung_cc_pct": 0.6, - "reinsertion_lung_ml_pct": 0.5, - "reinsertion_lung_ap_pct": 0.5, - "reinsertion_pleural_dist_mm": 1.2, - "reinsertion_airway_dist_mm": 0.7, - "reinsertion_nodule_diam_mm": 1.0, - # Categorical one-hot penalty (lobe mismatch costs this much) - "_lobe_mismatch": 3.0, - "_side_mismatch": 2.0, - "_zone_mismatch": 1.5, -} - - -# --------------------------------------------------------------------------- -# Result container -# --------------------------------------------------------------------------- - - -@dataclass -class SimilarityResult: - """A single similar nodule with its distance.""" - - annotation_id: str - dataset: str - distance: float - rank: int - feature_deltas: dict # per-feature raw delta for explainability - row: pd.Series = field(repr=False) - - def __repr__(self) -> str: - return ( - f"SimilarityResult(rank={self.rank} | d={self.distance:.4f} | " - f"{self.dataset}/{self.annotation_id})" - ) - - -# --------------------------------------------------------------------------- -# Similarity engine -# --------------------------------------------------------------------------- - - -class SimilarityEngine: - """ - Weighted nearest-neighbour search over reinsertion feature space. - - On construction the engine z-normalises numeric features (globally or - per-dataset, controlled by *per_dataset_norm*) and caches the result - matrix for O(n) distance lookups. - """ - - def __init__( - self, - index: NoduleIndex, - weights: Optional[dict[str, float]] = None, - per_dataset_norm: bool = False, - ): - self._index = index - self._weights = {**DEFAULT_WEIGHTS, **(weights or {})} - self._per_dataset = per_dataset_norm - - # Build normalised feature matrix - self._df = index.df.copy() - self._feat_matrix, self._feat_cols = self._build_features() - - # ── Public API ──────────────────────────────────────────────────────────── - - def find_similar( - self, - annotation_id: str, - k: int = 10, - exclude_same_patient: bool = True, - include_datasets: Optional[list[str]] = None, - exclude_datasets: Optional[list[str]] = None, - label: Optional[int] = None, - ) -> list[SimilarityResult]: - """Find the k most similar nodules to the given reference. - - Args: - annotation_id: The reference nodule. - k: Number of results to return. - exclude_same_patient: Exclude nodules from the same patient. - include_datasets: Restrict search to these datasets. - exclude_datasets: Exclude these datasets. - label: Filter by label (0, 1, or None for any). - - Returns: - List of SimilarityResult sorted by distance ascending. - """ - ref_mask = self._df["annotation_id"] == annotation_id - if not ref_mask.any(): - raise KeyError(f"annotation_id '{annotation_id}' not found in index") - - ref_idx = ref_mask.idxmax() - ref_row = self._df.loc[ref_idx] - ref_vec = self._feat_matrix[ref_idx] - - # Build candidate mask - cand_mask = ~ref_mask # exclude self - if exclude_same_patient: - cand_mask &= self._df["patient_id"] != ref_row["patient_id"] - if include_datasets: - cand_mask &= self._df["dataset"].isin(include_datasets) - if exclude_datasets: - cand_mask &= ~self._df["dataset"].isin(exclude_datasets) - if label is not None: - cand_mask &= self._df["label"] == label - - cand_indices = self._df.index[cand_mask].to_numpy() - if len(cand_indices) == 0: - return [] - - # Compute distances - cand_vecs = self._feat_matrix[cand_indices] - dists = np.linalg.norm(cand_vecs - ref_vec, axis=1) - - # Top-k - top_k_local = np.argsort(dists)[:k] - top_k_global = cand_indices[top_k_local] - top_k_dists = dists[top_k_local] - - results = [] - for rank, (gi, d) in enumerate(zip(top_k_global, top_k_dists), 1): - row = self._df.loc[gi] - deltas = self._compute_deltas(ref_vec, self._feat_matrix[gi]) - results.append( - SimilarityResult( - annotation_id=str(row["annotation_id"]), - dataset=str(row["dataset"]), - distance=float(d), - rank=rank, - feature_deltas=deltas, - row=row, - ) - ) - return results - - def get_feature_vector(self, annotation_id: str) -> dict[str, float]: - """Return the normalised feature vector for a nodule.""" - mask = self._df["annotation_id"] == annotation_id - if not mask.any(): - raise KeyError(f"annotation_id '{annotation_id}' not found") - idx = mask.idxmax() - return dict(zip(self._feat_cols, self._feat_matrix[idx])) - - # ── Internals ───────────────────────────────────────────────────────────── - - def _build_features(self) -> tuple[np.ndarray, list[str]]: - """Build the normalised numeric + one-hot feature matrix.""" - df = self._df - feat_cols: list[str] = [] - feat_arrays: list[np.ndarray] = [] - - # Numeric features — z-score normalise - for col in _NUMERIC_FEATURES: - if col not in df.columns: - continue - raw = df[col].fillna(0.0).to_numpy(dtype=np.float64) - w = self._weights.get(col, 1.0) - - if self._per_dataset: - normed = np.zeros_like(raw) - for ds in df["dataset"].unique(): - ds_mask = (df["dataset"] == ds).to_numpy() - subset = raw[ds_mask] - mu, sigma = subset.mean(), subset.std() - sigma = max(sigma, 1e-8) - normed[ds_mask] = (subset - mu) / sigma - else: - mu, sigma = raw.mean(), raw.std() - sigma = max(sigma, 1e-8) - normed = (raw - mu) / sigma - - feat_arrays.append(normed * w) - feat_cols.append(col) - - # Categorical features — one-hot with mismatch penalty - penalty_map = { - "reinsertion_lobe": self._weights.get("_lobe_mismatch", 3.0), - "reinsertion_lung_side": self._weights.get("_side_mismatch", 2.0), - "reinsertion_lung_zone": self._weights.get("_zone_mismatch", 1.5), - } - for col in _CATEGORICAL_FEATURES: - if col not in df.columns: - continue - penalty = penalty_map.get(col, 1.0) - dummies = pd.get_dummies(df[col], prefix=col).to_numpy(dtype=np.float64) - dummies *= penalty - for i in range(dummies.shape[1]): - feat_cols.append(f"{col}_{i}") - feat_arrays.append(dummies) - - matrix = np.column_stack(feat_arrays) if feat_arrays else np.zeros((len(df), 0)) - return matrix, feat_cols - - def _compute_deltas(self, ref_vec: np.ndarray, cand_vec: np.ndarray) -> dict[str, float]: - """Per-feature delta for explainability.""" - deltas = {} - for i, col in enumerate(self._feat_cols): - if i < len(ref_vec): - deltas[col] = float(cand_vec[i] - ref_vec[i]) - return deltas diff --git a/itrialspace/src/itrialspace/apps/retriever/slicer.py b/itrialspace/src/itrialspace/apps/retriever/slicer.py deleted file mode 100644 index a41a19ddca249e5e35e088fb373d170ee7d425c9..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/slicer.py +++ /dev/null @@ -1,312 +0,0 @@ -""" -NIfTISlicer — extract 2-D slices from NIfTI CT/mask volumes. - -Supports axial, coronal, sagittal views with optional overlay of -nodule masks or organ segmentations. Returns numpy arrays that -can be converted to PNG by the API layer or rendered directly in -matplotlib / Streamlit. -""" - -from __future__ import annotations - -import io -import os -from dataclasses import dataclass -from enum import Enum -from typing import Optional - -import numpy as np - -try: - import nibabel as nib -except ImportError: - nib = None # type: ignore[assignment] - -try: - from PIL import Image -except ImportError: - Image = None # type: ignore[assignment] - - -class SliceAxis(str, Enum): - AXIAL = "axial" # Z-axis - CORONAL = "coronal" # Y-axis - SAGITTAL = "sagittal" # X-axis - - -@dataclass -class SliceResult: - """A rendered 2-D slice with metadata.""" - - image: np.ndarray # 2-D float array (HU or normalised) - mask: Optional[np.ndarray] # 2-D binary mask (or None) - axis: SliceAxis - slice_index: int - shape_3d: tuple[int, int, int] - window_center: float - window_width: float - spacing_mm: tuple[float, float, float] - - @property - def windowed(self) -> np.ndarray: - """Apply CT window and return uint8 [0, 255].""" - lo = self.window_center - self.window_width / 2 - hi = self.window_center + self.window_width / 2 - img = np.clip(self.image, lo, hi) - img = ((img - lo) / (hi - lo) * 255).astype(np.uint8) - return img - - def to_png_bytes(self, overlay_alpha: float = 0.35, labels: bool = True) -> bytes: - """Render as PNG bytes with optional mask overlay and orientation labels.""" - if Image is None: - raise ImportError("Pillow is required: pip install Pillow") - - base = self.windowed - rgb = np.stack([base, base, base], axis=-1) # grayscale → RGB - - if self.mask is not None and self.mask.any(): - overlay = np.zeros_like(rgb) - overlay[self.mask > 0] = [255, 50, 50] # red overlay - alpha = overlay_alpha - blended = (rgb.astype(float) * (1 - alpha) + overlay.astype(float) * alpha).astype( - np.uint8 - ) - # Only blend where mask is active - rgb[self.mask > 0] = blended[self.mask > 0] - - img = Image.fromarray(rgb) - - # ── Orientation labels (radiology convention) ────────────────── - if labels: - from PIL import ImageDraw, ImageFont - - draw = ImageDraw.Draw(img) - try: - font = ImageFont.truetype( - "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 14 - ) - except (IOError, OSError): - font = ImageFont.load_default() - - h_img, w_img = rgb.shape[0], rgb.shape[1] - label_color = (255, 255, 0) # yellow - shadow = (0, 0, 0) - m = 4 # margin - - def _lbl(x, y, text, anchor=None): - draw.text((x + 1, y + 1), text, fill=shadow, font=font, anchor=anchor) - draw.text((x, y), text, fill=label_color, font=font, anchor=anchor) - - if self.axis == SliceAxis.AXIAL: - _lbl(m, h_img // 2, "R", "lm") # left = patient-Right - _lbl(w_img - m, h_img // 2, "L", "rm") # right = patient-Left - _lbl(w_img // 2, m, "A", "mt") # top = Anterior - _lbl(w_img // 2, h_img - m, "P", "mb") # bot = Posterior - elif self.axis == SliceAxis.CORONAL: - _lbl(m, h_img // 2, "R", "lm") - _lbl(w_img - m, h_img // 2, "L", "rm") - _lbl(w_img // 2, m, "S", "mt") # top = Superior - _lbl(w_img // 2, h_img - m, "I", "mb") # bot = Inferior - elif self.axis == SliceAxis.SAGITTAL: - _lbl(m, h_img // 2, "A", "lm") # left = Anterior - _lbl(w_img - m, h_img // 2, "P", "rm") # right = Posterior - _lbl(w_img // 2, m, "S", "mt") - _lbl(w_img // 2, h_img - m, "I", "mb") - - buf = io.BytesIO() - img.save(buf, format="PNG") - return buf.getvalue() - - -# Default CT window presets -WINDOW_PRESETS = { - "lung": {"center": -600, "width": 1500}, - "mediastinum": {"center": 40, "width": 400}, - "bone": {"center": 400, "width": 1800}, - "soft_tissue": {"center": 50, "width": 350}, -} - - -class NIfTISlicer: - """ - Load NIfTI volumes and extract 2-D slices for the viewer. - - Uses a small LRU cache to avoid re-loading the same volume - on sequential slice requests (e.g. scrolling through axial slices). - """ - - def __init__(self, cache_size: int = 4): - if nib is None: - raise ImportError("nibabel is required: pip install nibabel") - self._cache: dict[str, np.ndarray] = {} - self._cache_order: list[str] = [] - self._cache_size = cache_size - self._affine_cache: dict[str, np.ndarray] = {} - - # ── Volume loading ──────────────────────────────────────────────────────── - - def _load(self, path: str) -> tuple[np.ndarray, np.ndarray]: - """Load a NIfTI volume, reorient to RAS+ canonical, return (data, affine).""" - if path in self._cache: - return self._cache[path], self._affine_cache[path] - - if not os.path.isfile(path): - raise FileNotFoundError(f"NIfTI file not found: {path}") - - img = nib.load(path) - # Reorient to RAS+ canonical so axes are always: - # axis-0 = R→L (X), axis-1 = A→P (Y), axis-2 = I→S (Z) - canon = nib.as_closest_canonical(img) - data = np.asarray(canon.dataobj, dtype=np.float32) - - # Squeeze extra dims (some files are 5-D) - while data.ndim > 3: - data = data[..., 0] - - affine = canon.affine - - # Cache management (LRU eviction) - if len(self._cache) >= self._cache_size: - evict = self._cache_order.pop(0) - self._cache.pop(evict, None) - self._affine_cache.pop(evict, None) - self._cache[path] = data - self._affine_cache[path] = affine - self._cache_order.append(path) - - return data, affine - - def volume_shape(self, path: str) -> tuple[int, int, int]: - """Return the 3-D shape of a NIfTI volume.""" - data, _ = self._load(path) - return data.shape[:3] # type: ignore[return-value] - - def voxel_spacing(self, path: str) -> tuple[float, float, float]: - """Return voxel spacing in mm from the affine.""" - _, affine = self._load(path) - spacing = np.abs(np.diag(affine)[:3]) - return tuple(float(s) for s in spacing) # type: ignore[return-value] - - # ── Slice extraction ────────────────────────────────────────────────────── - - def get_slice( - self, - ct_path: str, - axis: SliceAxis = SliceAxis.AXIAL, - index: Optional[int] = None, - mask_path: Optional[str] = None, - window: str = "lung", - window_center: Optional[float] = None, - window_width: Optional[float] = None, - ) -> SliceResult: - """Extract a 2-D slice from a CT volume. - - Args: - ct_path: Path to CT NIfTI. - axis: Slice orientation. - index: Slice index. None = middle slice. - mask_path: Optional path to mask NIfTI for overlay. - window: CT window preset name. - window_center: Override window center. - window_width: Override window width. - """ - data, affine = self._load(ct_path) - shape = data.shape[:3] - spacing = tuple(float(s) for s in np.abs(np.diag(affine)[:3])) - - # Determine axis dimension - axis_dim = {"axial": 2, "coronal": 1, "sagittal": 0}[axis.value] - max_idx = shape[axis_dim] - 1 - - if index is None: - index = max_idx // 2 - index = max(0, min(index, max_idx)) - - # Extract slice and apply radiology display transform. - # After RAS+ canonical load: - # axis-0 = R→L (X), axis-1 = A→P (Y), axis-2 = I→S (Z) - if axis_dim == 2: # Axial — fixed Z, shows (X, Y) plane - img_slice = data[:, :, index] - elif axis_dim == 1: # Coronal — fixed Y, shows (X, Z) plane - img_slice = data[:, index, :] - else: # Sagittal — fixed X, shows (Y, Z) plane - img_slice = data[index, :, :] - - # Apply radiology display transform: - # Axial: .T → (Y,X) then fliplr (R on left) then flipud (A at top) - # Coronal: .T → (Z,X) then fliplr (R on left) then flipud (S at top) - # Sagittal: .T → (Z,Y) then fliplr (A on left) then flipud (S at top) - img_slice = np.flipud(np.fliplr(img_slice.T)) - - # Mask overlay - mask_slice = None - if mask_path and os.path.isfile(mask_path): - mask_data, _ = self._load(mask_path) - # Ensure compatible shape - if mask_data.shape[:3] == shape: - if axis_dim == 2: - mask_slice = mask_data[:, :, index] - elif axis_dim == 1: - mask_slice = mask_data[:, index, :] - else: - mask_slice = mask_data[index, :, :] - # Same radiology display transform as CT - mask_slice = np.flipud(np.fliplr(mask_slice.T)) - mask_slice = (mask_slice > 0).astype(np.uint8) - - # Window - wc = ( - window_center - if window_center is not None - else WINDOW_PRESETS.get(window, WINDOW_PRESETS["lung"])["center"] - ) - ww = ( - window_width - if window_width is not None - else WINDOW_PRESETS.get(window, WINDOW_PRESETS["lung"])["width"] - ) - - return SliceResult( - image=img_slice, - mask=mask_slice, - axis=SliceAxis(axis), - slice_index=index, - shape_3d=shape, # type: ignore[arg-type] - window_center=wc, - window_width=ww, - spacing_mm=spacing, # type: ignore[arg-type] - ) - - def get_nodule_slice( - self, - ct_path: str, - mask_path: str, - coord_x: float, - coord_y: float, - coord_z: float, - axis: SliceAxis = SliceAxis.AXIAL, - window: str = "lung", - ) -> SliceResult: - """Extract the slice passing through the nodule centre. - - Coordinates are in world/physical space (mm) as stored in the - nodule profile CSVs. We convert to voxel indices using the - inverse affine. - """ - data, affine = self._load(ct_path) - inv = np.linalg.inv(affine) - world = np.array([coord_x, coord_y, coord_z, 1.0]) - voxel = inv @ world - - # Map axis → voxel dimension - axis_to_dim = {"axial": 2, "coronal": 1, "sagittal": 0} - dim = axis_to_dim[axis.value] - idx = int(round(voxel[dim])) - - return self.get_slice( - ct_path, - axis=axis, - index=idx, - mask_path=mask_path, - window=window, - ) diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/__init__.py b/itrialspace/src/itrialspace/apps/retriever/ui/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 2ba9bc66780dcd05f26bcd6aed8846190549cd2f..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/app.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/app.cpython-310.pyc deleted file mode 100644 index af5dbca2780ce9f6889db40b1b1a32ca1ac24cca..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/app.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/app.py b/itrialspace/src/itrialspace/apps/retriever/ui/app.py deleted file mode 100644 index 9ee01afec0b9747ea1a6fa18c9da3d74e709c6a6..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/apps/retriever/ui/app.py +++ /dev/null @@ -1,686 +0,0 @@ -""" -Streamlit frontend for the iTrialSpace Retriever. - -Launch: - streamlit run retriever/ui/app.py -- [--api-url http://localhost:8421] - -Two modes: - 1. **Direct mode** (default): Loads the NoduleIndex in-process. - 2. **API mode** (--api-url): Calls the FastAPI backend via requests. -""" - -from __future__ import annotations - -import sys -from typing import Optional - -import numpy as np -import pandas as pd -import streamlit as st - -# --------------------------------------------------------------------------- -# Mode detection (direct vs API) -# --------------------------------------------------------------------------- - - -def _parse_api_url() -> Optional[str]: - """Check for --api-url flag in sys.argv (Streamlit passes args after --).""" - for i, arg in enumerate(sys.argv): - if arg == "--api-url" and i + 1 < len(sys.argv): - return sys.argv[i + 1] - return None - - -API_URL = _parse_api_url() - -# --------------------------------------------------------------------------- -# Engine / API wrappers -# --------------------------------------------------------------------------- - - -@st.cache_resource(show_spinner="Loading 13k+ nodules …") -def _load_engine(): - """Load the retriever engine in direct mode.""" - from itrialspace.apps.retriever.engine import RetrieverEngine - - return RetrieverEngine.from_defaults(verbose=True) - - -def _search(filters: dict) -> dict: - """Run a search, returning {total_matching, results (list[dict]), facet_counts}.""" - if API_URL: - import requests - - resp = requests.post(f"{API_URL}/search", json=filters, timeout=30) - resp.raise_for_status() - return resp.json() - else: - from itrialspace.apps.retriever.search import SearchFilters - - engine = _load_engine() - sf = SearchFilters(**{k: v for k, v in filters.items() if v is not None}) - result = engine.search(sf) - rows = result.df.to_dict(orient="records") - # Serialise NaN - for r in rows: - for k, v in r.items(): - if isinstance(v, float) and np.isnan(v): - r[k] = None - return { - "total_matching": result.total_matching, - "results": rows, - "facet_counts": result.facet_counts, - } - - -def _find_similar(annotation_id: str, k: int, **kwargs) -> list[dict]: - if API_URL: - import requests - - body = {"annotation_id": annotation_id, "k": k, **kwargs} - resp = requests.post(f"{API_URL}/similar", json=body, timeout=30) - resp.raise_for_status() - return resp.json()["results"] - else: - engine = _load_engine() - results = engine.find_similar(annotation_id=annotation_id, k=k, **kwargs) - return [ - { - "annotation_id": r.annotation_id, - "dataset": r.dataset, - "distance": round(r.distance, 4), - "rank": r.rank, - } - for r in results - ] - - -def _find_match(lobe: str, k: int = 10, **kwargs) -> list[dict]: - if API_URL: - import requests - - body = {"lobe": lobe, "k": k, **kwargs} - resp = requests.post(f"{API_URL}/matcher", json=body, timeout=30) - resp.raise_for_status() - return resp.json()["results"] - else: - engine = _load_engine() - results = engine.find_reinsertion_match(lobe=lobe, k=k, **kwargs) - return [ - { - "annotation_id": m.annotation_id, - "dataset": m.dataset, - "score": round(m.score, 4), - "lobe": m.lobe, - "diameter_mm": round(m.diameter_mm, 2), - "label": m.label, - } - for m in results - ] - - -def _get_nodule_detail(annotation_id: str) -> dict: - if API_URL: - import requests - - resp = requests.get(f"{API_URL}/nodule/{annotation_id}", timeout=15) - resp.raise_for_status() - return resp.json() - else: - engine = _load_engine() - return engine.get_nodule_detail(annotation_id) - - -def _get_slice_png( - ct_path: str, axis: str, index: int, mask_path: str = None, window: str = "lung" -) -> Optional[bytes]: - """Return PNG bytes for a CT slice.""" - if API_URL: - import requests - - params = {"ct_path": ct_path, "axis": axis, "index": index, "window": window} - if mask_path: - params["mask_path"] = mask_path - resp = requests.get(f"{API_URL}/ct/slice", params=params, timeout=30) - if resp.ok: - return resp.content - return None - else: - try: - engine = _load_engine() - sl = engine.get_slice( - ct_path=ct_path, axis=axis, index=index, mask_path=mask_path, window=window - ) - return sl.to_png_bytes() - except Exception: - return None - - -def _get_nodule_view_png( - annotation_id: str, axis: str = "axial", window: str = "lung", show_mask: bool = True -) -> Optional[bytes]: - """Return PNG bytes for the CT slice at the nodule centre.""" - if API_URL: - import requests - - params = { - "annotation_id": annotation_id, - "axis": axis, - "window": window, - "show_mask": show_mask, - } - resp = requests.get(f"{API_URL}/ct/nodule-view", params=params, timeout=30) - if resp.ok: - return resp.content - return None - else: - try: - engine = _load_engine() - sl = engine.get_nodule_view( - annotation_id, axis=axis, window=window, show_mask=show_mask - ) - return sl.to_png_bytes() - except Exception: - return None - - -def _get_volume_info(ct_path: str) -> Optional[dict]: - """Return {shape, spacing_mm} for a CT volume.""" - if API_URL: - import requests - - resp = requests.get(f"{API_URL}/ct/info", params={"ct_path": ct_path}, timeout=15) - if resp.ok: - return resp.json() - return None - else: - try: - engine = _load_engine() - shape = engine.volume_shape(ct_path) - spacing = engine._slicer.voxel_spacing(ct_path) - return {"shape": list(shape), "spacing_mm": [round(s, 3) for s in spacing]} - except Exception: - return None - - -def _resolve_paths(annotation_id: str) -> dict: - """Resolve all file paths for a nodule.""" - if API_URL: - import requests - - resp = requests.get(f"{API_URL}/nodule/{annotation_id}", timeout=15) - if resp.ok: - data = resp.json() - return data.get("paths", {}) - return {} - else: - try: - engine = _load_engine() - return engine.resolve_paths(annotation_id) - except Exception: - return {} - - -def _available_filters() -> dict: - if API_URL: - import requests - - resp = requests.get(f"{API_URL}/filters", timeout=10) - resp.raise_for_status() - return resp.json() - else: - engine = _load_engine() - return engine.available_filters - - -# --------------------------------------------------------------------------- -# Streamlit UI -# --------------------------------------------------------------------------- - - -def main(): - st.set_page_config( - page_title="iTrialSpace Retriever", - page_icon="🫁", - layout="wide", - initial_sidebar_state="expanded", - ) - - st.title("iTrialSpace Retriever") - st.caption("Interactive retrieval across 13,140 lung nodules from 7 datasets") - - # Sidebar filters - with st.sidebar: - st.header("Filters") - af = _available_filters() - - # Tabs for different modes - mode = st.radio("Mode", ["Search", "Similarity", "Matcher"], horizontal=True) - - if mode == "Search": - filters = _build_search_sidebar(af) - elif mode == "Similarity": - sim_params = _build_similarity_sidebar() - else: - match_params = _build_matcher_sidebar(af) - - # Main content area - if mode == "Search": - _render_search(filters) - elif mode == "Similarity": - _render_similarity(sim_params) - else: - _render_matcher(match_params) - - -# --------------------------------------------------------------------------- -# Sidebar builders -# --------------------------------------------------------------------------- - - -def _build_search_sidebar(af: dict) -> dict: - """Build the faceted search sidebar, return filter dict.""" - filters: dict = {} - - # Dataset multi-select - ds_options = af.get("datasets", []) - selected_ds = st.multiselect("Datasets", ds_options, default=None) - if selected_ds: - filters["datasets"] = selected_ds - - # Label - label_choice = st.selectbox("Label", ["Any", "Malignant (1)", "Benign (0)"]) - if label_choice == "Malignant (1)": - filters["label"] = 1 - elif label_choice == "Benign (0)": - filters["label"] = 0 - - # Lobe - lobe_options = af.get("lobes", []) - selected_lobes = st.multiselect("Lobe", lobe_options, default=None) - if selected_lobes: - filters["lobe"] = selected_lobes - - # Zone - zone_options = af.get("zones", []) - selected_zones = st.multiselect("Zone", zone_options, default=None) - if selected_zones: - filters["lung_zone"] = selected_zones - - # Side - side = st.selectbox("Side", ["Any", "left", "right"]) - if side != "Any": - filters["lung_side"] = side - - # Central/peripheral - cp = st.selectbox("Position", ["Any", "central", "peripheral"]) - if cp != "Any": - filters["central_peripheral"] = cp - - # Diameter range - st.subheader("Size (mm)") - diam_range = st.slider("Diameter", 0.0, 100.0, (0.0, 100.0), step=1.0) - if diam_range[0] > 0: - filters["diameter_min"] = diam_range[0] - if diam_range[1] < 100: - filters["diameter_max"] = diam_range[1] - - # Pleural distance - st.subheader("Pleural distance") - pleural = st.slider("Pleural distance (mm)", 0.0, 80.0, (0.0, 80.0), step=1.0) - if pleural[0] > 0: - filters["pleural_distance_min"] = pleural[0] - if pleural[1] < 80: - filters["pleural_distance_max"] = pleural[1] - - # Population type - pop = st.selectbox("Population type", ["Any", "screening", "diagnostic"]) - if pop != "Any": - filters["population_type"] = pop - - # Label source - ls = st.selectbox("Label source", ["Any", "histopathology", "radiology"]) - if ls != "Any": - filters["label_source"] = ls - - # Limit - filters["limit"] = st.number_input("Max results", 10, 5000, 200, step=50) - - # Sort - sort_col = st.selectbox( - "Sort by", - [ - "None", - "nodule_mean_diam_mm", - "pleural_distance_mm", - "reinsertion_lobe_cc_pct", - "dataset", - "lobe_name", - ], - ) - if sort_col != "None": - filters["sort_by"] = sort_col - filters["sort_ascending"] = st.checkbox("Ascending", value=True) - - return filters - - -def _build_similarity_sidebar() -> dict: - """Build the similarity query sidebar.""" - params: dict = {} - params["annotation_id"] = st.text_input( - "Reference annotation_id", placeholder="e.g. DLCS24_n0001" - ) - params["k"] = st.slider("Top-K", 1, 100, 10) - params["exclude_same_patient"] = st.checkbox("Exclude same patient", value=True) - - label_choice = st.selectbox("Label filter", ["Any", "Malignant (1)", "Benign (0)"]) - if label_choice == "Malignant (1)": - params["label"] = 1 - elif label_choice == "Benign (0)": - params["label"] = 0 - - return params - - -def _build_matcher_sidebar(af: dict) -> dict: - """Build the reinsertion matcher sidebar.""" - params: dict = {} - lobe_options = af.get("lobes", []) - params["lobe"] = st.selectbox("Target lobe", lobe_options) - params["k"] = st.slider("Top-K", 1, 100, 10) - - params["lobe_cc_pct"] = st.slider("Lobe CC %", 0.0, 100.0, 50.0, step=1.0) - params["pleural_dist_mm"] = st.number_input("Pleural dist (mm)", 0.0, 100.0, 15.0, step=1.0) - params["diameter_mm"] = st.number_input("Target diameter (mm)", 1.0, 60.0, 10.0, step=0.5) - - label_choice = st.selectbox("Label", ["Any", "Malignant (1)", "Benign (0)"]) - if label_choice == "Malignant (1)": - params["label"] = 1 - elif label_choice == "Benign (0)": - params["label"] = 0 - - return params - - -# --------------------------------------------------------------------------- -# Main content renderers -# --------------------------------------------------------------------------- - - -def _render_search(filters: dict): - """Render faceted search results.""" - if st.sidebar.button("Search", type="primary"): - with st.spinner("Searching …"): - data = _search(filters) - st.session_state["search_data"] = data - - # Render from session_state so the page survives widget interactions - data = st.session_state.get("search_data") - if data is None: - st.info("Configure filters in the sidebar and click **Search**.") - return - - total = data["total_matching"] - results = data["results"] - facets = data.get("facet_counts", {}) - - st.metric("Total matching", f"{total:,}") - - # Facet counts in expander - if facets: - with st.expander("Facet counts (full index)"): - for facet_name, counts in facets.items(): - st.write(f"**{facet_name}**") - st.json(counts) - - if results: - df = pd.DataFrame(results) - display_cols = [ - c - for c in [ - "annotation_id", - "dataset", - "label", - "lobe_name", - "lung_side", - "lung_zone", - "central_peripheral", - "nodule_mean_diam_mm", - "pleural_distance_mm", - "reinsertion_lobe", - "reinsertion_nodule_diam_mm", - ] - if c in df.columns - ] - st.dataframe(df[display_cols], use_container_width=True, height=500) - - # Detail viewer - st.subheader("Nodule detail") - selected_id = st.selectbox( - "Select nodule for detail", - df["annotation_id"].tolist() if "annotation_id" in df.columns else [], - key="search_detail_select", - ) - if selected_id: - _render_detail(selected_id) - - # Export - st.subheader("Export") - col1, col2 = st.columns(2) - with col1: - csv_data = df.to_csv(index=False) - st.download_button( - "Download CSV", - csv_data, - file_name="itrialspace_search.csv", - mime="text/csv", - ) - with col2: - json_data = df.to_json(orient="records", indent=2, default_handler=str) - st.download_button( - "Download JSON", - json_data, - file_name="itrialspace_search.json", - mime="application/json", - ) - else: - st.info("No results. Adjust filters and try again.") - - -def _render_similarity(params: dict): - """Render similarity results with CT viewer for similar nodules.""" - aid = params.get("annotation_id", "").strip() - if not aid: - st.info("Enter a reference annotation_id in the sidebar to find similar nodules.") - return - - if st.sidebar.button("Find similar", type="primary"): - with st.spinner("Computing similarity …"): - kwargs = { - k: v for k, v in params.items() if k not in ("annotation_id", "k") and v is not None - } - results = _find_similar(aid, params["k"], **kwargs) - - if results: - st.session_state["sim_results"] = results - st.session_state["sim_ref"] = aid - else: - st.session_state.pop("sim_results", None) - st.warning("No similar nodules found.") - return - - results = st.session_state.get("sim_results") - aid = st.session_state.get("sim_ref", aid) - if not results: - return - - st.subheader(f"Top-{len(results)} similar to {aid}") - df = pd.DataFrame(results) - st.dataframe(df, use_container_width=True) - - # ── Window preset for all CT views in this section - sim_window = st.selectbox( - "CT window (for all views below)", - ["lung", "mediastinum", "soft_tissue", "bone"], - key="sim_ct_window", - ) - - # ── Reference nodule - with st.expander("Reference nodule detail", expanded=True): - _render_detail(aid) - - # ── Similar nodules — CT comparison - st.subheader("Compare similar nodules") - sim_ids = [r["annotation_id"] for r in results if "annotation_id" in r] - if not sim_ids: - return - - selected_sim = st.multiselect( - "Select similar nodules to view", - sim_ids, - default=sim_ids[: min(3, len(sim_ids))], - key="sim_compare_select", - ) - - if selected_sim: - # Show in a grid: up to 3 per row - for row_start in range(0, len(selected_sim), 3): - row_ids = selected_sim[row_start : row_start + 3] - cols = st.columns(len(row_ids)) - for col, sid in zip(cols, row_ids): - with col: - st.markdown(f"**{sid}**") - match = next((r for r in results if r.get("annotation_id") == sid), {}) - dist = match.get("distance", "?") - diam = match.get("nodule_mean_diam_mm", "?") - lobe = match.get("lobe_name", "?") - label = match.get("label", "?") - st.caption(f"dist={dist} | diam={diam}mm | {lobe} | label={label}") - - png = _get_nodule_view_png(sid, axis="axial", window=sim_window, show_mask=True) - if png: - st.image(png, use_container_width=True) - else: - st.warning("CT unavailable") - - -def _render_matcher(params: dict): - """Render reinsertion matcher results.""" - if st.sidebar.button("Find matches", type="primary"): - with st.spinner("Matching …"): - kwargs = {k: v for k, v in params.items() if k not in ("lobe", "k") and v is not None} - results = _find_match(params["lobe"], params["k"], **kwargs) - st.session_state["matcher_results"] = results - st.session_state["matcher_params"] = {"k": params["k"], "lobe": params["lobe"]} - - results = st.session_state.get("matcher_results") - mp = st.session_state.get("matcher_params", {}) - if not results: - st.info("Configure parameters in the sidebar and click **Find matches**.") - return - - st.subheader(f"Top-{mp.get('k', '?')} matches for {mp.get('lobe', '?')}") - df = pd.DataFrame(results) - st.dataframe(df, use_container_width=True) - - -def _render_detail(annotation_id: str): - """Render full detail panel for a nodule with CT viewer.""" - try: - detail = _get_nodule_detail(annotation_id) - except Exception as e: - st.error(f"Could not load detail: {e}") - return - - # If detail is a dict with nested 'detail', flatten - info = detail.get("detail", detail) if isinstance(detail, dict) else detail - paths = detail.get("_paths", detail.get("paths", {})) - - # ── CT Viewer — Axial slice at nodule centre ───────────────────────── - ct_abs = paths.get("ct_path", "") - - if ct_abs: - wcol1, wcol2 = st.columns([1, 1]) - with wcol1: - view_window = st.selectbox( - "Window preset", - ["lung", "mediastinum", "soft_tissue", "bone"], - key=f"window_{annotation_id}", - ) - with wcol2: - show_mask = st.checkbox("Show nodule mask", value=True, key=f"mask_{annotation_id}") - - png = _get_nodule_view_png( - annotation_id, axis="axial", window=view_window, show_mask=show_mask - ) - - # Volume info badge - vol_info = _get_volume_info(ct_abs) - if vol_info: - s = vol_info["shape"] - sp = vol_info["spacing_mm"] - st.caption( - f"Volume: {s[0]}×{s[1]}×{s[2]} | " - f"Spacing: {sp[0]:.2f}×{sp[1]:.2f}×{sp[2]:.2f} mm | " - f"Centre: ({info.get('coordX','?')}, {info.get('coordY','?')}, {info.get('coordZ','?')})" - ) - - if png: - st.image(png, caption=f"Axial — {view_window} window", use_container_width=True) - else: - st.warning("CT file not accessible from this node. " f"Expected: `{ct_abs}`") - else: - st.info("No CT path resolved for this nodule.") - - # ── Metadata tables ────────────────────────────────────────────────── - st.subheader("Nodule Metadata") - col1, col2 = st.columns([2, 1]) - with col1: - core_keys = [ - "annotation_id", - "dataset", - "patient_id", - "label", - "lobe_name", - "lung_side", - "lung_zone", - "central_peripheral", - "nodule_mean_diam_mm", - "nodule_vol_mm3", - "pleural_distance_mm", - "airway_distance_mm", - "cranio_caudal_pct", - "mediolateral_pct", - "anteroposterior_pct", - "coordX", - "coordY", - "coordZ", - ] - rows = [(k, info.get(k, "")) for k in core_keys if k in info] - st.table(pd.DataFrame(rows, columns=["Field", "Value"])) - - with col2: - rkeys = [k for k in info if str(k).startswith("reinsertion_")] - if rkeys: - st.write("**Reinsertion coordinates**") - rrows = [(k, info[k]) for k in rkeys] - st.table(pd.DataFrame(rrows, columns=["Field", "Value"])) - - # ── File paths ──────────────────────────────────────────────────────── - if paths: - with st.expander("File paths"): - for k, v in paths.items(): - import os - - exists = os.path.isfile(str(v)) if v else False - icon = "✅" if exists else "❌" - st.text(f"{icon} {k}: {v}") - - -# --------------------------------------------------------------------------- -# Entry point -# --------------------------------------------------------------------------- - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/cli.py b/itrialspace/src/itrialspace/cli.py deleted file mode 100644 index 2969088d01243d20f9df7fd183e48bfdb217f923..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/cli.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Umbrella command-line interface for iTrialSpace (``its``). - -Lightweight entry point over the core nodule index. Component-specific commands have -their own console scripts (``its-insert``, ``its-trials``, ``its-nodulemap``, -``its-retriever``). -""" - -from __future__ import annotations - -import argparse -import sys - -from itrialspace import __version__ -from itrialspace.config import settings - - -def _cmd_config(_args: argparse.Namespace) -> int: - """Print resolved paths so users can verify their environment.""" - print("iTrialSpace resolved configuration:") - print(f" repo_root {settings.repo_root()}") - print(f" data_dir {settings.data_dir()}") - print(f" output_dir {settings.output_dir()}") - print(f" configs_dir {settings.configs_dir()}") - print(f" nodulemap_artifacts {settings.nodulemap_artifacts_dir()}") - try: - ds = settings.find_config("datasets.yaml") - print(f" datasets config {ds}") - except FileNotFoundError as exc: - print(f" datasets config (not found: {exc})") - return 0 - - -def _load_index(): - from itrialspace import DatasetRegistry, NoduleIndex - - registry = DatasetRegistry.from_yaml() - if len(registry) == 0: - print( - "No datasets found. Set ITRIALSPACE_DATA_DIR (see `its config`) and ensure " - "profile CSVs exist; see docs/data.md.", - file=sys.stderr, - ) - raise SystemExit(2) - return NoduleIndex.from_registry(registry) - - -def _cmd_stats(_args: argparse.Namespace) -> int: - idx = _load_index() - print(f"Loaded {len(idx)} nodules across {len(idx.datasets)} datasets.\n") - print(idx.stats().to_string()) - return 0 - - -def _cmd_info(_args: argparse.Namespace) -> int: - from itrialspace import DatasetRegistry - - registry = DatasetRegistry.from_yaml() - print(repr(registry)) - return 0 - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="its", description="iTrialSpace command-line interface") - parser.add_argument("--version", action="version", version=f"iTrialSpace {__version__}") - sub = parser.add_subparsers(dest="command") - - p_config = sub.add_parser("config", help="show resolved paths / environment") - p_config.set_defaults(func=_cmd_config) - - p_info = sub.add_parser("info", help="list configured datasets") - p_info.set_defaults(func=_cmd_info) - - p_index = sub.add_parser("index", help="nodule index operations") - index_sub = p_index.add_subparsers(dest="index_command") - p_stats = index_sub.add_parser("stats", help="build the index and print summary stats") - p_stats.set_defaults(func=_cmd_stats) - - return parser - - -def main(argv: list[str] | None = None) -> int: - parser = build_parser() - args = parser.parse_args(argv) - func = getattr(args, "func", None) - if func is None: - parser.print_help() - return 0 - return func(args) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/itrialspace/src/itrialspace/config/__init__.py b/itrialspace/src/itrialspace/config/__init__.py deleted file mode 100644 index e349ea733a48e37f312f868548f8ed2e3fde21af..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/config/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Configuration and portable path resolution for iTrialSpace.""" - -from itrialspace.config.settings import ( - configs_dir, - data_dir, - expand, - expand_tree, - find_config, - load_yaml, - output_dir, - repo_root, -) - -__all__ = [ - "repo_root", - "data_dir", - "output_dir", - "configs_dir", - "expand", - "expand_tree", - "load_yaml", - "find_config", -] diff --git a/itrialspace/src/itrialspace/config/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/config/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 7a17ea1edadc839206cddd122d38e3c200056256..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/config/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/config/__pycache__/settings.cpython-310.pyc b/itrialspace/src/itrialspace/config/__pycache__/settings.cpython-310.pyc deleted file mode 100644 index 35cd30aba7cf5ce885c9c2357911815f3fe42444..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/config/__pycache__/settings.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/config/datasets.yaml b/itrialspace/src/itrialspace/config/datasets.yaml deleted file mode 100644 index 65993e4fa2f62e34235a19f4235c13bb68d05437..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/config/datasets.yaml +++ /dev/null @@ -1,35 +0,0 @@ -# iTrialSpace Dataset Registry — maps dataset name → nodule-profile CSV path. -# -# Copy to `configs/datasets.yaml` and adjust if your layout differs. Paths use the -# ${ITRIALSPACE_DATA_DIR} placeholder, which is expanded by itrialspace.config.settings -# (default: ~/.itrialspace/data). You usually only need to set ITRIALSPACE_DATA_DIR in .env. - -datasets: - - DLCS24: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/DLCS24_nodule_profiles.csv - notes: "Binary label. Lung-RADS scores, smoking, age/sex. 2,487 nodules." - - LUNA25: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA25_nodule_profiles.csv - notes: "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening." - - LUNA16: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA16_nodule_profiles.csv - notes: "No malignancy label. Use for reinsertion/anatomy analysis only." - - LUNGx: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNGx_nodule_profiles.csv - notes: "Benchmark challenge. 49.4% malignant. Has CADe detection scores." - - LNDbv4: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LNDbv4_nodule_profiles.csv - notes: "Malignancy is continuous float (radiologist avg 1-5). Threshold 3.0 used." - - NSCLCR: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/NSCLCR_nodule_profiles.csv - notes: "All malignant (100%). Large tumours (median 52mm). Has staging/survival." - - IMDCT: - csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/IMDCT_nodule_profiles.csv - notes: "Label is string benign/cancer. Has nodule type, PET, spiculation." diff --git a/itrialspace/src/itrialspace/config/settings.py b/itrialspace/src/itrialspace/config/settings.py deleted file mode 100644 index 8270cfc9faa078614318c4acb04e11cb623ecf8e..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/config/settings.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Central, machine-portable settings and path resolution for iTrialSpace. - -This module is the **single source of truth** for every filesystem path the project -needs. Nothing else in the codebase should hardcode an absolute path. All locations -are derived from environment variables (with sensible defaults), so the same code runs -unchanged on a laptop, a workstation, or an HPC cluster. - -Environment variables (see ``.env.example``): - - ITRIALSPACE_DATA_DIR base directory of the unified data layout - (default: ~/.itrialspace/data) - ITRIALSPACE_ROOT repo root (auto-detected from this file when editable) - ITRIALSPACE_OUTPUT_DIR where generated artifacts go (default: ITRIALSPACE_DATA_DIR) - -YAML interpolation: - - Any string value in a config YAML may reference these variables with ``${VAR}`` - syntax, e.g. ``base_dir: ${ITRIALSPACE_DATA_DIR}``. Use :func:`load_yaml` (or - :func:`expand`) so the placeholders resolve — falling back to the documented - defaults even when the variable is not exported. -""" - -from __future__ import annotations - -import os -from functools import lru_cache -from pathlib import Path -from string import Template -from typing import Any, Optional - -_ENV_DATA = "ITRIALSPACE_DATA_DIR" -_ENV_ROOT = "ITRIALSPACE_ROOT" -_ENV_OUTPUT = "ITRIALSPACE_OUTPUT_DIR" -_ENV_NODULEMAP_ARTIFACTS = "NODULEMAP_ARTIFACTS" - - -@lru_cache(maxsize=1) -def repo_root() -> Path: - """Best-effort repo root. - - Prefers ``$ITRIALSPACE_ROOT``; otherwise walks up from this file looking for a - repo marker (``pyproject.toml``). Falls back to the current working directory - when installed as a non-editable wheel. - """ - env = os.environ.get(_ENV_ROOT) - if env: - return Path(env).expanduser().resolve() - here = Path(__file__).resolve() - for parent in here.parents: - if (parent / "pyproject.toml").is_file(): - return parent - return Path.cwd() - - -@lru_cache(maxsize=1) -def data_dir() -> Path: - """Base directory of the unified data layout (raw_ct/, masks/, profiles/, ...).""" - env = os.environ.get(_ENV_DATA) - base = Path(env).expanduser() if env else Path.home() / ".itrialspace" / "data" - return base - - -@lru_cache(maxsize=1) -def output_dir() -> Path: - """Where generated artifacts (manifests, masks, CTs, reports) are written.""" - env = os.environ.get(_ENV_OUTPUT) - return Path(env).expanduser() if env else data_dir() - - -def configs_dir() -> Path: - """Top-level ``configs/`` directory holding user/example configs.""" - return repo_root() / "configs" - - -def nodulemap_artifacts_dir() -> Path: - """Directory holding NoduleMap build artifacts (embeddings, edges, metadata). - - Set ``$NODULEMAP_ARTIFACTS`` to read pre-built artifacts (or to choose where new - ones are written). Default: ``$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts``. - """ - env = os.environ.get(_ENV_NODULEMAP_ARTIFACTS) - return Path(env).expanduser() if env else output_dir() / "nodulemap_artifacts" - - -def _defaults() -> dict[str, str]: - """Mapping used for ``${VAR}`` expansion: resolved defaults + live environment.""" - base = { - _ENV_DATA: str(data_dir()), - _ENV_ROOT: str(repo_root()), - _ENV_OUTPUT: str(output_dir()), - _ENV_NODULEMAP_ARTIFACTS: str(nodulemap_artifacts_dir()), - } - base.update(os.environ) # real environment wins - return base - - -def expand(value: Any) -> Any: - """Expand ``${VAR}`` placeholders and ``~`` in a string. - - Non-strings are returned unchanged. Unknown variables are left intact (via - ``safe_substitute``) so misconfigurations are visible rather than silently empty. - """ - if not isinstance(value, str): - return value - substituted = Template(value).safe_substitute(_defaults()) - return os.path.expanduser(substituted) - - -def expand_tree(obj: Any) -> Any: - """Recursively expand ``${VAR}`` in all string leaves of a dict/list structure.""" - if isinstance(obj, dict): - return {k: expand_tree(v) for k, v in obj.items()} - if isinstance(obj, list): - return [expand_tree(v) for v in obj] - return expand(obj) - - -def load_yaml(path: str | Path) -> dict: - """Load a YAML file and expand ``${VAR}`` placeholders throughout.""" - try: - import yaml - except ImportError as exc: # pragma: no cover - raise ImportError("PyYAML required: pip install pyyaml") from exc - with open(path) as f: - raw = yaml.safe_load(f) or {} - return expand_tree(raw) - - -def find_config(name: str, package_default: Optional[str | Path] = None) -> Path: - """Resolve a config file name to a concrete path. - - Resolution order: - 1. ``$ITRIALSPACE__CONFIG`` env override (NAME upper-cased, no extension) - 2. top-level ``configs/`` (user copy) - 3. top-level ``configs/.example.`` (shipped example) - 4. ``package_default`` (config bundled inside the package), if provided - - Raises ``FileNotFoundError`` if nothing is found. - """ - stem = Path(name).stem - ext = Path(name).suffix or ".yaml" - - env_key = f"ITRIALSPACE_{stem.upper()}_CONFIG" - if os.environ.get(env_key): - return Path(os.environ[env_key]).expanduser() - - cfg = configs_dir() - candidates = [cfg / name, cfg / f"{stem}.example{ext}"] - for cand in candidates: - if cand.is_file(): - return cand - - if package_default is not None and Path(package_default).is_file(): - return Path(package_default) - - raise FileNotFoundError( - f"Config '{name}' not found. Looked for: " - + ", ".join(str(c) for c in candidates) - + (f", {package_default}" if package_default else "") - + f". Set {env_key} or create configs/{name}." - ) - - -__all__ = [ - "repo_root", - "data_dir", - "output_dir", - "configs_dir", - "nodulemap_artifacts_dir", - "expand", - "expand_tree", - "load_yaml", - "find_config", -] diff --git a/itrialspace/src/itrialspace/core/__init__.py b/itrialspace/src/itrialspace/core/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/core/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 5286290bbb9d0ece2e037bbccb145722ef15b250..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/core/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/core/__pycache__/label.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/label.cpython-310.pyc deleted file mode 100644 index 613c0aca82682b80ca1d72a44657eb285c29119d..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/core/__pycache__/label.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/core/__pycache__/profile.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/profile.cpython-310.pyc deleted file mode 100644 index cc72925d60a2d345236af892489da1d1e588482b..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/core/__pycache__/profile.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/core/__pycache__/schema.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/schema.cpython-310.pyc deleted file mode 100644 index da9e2ee48ec4d965498a80e7afd30ba378accdc4..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/core/__pycache__/schema.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/core/label.py b/itrialspace/src/itrialspace/core/label.py deleted file mode 100644 index 0c8df7b43571b9e56c12123abf38429940e3acbe..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/core/label.py +++ /dev/null @@ -1,99 +0,0 @@ -""" -LabelNormaliser — maps each dataset's native label column(s) -to a unified int | None value: - 0 = benign - 1 = malignant - None = unknown / unlabelled -""" - -from __future__ import annotations - -from typing import Optional - -import pandas as pd - - -class LabelNormaliser: - """ - Per-dataset rules for producing a unified binary label. - - Usage: - normaliser = LabelNormaliser("DLCS24") - label = normaliser.normalise(row) # row is a pandas Series - """ - - # Maps dataset → callable(row) → int | None - _RULES: dict[str, callable] = {} - - def __init__(self, dataset: str): - if dataset not in self._RULES: - raise ValueError(f"Unknown dataset '{dataset}'. " f"Known: {list(self._RULES.keys())}") - self.dataset = dataset - self._fn = self._RULES[dataset] - - def normalise(self, row: pd.Series) -> Optional[int]: - return self._fn(row) - - def normalise_series(self, df: pd.DataFrame) -> pd.Series: - """Apply to entire DataFrame, return Series of normalised labels.""" - return df.apply(self._fn, axis=1) - - # ── Register all dataset rules ──────────────────────────────────────────── - - @classmethod - def _register(cls): - def _safe_int(v) -> Optional[int]: - try: - return int(v) - except (TypeError, ValueError): - return None - - cls._RULES["DLCS24"] = lambda row: _safe_int(row.get("label")) - - cls._RULES["LUNA25"] = lambda row: _safe_int(row.get("label")) - - cls._RULES["LUNA16"] = lambda row: None # no malignancy label available - - cls._RULES["LUNGx"] = lambda row: _safe_int(row.get("CADx_label")) - - def _lndbv4(row) -> Optional[int]: - v = row.get("Malignancy") - if pd.isna(v): - return None - try: - return 1 if float(v) >= 3.0 else 0 - except (TypeError, ValueError): - return None - - cls._RULES["LNDbv4"] = _lndbv4 - - cls._RULES["NSCLCR"] = lambda row: 1 # 100% cancer cohort - - def _imdct(row) -> Optional[int]: - v = row.get("CADx_label") - if pd.isna(v): - return None - s = str(v).strip().lower() - if s == "cancer": - return 1 - if s == "benign": - return 0 - return None - - cls._RULES["IMDCT"] = _imdct - - @classmethod - def available_datasets(cls) -> list[str]: - return list(cls._RULES.keys()) - - -# Register rules at import time -LabelNormaliser._register() - - -# ── Standalone helper ───────────────────────────────────────────────────────── - - -def normalise_label(row: pd.Series, dataset: str) -> Optional[int]: - """Convenience function — normalise a single row.""" - return LabelNormaliser(dataset).normalise(row) diff --git a/itrialspace/src/itrialspace/core/profile.py b/itrialspace/src/itrialspace/core/profile.py deleted file mode 100644 index c20cf0fb4e3b4f9638fd5f290a0cfe84b82ee49d..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/core/profile.py +++ /dev/null @@ -1,150 +0,0 @@ -""" -NoduleProfile — the unified representation of a single lung nodule -across all 8 iTrialSpace datasets. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Optional - - -@dataclass -class NoduleProfile: - """ - A single nodule record, normalised from any iTrialSpace dataset CSV. - - The 53 core pipeline fields are typed attributes. - Dataset-specific columns (Lung-RADS, staging, pack-years, etc.) - live in `meta` and are also retained in the NoduleIndex DataFrame. - """ - - # ── Identity ────────────────────────────────────────────────────────────── - annotation_id: str # AnnotationID (universal across datasets) - patient_id: str # normalised from 8 different source col names - dataset: str # 'DLCS24' | 'LUNA25' | 'LUNA16' | ... - ct_path: str - - # ── Label ───────────────────────────────────────────────────────────────── - label: Optional[int] = None # 0=benign, 1=malignant, None=unknown - - # ── Bounding box ────────────────────────────────────────────────────────── - coord_x: float = 0.0 - coord_y: float = 0.0 - coord_z: float = 0.0 - w: float = 0.0 - h: float = 0.0 - d: float = 0.0 - - # ── Morphology ──────────────────────────────────────────────────────────── - nodule_mean_diam_mm: float = 0.0 - nodule_vol_mm3: Optional[float] = None - - # ── Anatomy ─────────────────────────────────────────────────────────────── - lobe_name: str = "unknown" - lung_side: str = "unknown" - lung_zone: str = "unknown" - organ_label_id: int = 0 - organ_label_name: str = "" - central_peripheral: str = "unknown" - nearby_organs_10mm: Optional[str] = None - - # ── Position — whole-lung % ─────────────────────────────────────────────── - cranio_caudal_pct: Optional[float] = None - mediolateral_pct: Optional[float] = None - anteroposterior_pct: Optional[float] = None - - # ── Position — lobe % ──────────────────────────────────────────────────── - # NOTE: lobe_cc_pct is clean (use freely). - # lobe_ml_pct and lobe_ap_pct have known outliers in DLCS24 - # due to a normalisation bug — check dataset_flags before using. - lobe_cc_pct: Optional[float] = None - lobe_ml_pct: Optional[float] = None - lobe_ap_pct: Optional[float] = None - - # ── Distances (mm) ──────────────────────────────────────────────────────── - dist_to_trachea_mm: Optional[float] = None - dist_to_aorta_mm: Optional[float] = None - dist_to_heart_mm: Optional[float] = None - dist_to_esophagus_mm: Optional[float] = None - dist_to_pulmonary_vein_mm: Optional[float] = None - dist_to_superior_vena_cava_mm: Optional[float] = None - pleural_distance_mm: Optional[float] = None - airway_distance_mm: Optional[float] = None - - # ── Inter-nodule ────────────────────────────────────────────────────────── - n_nodules_in_patient: int = 1 - nearest_nodule_id: Optional[str] = None - nearest_nodule_dist_mm: Optional[float] = None - nearest_dx_mm: Optional[float] = None - nearest_dy_mm: Optional[float] = None - nearest_dz_mm: Optional[float] = None - all_nodule_ids: Optional[str] = None - all_nodule_dists_mm: Optional[str] = None - ipsilateral: Optional[bool] = None - nearest_same_lobe: Optional[bool] = None - bilateral_distribution: bool = False - - # ── Reinsertion — 100% complete, primary query / match index ───────────── - reinsertion_lobe: str = "unknown" - reinsertion_lung_side: str = "unknown" - reinsertion_lung_zone: str = "unknown" - reinsertion_lobe_cc_pct: float = 0.0 - reinsertion_lobe_ml_pct: float = 0.0 - reinsertion_lobe_ap_pct: float = 0.0 - reinsertion_lung_cc_pct: float = 0.0 - reinsertion_lung_ml_pct: float = 0.0 - reinsertion_lung_ap_pct: float = 0.0 - reinsertion_pleural_dist_mm: Optional[float] = None - reinsertion_airway_dist_mm: Optional[float] = None - reinsertion_nodule_diam_mm: float = 0.0 - - # ── Dataset-specific metadata ───────────────────────────────────────────── - # All extra columns from the source CSV land here. - # Also retained in NoduleIndex DataFrame under original column names. - # - # Examples by dataset: - # DLCS24: 'Lung-RADS score', 'Smoking Status', 'Age', 'Sex', 'annotation_group' - # LUNA25: 'LesionID', 'NoduleID', 'StudyDate', 'Split', 'age', 'gender' - # LNDbv4: 'Malignancy' (raw float), 'Texture', 'Spiculation', 'NumRadsFound' - # NSCLCR: 'overall.stage', 'histology', 'survival.time', 'deadstatus.event' - # IMDCT: 'nodules_types', 'Spiculation', 'Emphysema', 'PET', 'uptake_class' - # LUNGx: 'Final Diagnosis', 'ANod_score', 'meta_prob' - meta: dict = field(default_factory=dict) - - # ── Convenience properties ──────────────────────────────────────────────── - @property - def is_malignant(self) -> Optional[bool]: - if self.label is None: - return None - return bool(self.label) - - @property - def is_upper_lobe(self) -> bool: - return "upper" in self.lobe_name - - @property - def is_peripheral(self) -> bool: - return self.central_peripheral == "peripheral" - - @property - def size_bucket(self) -> str: - d = self.nodule_mean_diam_mm - if d < 5: - return "<5mm" - if d < 10: - return "5-10mm" - if d < 15: - return "10-15mm" - if d < 20: - return "15-20mm" - if d < 30: - return "20-30mm" - return ">30mm" - - def __repr__(self) -> str: - lbl = {0: "benign", 1: "malignant", None: "unlabelled"}[self.label] - return ( - f"NoduleProfile({self.dataset} | {self.annotation_id} | " - f"{self.nodule_mean_diam_mm:.1f}mm | {self.lobe_name} | {lbl})" - ) diff --git a/itrialspace/src/itrialspace/core/schema.py b/itrialspace/src/itrialspace/core/schema.py deleted file mode 100644 index 4650f8d77c6d085b39fc410c8eff89292fba5afe..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/core/schema.py +++ /dev/null @@ -1,198 +0,0 @@ -""" -Schema constants — the 53 columns present in every nodule profile CSV, -plus enums for categorical values. -""" - -from enum import Enum - -# ── Core columns present in ALL 7 datasets ──────────────────────────────────── -CORE_COLS = [ - # identity - "ct_path", - # bounding box - "coordX", - "coordY", - "coordZ", - "w", - "h", - "d", - # morphology - "nodule_mean_diam_mm", - "nodule_vol_mm3", - # anatomy - "organ_label_id", - "organ_label_name", - "nearby_organs_10mm", - "lung_side", - "lobe_name", - "lung_zone", - "central_peripheral", - # position – whole lung % - "cranio_caudal_pct", - "mediolateral_pct", - "anteroposterior_pct", - # position – lobe % - "lobe_cc_pct", - "lobe_ml_pct", - "lobe_ap_pct", - # distances mm - "dist_to_trachea_mm", - "dist_to_aorta_mm", - "dist_to_heart_mm", - "dist_to_esophagus_mm", - "dist_to_pulmonary_vein_mm", - "dist_to_superior_vena_cava_mm", - "pleural_distance_mm", - "airway_distance_mm", - # inter-nodule - "n_nodules_in_patient", - "nearest_nodule_id", - "nearest_nodule_dist_mm", - "nearest_dx_mm", - "nearest_dy_mm", - "nearest_dz_mm", - "all_nodule_ids", - "all_nodule_dists_mm", - "ipsilateral", - "nearest_same_lobe", - "bilateral_distribution", - # reinsertion (100% complete across all datasets) - "reinsertion_lobe", - "reinsertion_lung_side", - "reinsertion_lung_zone", - "reinsertion_lobe_cc_pct", - "reinsertion_lobe_ml_pct", - "reinsertion_lobe_ap_pct", - "reinsertion_lung_cc_pct", - "reinsertion_lung_ml_pct", - "reinsertion_lung_ap_pct", - "reinsertion_pleural_dist_mm", - "reinsertion_airway_dist_mm", - "reinsertion_nodule_diam_mm", -] - -# Pipeline-computed columns that map to NoduleProfile typed fields -PROFILING_COLS = [c for c in CORE_COLS if c != "ct_path"] - -# Reinsertion subset — 100% complete, primary query index -REINSERTION_COLS = [c for c in CORE_COLS if c.startswith("reinsertion_")] - -# ── Categorical values ───────────────────────────────────────────────────────── -LOBE_NAMES = [ - "right_lung_upper_lobe", - "right_lung_middle_lobe", - "right_lung_lower_lobe", - "left_lung_upper_lobe", - "left_lung_lower_lobe", -] -LOBE_NAMES_WITH_BG = LOBE_NAMES + ["background", "unknown"] - -ZONE_NAMES = ["upper_zone", "middle_zone", "lower_zone"] -SIDE_NAMES = ["right", "left", "unknown"] -CP_VALUES = ["central", "peripheral", "unknown"] - -DATASET_NAMES = ["DLCS24", "LUNA25", "LUNA16", "LUNGx", "LNDbv4", "NSCLCR", "IMDCT"] - - -class Lobe(str, Enum): - RIGHT_UPPER = "right_lung_upper_lobe" - RIGHT_MIDDLE = "right_lung_middle_lobe" - RIGHT_LOWER = "right_lung_lower_lobe" - LEFT_UPPER = "left_lung_upper_lobe" - LEFT_LOWER = "left_lung_lower_lobe" - BACKGROUND = "background" - UNKNOWN = "unknown" - - -class Zone(str, Enum): - UPPER = "upper_zone" - MIDDLE = "middle_zone" - LOWER = "lower_zone" - - -class Side(str, Enum): - RIGHT = "right" - LEFT = "left" - UNKNOWN = "unknown" - - -class CentralPeripheral(str, Enum): - CENTRAL = "central" - PERIPHERAL = "peripheral" - UNKNOWN = "unknown" - - -# ── Known data quality flags per dataset ────────────────────────────────────── -DATASET_FLAGS: dict[str, dict] = { - "DLCS24": { - "lobe_ml_pct_unreliable": True, # 93% outside [0,100] — pipeline normalisation bug - "lobe_ap_pct_unreliable": True, # 50.7% outside [0,100] - "lobe_cc_pct_unreliable": False, - "has_label": True, - "all_malignant": False, - "all_unlabelled": False, - "label_is_soft": False, - "notes": "Binary label. Includes Lung-RADS scores, smoking, age/sex.", - }, - "LUNA25": { - "lobe_ml_pct_unreliable": False, - "lobe_ap_pct_unreliable": False, - "lobe_cc_pct_unreliable": False, - "has_label": True, - "all_malignant": False, - "all_unlabelled": False, - "label_is_soft": False, - "notes": "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening.", - }, - "LUNA16": { - "lobe_ml_pct_unreliable": False, - "lobe_ap_pct_unreliable": False, - "lobe_cc_pct_unreliable": False, - "has_label": False, - "all_malignant": False, - "all_unlabelled": True, - "label_is_soft": False, - "notes": "No malignancy label. Use for reinsertion/anatomy only.", - }, - "LUNGx": { - "lobe_ml_pct_unreliable": False, - "lobe_ap_pct_unreliable": False, - "lobe_cc_pct_unreliable": False, - "has_label": True, - "all_malignant": False, - "all_unlabelled": False, - "label_is_soft": False, - "notes": "Benchmark challenge dataset. CADx_label binary. 49.4% malignant.", - }, - "LNDbv4": { - "lobe_ml_pct_unreliable": False, - "lobe_ap_pct_unreliable": False, - "lobe_cc_pct_unreliable": False, - "has_label": True, - "all_malignant": False, - "all_unlabelled": False, - "label_is_soft": True, # continuous 1–5 radiologist average - "label_threshold": 3.0, - "notes": "Malignancy is float avg of radiologist ratings (1–5). Threshold >=3 used.", - }, - "NSCLCR": { - "lobe_ml_pct_unreliable": False, - "lobe_ap_pct_unreliable": False, - "lobe_cc_pct_unreliable": False, - "has_label": True, - "all_malignant": True, # 100% cancer cohort - "all_unlabelled": False, - "label_is_soft": False, - "notes": "All malignant (lung cancer patients). Large tumours (median 52mm). Has staging/survival.", - }, - "IMDCT": { - "lobe_ml_pct_unreliable": False, - "lobe_ap_pct_unreliable": False, - "lobe_cc_pct_unreliable": False, - "has_label": True, - "all_malignant": False, - "all_unlabelled": False, - "label_is_soft": False, - "notes": "Label is string 'benign'/'cancer'. Has nodule type, PET, spiculation.", - }, -} diff --git a/itrialspace/src/itrialspace/index/__init__.py b/itrialspace/src/itrialspace/index/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/index/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/index/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 0a1ffb5fc8d2eacb05539a2ae4c2584e36561900..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/index/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/index/__pycache__/nodule_index.cpython-310.pyc b/itrialspace/src/itrialspace/index/__pycache__/nodule_index.cpython-310.pyc deleted file mode 100644 index 810b46aff514ac387e8c6f45d00c03e97b8d0658..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/index/__pycache__/nodule_index.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/index/nodule_index.py b/itrialspace/src/itrialspace/index/nodule_index.py deleted file mode 100644 index 29b85aaa48e15535ce5ea630e05243f93d34cbe7..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/index/nodule_index.py +++ /dev/null @@ -1,197 +0,0 @@ -""" -NoduleIndex — the central object. -Loads all datasets, merges into a single DataFrame, exposes query/stats API. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -import pandas as pd - -from itrialspace.core.schema import DATASET_FLAGS -from itrialspace.io.loader import DatasetLoader -from itrialspace.io.registry import DatasetRegistry - -if TYPE_CHECKING: - from itrialspace.query.query_api import NoduleQuery - - -class NoduleIndex: - """ - A merged, queryable index over all iTrialSpace nodule profile datasets. - - The backing store is a single pandas DataFrame containing the 53 core - pipeline columns plus `label`, `patient_id`, `annotation_id`, `dataset`, - and all dataset-specific extra columns (NaN where not applicable). - - Usage: - # From a registry (recommended) - registry = DatasetRegistry.from_directory("/data/profiles/") - idx = NoduleIndex.from_registry(registry) - - # From a single CSV - idx = NoduleIndex.from_csv("DLCS24", "/data/DLCS24_nodule_profiles.csv") - - # From a pre-built DataFrame - idx = NoduleIndex(df) - - # Query - results = idx.query().label(1).lobe("right_lung_upper_lobe").fetch() - - # Stats - print(idx.stats()) - """ - - def __init__(self, df: pd.DataFrame): - self._df = df.copy().reset_index(drop=True) - - @classmethod - def from_csv(cls, dataset: str, csv_path: str) -> "NoduleIndex": - """Load a single dataset CSV.""" - df = DatasetLoader.load_to_dataframe(dataset, csv_path) - return cls(df) - - @classmethod - def from_registry(cls, registry: DatasetRegistry, verbose: bool = True) -> "NoduleIndex": - """Load all registered datasets and merge into one index.""" - frames = [] - for dataset, path in registry.items(): - if verbose: - print(f" Loading {dataset:<10s} ← {path}") - try: - df = DatasetLoader.load_to_dataframe(dataset, path) - frames.append(df) - if verbose: - mal = df["label"].sum() if df["label"].notna().any() else "?" - print(f" {len(df):>5d} rows | label={mal}") - except Exception as e: - print(f" ⚠ {dataset}: failed ({e})") - - if not frames: - raise RuntimeError("No datasets loaded.") - - merged = pd.concat(frames, axis=0, ignore_index=True, sort=False) - if verbose: - print(f"\n Total: {len(merged):,} nodules across {len(frames)} datasets") - return cls(merged) - - @classmethod - def from_dict(cls, mapping: dict[str, str], verbose: bool = True) -> "NoduleIndex": - """Shortcut: load from dict {'DLCS24': '/path/...', ...}""" - registry = DatasetRegistry.from_dict(mapping) - return cls.from_registry(registry, verbose=verbose) - - # ── Core properties ──────────────────────────────────────────────────────── - - @property - def df(self) -> pd.DataFrame: - """Access the underlying DataFrame directly.""" - return self._df - - @property - def datasets(self) -> list[str]: - return sorted(self._df["dataset"].unique().tolist()) - - def __len__(self) -> int: - return len(self._df) - - def __repr__(self) -> str: - n = len(self._df) - ds = ", ".join(self.datasets) - labelled = self._df["label"].notna().sum() - return f"NoduleIndex({n:,} nodules | {ds} | {labelled:,} labelled)" - - # ── Query entry point ────────────────────────────────────────────────────── - - def query(self) -> "NoduleQuery": - from itrialspace.query.query_api import NoduleQuery - - return NoduleQuery(self._df) - - # ── Stats ────────────────────────────────────────────────────────────────── - - def stats(self) -> pd.DataFrame: - """ - Per-dataset summary table: n, malignancy rate, size stats, lobe coverage. - """ - rows = [] - for ds in sorted(self._df["dataset"].unique()): - sub = self._df[self._df["dataset"] == ds] - flags = DATASET_FLAGS.get(ds, {}) - - labelled = sub["label"].notna() - mal_rate = ( - f"{sub.loc[labelled, 'label'].mean() * 100:.1f}%" if labelled.any() else "N/A" - ) - mal_n = int(sub["label"].sum()) if labelled.any() else 0 - - diam = sub["nodule_mean_diam_mm"] - rows.append( - { - "dataset": ds, - "n": len(sub), - "patients": sub["patient_id"].nunique(), - "labelled": int(labelled.sum()), - "malignant": mal_n, - "mal_rate": mal_rate, - "diam_median": round(diam.median(), 1), - "diam_mean": round(diam.mean(), 1), - "diam_max": round(diam.max(), 1), - "all_malignant": flags.get("all_malignant", False), - "all_unlabelled": flags.get("all_unlabelled", False), - "label_is_soft": flags.get("label_is_soft", False), - "notes": flags.get("notes", ""), - } - ) - return pd.DataFrame(rows).set_index("dataset") - - def lobe_stats(self) -> pd.DataFrame: - """Lobe × dataset malignancy rates.""" - sub = self._df[self._df["label"].notna()] - return ( - sub.groupby(["dataset", "lobe_name"])["label"] - .agg(["sum", "count", "mean"]) - .rename(columns={"sum": "malignant", "count": "total", "mean": "rate"}) - .assign(rate=lambda d: (d["rate"] * 100).round(1)) - ) - - def size_stats(self) -> pd.DataFrame: - """Size bucket × dataset malignancy rates.""" - bins = [0, 5, 10, 15, 20, 30, 200] - lbls = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] - df = self._df.copy() - df["size_bucket"] = pd.cut(df["nodule_mean_diam_mm"], bins=bins, labels=lbls) - return ( - df.groupby(["dataset", "size_bucket"])["label"] - .agg(["sum", "count", "mean"]) - .rename(columns={"sum": "malignant", "count": "total", "mean": "rate"}) - .assign(rate=lambda d: (d["rate"] * 100).round(1)) - ) - - # ── Flags ────────────────────────────────────────────────────────────────── - - def dataset_flags(self, dataset: str) -> dict: - """Return known data quality flags for a dataset.""" - flags = DATASET_FLAGS.get(dataset, {}) - if not flags: - return {"warning": f"No flags registered for '{dataset}'"} - return flags - - # ── Convenience filters ─────────────────────────────────────────────────── - - def labelled(self) -> "NoduleIndex": - """Return a new NoduleIndex with only rows that have a label.""" - return NoduleIndex(self._df[self._df["label"].notna()]) - - def malignant(self) -> "NoduleIndex": - """Return only malignant rows.""" - return NoduleIndex(self._df[self._df["label"] == 1]) - - def benign(self) -> "NoduleIndex": - """Return only benign rows.""" - return NoduleIndex(self._df[self._df["label"] == 0]) - - def subset(self, datasets: list[str]) -> "NoduleIndex": - """Return only rows from specified datasets.""" - return NoduleIndex(self._df[self._df["dataset"].isin(datasets)]) diff --git a/itrialspace/src/itrialspace/io/__init__.py b/itrialspace/src/itrialspace/io/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/io/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/io/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 1716442af41174b35d6828acae43619b66abc5c6..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/io/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/io/__pycache__/loader.cpython-310.pyc b/itrialspace/src/itrialspace/io/__pycache__/loader.cpython-310.pyc deleted file mode 100644 index d9a44f29ad2cbe368b3ecbad8f1a997c8d91bffe..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/io/__pycache__/loader.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/io/__pycache__/registry.cpython-310.pyc b/itrialspace/src/itrialspace/io/__pycache__/registry.cpython-310.pyc deleted file mode 100644 index a5eec882ac96590c1139c8780b55ae523aa95798..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/io/__pycache__/registry.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/io/adapters/__init__.py b/itrialspace/src/itrialspace/io/adapters/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/io/adapters/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/io/adapters/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 2388d3fa33c1181823401b60cdc622c47ec0e463..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/io/adapters/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/io/adapters/__pycache__/adapters.cpython-310.pyc b/itrialspace/src/itrialspace/io/adapters/__pycache__/adapters.cpython-310.pyc deleted file mode 100644 index 2005de7d88372e8bc75b1bb7d56f72c3d22ff6bc..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/io/adapters/__pycache__/adapters.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/io/adapters/adapters.py b/itrialspace/src/itrialspace/io/adapters/adapters.py deleted file mode 100644 index 31f65962289786565287f071946ecce84345e3b8..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/io/adapters/adapters.py +++ /dev/null @@ -1,128 +0,0 @@ -""" -Dataset adapters — one class per dataset. - -Each adapter knows: - - which column is the patient_id - - which column is the annotation_id - - which columns are dataset-specific metadata (go into meta{}) - - any special pre-processing needed before loading -""" - -from __future__ import annotations - -from typing import Optional - -import pandas as pd - - -class _BaseAdapter: - dataset: str = "" - patient_id_col: str = "PatientID" - annotation_id_col: Optional[str] = "AnnotationID" - - # Columns that are dataset-specific (go to meta dict, not core fields) - # Computed as: all columns NOT in CORE_COLS and NOT identity cols - _extra_col_cache: Optional[list[str]] = None - - def extra_cols(self, df_columns: list[str]) -> list[str]: - from itrialspace.core.schema import CORE_COLS - - core_set = set(CORE_COLS) | { - "coordX", - "coordY", - "coordZ", - self.patient_id_col, - self.annotation_id_col or "", - "ct_path", - } - return [c for c in df_columns if c not in core_set] - - def get_patient_id(self, row: pd.Series) -> str: - v = row.get(self.patient_id_col) - return str(v) if pd.notna(v) else "unknown" - - def get_annotation_id(self, row: pd.Series) -> str: - if self.annotation_id_col and self.annotation_id_col in row.index: - v = row.get(self.annotation_id_col) - if pd.notna(v): - return str(v) - # fallback: dataset + index - return f"{self.dataset}_unknown" - - def preprocess(self, df: pd.DataFrame) -> pd.DataFrame: - """Hook for dataset-specific pre-processing. Override as needed.""" - return df - - -class DLCS24Adapter(_BaseAdapter): - dataset = "DLCS24" - patient_id_col = "patient-id" - annotation_id_col = "AnnotationID" - - -class LUNA25Adapter(_BaseAdapter): - dataset = "LUNA25" - patient_id_col = "PatientID" - annotation_id_col = "AnnotationID" - - -class LUNA16Adapter(_BaseAdapter): - dataset = "LUNA16" - patient_id_col = "seriesuid" - annotation_id_col = "AnnotationID" - - -class LUNGxAdapter(_BaseAdapter): - dataset = "LUNGx" - patient_id_col = "PatientID" - annotation_id_col = "AnnotationID" - - -class LNDbv4Adapter(_BaseAdapter): - dataset = "LNDbv4" - patient_id_col = "PatientID" - annotation_id_col = "AnnotationID" - - def preprocess(self, df: pd.DataFrame) -> pd.DataFrame: - # Aggregate multi-radiologist rows: group by unique_NoduleID, - # take mean of numeric ratings, keep first for string fields - if "unique_NoduleID" not in df.columns: - return df - return df # loaded as-is; aggregation is optional and caller-driven - - -class NSCLCRAdapter(_BaseAdapter): - dataset = "NSCLCR" - patient_id_col = "PatientID" - annotation_id_col = "AnnotationID" - - -class IMDCTAdapter(_BaseAdapter): - dataset = "IMDCT" - patient_id_col = "PatientID" - annotation_id_col = None # IMDCT has no AnnotationID column - - def get_annotation_id(self, row: pd.Series) -> str: - # Synthesise from PatientID + row index (set by loader) - pid = self.get_patient_id(row) - idx = row.get("_row_index", "0") - return f"IMDCT_{pid}_{idx}" - - -# ── Registry ────────────────────────────────────────────────────────────────── - -ADAPTERS: dict[str, _BaseAdapter] = { - "DLCS24": DLCS24Adapter(), - "LUNA25": LUNA25Adapter(), - "LUNA16": LUNA16Adapter(), - "LUNGx": LUNGxAdapter(), - "LNDbv4": LNDbv4Adapter(), - "NSCLCR": NSCLCRAdapter(), - "IMDCT": IMDCTAdapter(), -} - - -def get_adapter(dataset: str) -> _BaseAdapter: - if dataset not in ADAPTERS: - raise ValueError(f"No adapter for dataset '{dataset}'. Known: {list(ADAPTERS)}") - return ADAPTERS[dataset] diff --git a/itrialspace/src/itrialspace/io/loader.py b/itrialspace/src/itrialspace/io/loader.py deleted file mode 100644 index 525874cacb48658bece5923e8a62e6b1ca9d664a..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/io/loader.py +++ /dev/null @@ -1,196 +0,0 @@ -""" -DatasetLoader — reads a nodule profile CSV and returns a list of -NoduleProfile objects with unified schema. -""" - -from __future__ import annotations - -from typing import Optional - -import numpy as np -import pandas as pd - -from itrialspace.core.label import LabelNormaliser -from itrialspace.core.profile import NoduleProfile -from itrialspace.io.adapters.adapters import get_adapter - -# Map CSV column names → NoduleProfile attribute names -_COL_MAP = { - "coordX": "coord_x", - "coordY": "coord_y", - "coordZ": "coord_z", -} - - -def _f(v, default=None) -> Optional[float]: - """Safe float conversion.""" - try: - f = float(v) - return None if np.isnan(f) else f - except (TypeError, ValueError): - return default - - -def _i(v, default=None) -> Optional[int]: - """Safe int conversion.""" - try: - f = float(v) - return None if np.isnan(f) else int(f) - except (TypeError, ValueError): - return default - - -def _b(v) -> Optional[bool]: - """Safe bool conversion.""" - if pd.isna(v): - return None - if isinstance(v, bool): - return v - if isinstance(v, (int, float)): - return bool(v) - s = str(v).strip().lower() - if s in ("true", "1", "yes"): - return True - if s in ("false", "0", "no"): - return False - return None - - -def _s(v, default: str = "") -> str: - """Safe string conversion.""" - if pd.isna(v): - return default - return str(v).strip() - - -class DatasetLoader: - """ - Loads a nodule profile CSV for a given dataset and returns - a list of NoduleProfile objects. - - Usage: - profiles = DatasetLoader.load("DLCS24", "/path/to/DLCS24_nodule_profiles.csv") - """ - - @staticmethod - def load(dataset: str, csv_path: str) -> list[NoduleProfile]: - adapter = get_adapter(dataset) - normaliser = LabelNormaliser(dataset) - - df = pd.read_csv(csv_path, low_memory=False) - df = adapter.preprocess(df) - - # Add row index for adapters that need it (IMDCT) - df["_row_index"] = df.index.astype(str) - - extra_cols = adapter.extra_cols(list(df.columns)) - profiles = [] - - for _, row in df.iterrows(): - pid = adapter.get_patient_id(row) - aid = adapter.get_annotation_id(row) - label = normaliser.normalise(row) - - meta = { - c: (None if pd.isna(row.get(c)) else row.get(c)) - for c in extra_cols - if c != "_row_index" - } - - p = NoduleProfile( - # identity - annotation_id=aid, - patient_id=pid, - dataset=dataset, - ct_path=_s(row.get("ct_path")), - label=label, - # bounding box - coord_x=_f(row.get("coordX"), 0.0), - coord_y=_f(row.get("coordY"), 0.0), - coord_z=_f(row.get("coordZ"), 0.0), - w=_f(row.get("w"), 0.0), - h=_f(row.get("h"), 0.0), - d=_f(row.get("d"), 0.0), - # morphology - nodule_mean_diam_mm=_f(row.get("nodule_mean_diam_mm"), 0.0), - nodule_vol_mm3=_f(row.get("nodule_vol_mm3")), - # anatomy - lobe_name=_s(row.get("lobe_name"), "unknown"), - lung_side=_s(row.get("lung_side"), "unknown"), - lung_zone=_s(row.get("lung_zone"), "unknown"), - organ_label_id=_i(row.get("organ_label_id"), 0), - organ_label_name=_s(row.get("organ_label_name")), - central_peripheral=_s(row.get("central_peripheral"), "unknown"), - nearby_organs_10mm=_s(row.get("nearby_organs_10mm")) or None, - # position – lung % - cranio_caudal_pct=_f(row.get("cranio_caudal_pct")), - mediolateral_pct=_f(row.get("mediolateral_pct")), - anteroposterior_pct=_f(row.get("anteroposterior_pct")), - # position – lobe % - lobe_cc_pct=_f(row.get("lobe_cc_pct")), - lobe_ml_pct=_f(row.get("lobe_ml_pct")), - lobe_ap_pct=_f(row.get("lobe_ap_pct")), - # distances - dist_to_trachea_mm=_f(row.get("dist_to_trachea_mm")), - dist_to_aorta_mm=_f(row.get("dist_to_aorta_mm")), - dist_to_heart_mm=_f(row.get("dist_to_heart_mm")), - dist_to_esophagus_mm=_f(row.get("dist_to_esophagus_mm")), - dist_to_pulmonary_vein_mm=_f(row.get("dist_to_pulmonary_vein_mm")), - dist_to_superior_vena_cava_mm=_f(row.get("dist_to_superior_vena_cava_mm")), - pleural_distance_mm=_f(row.get("pleural_distance_mm")), - airway_distance_mm=_f(row.get("airway_distance_mm")), - # inter-nodule - n_nodules_in_patient=_i(row.get("n_nodules_in_patient"), 1), - nearest_nodule_id=_s(row.get("nearest_nodule_id")) or None, - nearest_nodule_dist_mm=_f(row.get("nearest_nodule_dist_mm")), - nearest_dx_mm=_f(row.get("nearest_dx_mm")), - nearest_dy_mm=_f(row.get("nearest_dy_mm")), - nearest_dz_mm=_f(row.get("nearest_dz_mm")), - all_nodule_ids=_s(row.get("all_nodule_ids")) or None, - all_nodule_dists_mm=_s(row.get("all_nodule_dists_mm")) or None, - ipsilateral=_b(row.get("ipsilateral")), - nearest_same_lobe=_b(row.get("nearest_same_lobe")), - bilateral_distribution=_b(row.get("bilateral_distribution")) or False, - # reinsertion (100% complete) - reinsertion_lobe=_s(row.get("reinsertion_lobe"), "unknown"), - reinsertion_lung_side=_s(row.get("reinsertion_lung_side"), "unknown"), - reinsertion_lung_zone=_s(row.get("reinsertion_lung_zone"), "unknown"), - reinsertion_lobe_cc_pct=_f(row.get("reinsertion_lobe_cc_pct"), 0.0), - reinsertion_lobe_ml_pct=_f(row.get("reinsertion_lobe_ml_pct"), 0.0), - reinsertion_lobe_ap_pct=_f(row.get("reinsertion_lobe_ap_pct"), 0.0), - reinsertion_lung_cc_pct=_f(row.get("reinsertion_lung_cc_pct"), 0.0), - reinsertion_lung_ml_pct=_f(row.get("reinsertion_lung_ml_pct"), 0.0), - reinsertion_lung_ap_pct=_f(row.get("reinsertion_lung_ap_pct"), 0.0), - reinsertion_pleural_dist_mm=_f(row.get("reinsertion_pleural_dist_mm")), - reinsertion_airway_dist_mm=_f(row.get("reinsertion_airway_dist_mm")), - reinsertion_nodule_diam_mm=_f(row.get("reinsertion_nodule_diam_mm"), 0.0), - meta=meta, - ) - profiles.append(p) - - return profiles - - @staticmethod - def load_to_dataframe(dataset: str, csv_path: str) -> pd.DataFrame: - """ - Load CSV, add normalised `label`, `patient_id`, `dataset` columns, - and return the full DataFrame (core + extra columns). - Faster than load() for index-building. - """ - adapter = get_adapter(dataset) - normaliser = LabelNormaliser(dataset) - - df = pd.read_csv(csv_path, low_memory=False) - df = adapter.preprocess(df) - df["_row_index"] = df.index.astype(str) - - # Normalised identity columns - df["dataset"] = dataset - df["patient_id"] = df.apply(adapter.get_patient_id, axis=1) - df["annotation_id"] = df.apply(adapter.get_annotation_id, axis=1) - df["label"] = normaliser.normalise_series(df) - - # Drop internal helper - df = df.drop(columns=["_row_index"]) - - return df diff --git a/itrialspace/src/itrialspace/io/registry.py b/itrialspace/src/itrialspace/io/registry.py deleted file mode 100644 index 87328ba5a1a02c510784b069f58a4f0e700c8dc2..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/io/registry.py +++ /dev/null @@ -1,135 +0,0 @@ -""" -DatasetRegistry — maps dataset names to CSV paths. -Reads from config/datasets.yaml or can be built programmatically. -""" - -from __future__ import annotations - -import os -from pathlib import Path -from typing import Optional - -# Datasets permanently removed from the ecosystem. -_REMOVED_DATASETS = {"NLST3D"} - - -class DatasetRegistry: - """ - Holds the mapping of dataset name → CSV path. - - Usage — from YAML config (recommended): - registry = DatasetRegistry.from_yaml("/path/to/datasets.yaml") - - Usage — programmatic: - registry = DatasetRegistry() - registry.register("DLCS24", "/data/DLCS24_nodule_profiles.csv") - registry.register("LUNA25", "/data/LUNA25_nodule_profiles.csv") - - Usage — auto-discover from a directory: - registry = DatasetRegistry.from_directory("/data/profiles/") - # Looks for files matching *_nodule_profiles.csv - """ - - # Known dataset names in canonical order - KNOWN_DATASETS = ["DLCS24", "LUNA25", "LUNA16", "LUNGx", "LNDbv4", "NSCLCR", "IMDCT"] - - def __init__(self): - self._entries: dict[str, str] = {} # dataset → csv_path - - def register(self, dataset: str, csv_path: str) -> "DatasetRegistry": - """Register a single dataset. Returns self for chaining.""" - if dataset in _REMOVED_DATASETS: - raise ValueError( - f"Dataset '{dataset}' was removed due to quality issues and cannot be registered." - ) - csv_path = str(Path(csv_path).expanduser()) - if not os.path.isfile(csv_path): - raise FileNotFoundError(f"CSV not found: {csv_path}") - self._entries[dataset] = csv_path - return self - - def register_if_exists(self, dataset: str, csv_path: str) -> "DatasetRegistry": - """Register only if the file exists. Silent skip otherwise.""" - try: - return self.register(dataset, csv_path) - except FileNotFoundError: - return self - - def get(self, dataset: str) -> Optional[str]: - return self._entries.get(dataset) - - def datasets(self) -> list[str]: - return list(self._entries.keys()) - - def items(self): - return self._entries.items() - - def __len__(self) -> int: - return len(self._entries) - - def __repr__(self) -> str: - lines = [f"DatasetRegistry ({len(self)} datasets):"] - for ds, path in self._entries.items(): - lines.append(f" {ds:<10s} {path}") - return "\n".join(lines) - - # ── Class methods ────────────────────────────────────────────────────────── - - @classmethod - def from_yaml(cls, yaml_path: Optional[str] = None) -> "DatasetRegistry": - """Load from a YAML config file. - - When ``yaml_path`` is omitted, the file is discovered via - ``itrialspace.config.settings`` (top-level ``configs/datasets.yaml`` → - shipped ``datasets.example.yaml`` → bundled package default), and - ``${ITRIALSPACE_DATA_DIR}`` style placeholders are expanded. - """ - from itrialspace.config import settings - - _pkg_default = Path(__file__).resolve().parents[1] / "config" / "datasets.yaml" - if yaml_path is None: - yaml_path = settings.find_config("datasets.yaml", package_default=_pkg_default) - - config = settings.load_yaml(yaml_path) - - registry = cls() - datasets = config.get("datasets", config) # support flat or nested - - for name, entry in datasets.items(): - if isinstance(entry, dict): - path = entry.get("csv_path") or entry.get("path") - else: - path = str(entry) - if path: - registry.register_if_exists(name, path) - - return registry - - @classmethod - def from_directory( - cls, directory: str, pattern: str = "*_nodule_profiles.csv" - ) -> "DatasetRegistry": - """ - Auto-discover CSVs in a directory. - Filename must start with the dataset name, e.g. DLCS24_nodule_profiles.csv - """ - import glob - - registry = cls() - paths = sorted(glob.glob(os.path.join(directory, pattern))) - for path in paths: - fname = os.path.basename(path) - # Extract dataset name as the part before '_nodule_profiles.csv' - if "_nodule_profiles" in fname: - dataset = fname.split("_nodule_profiles")[0] - if dataset in cls.KNOWN_DATASETS: - registry.register_if_exists(dataset, path) - return registry - - @classmethod - def from_dict(cls, mapping: dict[str, str]) -> "DatasetRegistry": - """Build from a plain dict: {'DLCS24': '/path/...', ...}""" - registry = cls() - for name, path in mapping.items(): - registry.register_if_exists(name, path) - return registry diff --git a/itrialspace/src/itrialspace/mask_inserter/__init__.py b/itrialspace/src/itrialspace/mask_inserter/__init__.py deleted file mode 100644 index c366ffddc6c9a918c9a8682c2ed00f4747e7a99d..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -""" -iTrialSpace Mask Insertion Engine -================================= - -Downstream module that takes an iTrialSpace CohortManifest and produces -host-space nodule masks by inserting donor nodule masks into host CT -geometry according to the manifest's insertion plan. - -Submodules: - placement – percentile→voxel conversion, snapping, pleural margin, collision - resample – scipy-based resampling, scaling, binary cleanup - resolver_bridge – PathResolver integration for host/donor path resolution - inserter – main per-row and per-manifest orchestration - cli – command-line interface for HPC batch execution -""" - -__version__ = "0.1.0" - -from itrialspace.mask_inserter.inserter import insert_case, insert_manifest - -__all__ = ["insert_manifest", "insert_case", "__version__"] diff --git a/itrialspace/src/itrialspace/mask_inserter/__main__.py b/itrialspace/src/itrialspace/mask_inserter/__main__.py deleted file mode 100644 index 49dfdd410a49ec8bc35ef628b7c8d5e02084e995..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -"""Allow running as ``python -m itrialspace.mask_inserter``.""" -from itrialspace.mask_inserter.cli import main - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index b53908c1a6d0f886a0f404dae16ced71930a4845..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/__main__.cpython-310.pyc deleted file mode 100644 index 9ef5f622b2a1e12baa98d3571166e4f3c6192084..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/__main__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/cli.cpython-310.pyc deleted file mode 100644 index 3576617989f0310a9e6cecb776afb4a2bf55a6a5..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/cli.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/inserter.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/inserter.cpython-310.pyc deleted file mode 100644 index f974b801f81b4dea9635092cf470887171e960b1..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/inserter.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/placement.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/placement.cpython-310.pyc deleted file mode 100644 index a360e2ba1aa134a16bcc9178370f70f9e6302f14..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/placement.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/resample.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/resample.cpython-310.pyc deleted file mode 100644 index 05adac54efcbf21f2a53b7cce15f5afa4b81cda0..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/resample.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/resolver_bridge.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/resolver_bridge.cpython-310.pyc deleted file mode 100644 index 9389203723acaf7f61e71829414c467200407b7b..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/__pycache__/resolver_bridge.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/cli.py b/itrialspace/src/itrialspace/mask_inserter/cli.py deleted file mode 100644 index adcb1326e4aef448d5efb873514b81ac9f37152f..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/cli.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -""" -cli.py — Command-line interface for the iTrialSpace Mask Insertion Engine. - -Usage:: - - # Full batch run - python -m itrialspace.mask_inserter run \\ - --manifest cohort_manifest.csv \\ - --output-dir $ITRIALSPACE_OUTPUT_DIR/trial_01 \\ - --config my_overrides.yaml \\ - --trial-name trial_01 \\ - --seed 42 - - # Dry-run (placement only, no files written) - python -m itrialspace.mask_inserter run \\ - --manifest cohort_manifest.csv \\ - --output-dir $ITRIALSPACE_OUTPUT_DIR/trial_01 \\ - --dry-run - - # Verify existing outputs - python -m itrialspace.mask_inserter verify \\ - --output-dir $ITRIALSPACE_OUTPUT_DIR/trial_01 -""" -from __future__ import annotations - -import argparse -import json -import logging -import os -import sys - - -def main(argv: list[str] | None = None) -> int: - """Entry point for ``python -m itrialspace.mask_inserter``.""" - parser = argparse.ArgumentParser( - prog="itrialspace.mask_inserter", - description="iTrialSpace Mask Insertion Engine — insert donor nodule " - "masks into host CT space according to a CohortManifest.", - ) - parser.add_argument( - "--version", - action="version", - version=f"%(prog)s {_get_version()}", - ) - sub = parser.add_subparsers(dest="command") - - # ── run ──────────────────────────────────────────────────────────────── - p_run = sub.add_parser("run", help="Run the insertion pipeline.") - p_run.add_argument( - "--manifest", - "-m", - required=True, - help="Path to CohortManifest CSV or JSON.", - ) - p_run.add_argument( - "--output-dir", - "-o", - required=True, - help="Root output directory.", - ) - p_run.add_argument( - "--config", - "-c", - default=None, - help="YAML config overrides (merged with defaults).", - ) - p_run.add_argument( - "--base-dir", - default=None, - help="Base directory for resolving relative paths in the manifest.", - ) - p_run.add_argument( - "--trial-name", - default="unnamed", - help="Trial name (used for deterministic seeding).", - ) - p_run.add_argument( - "--seed", - type=int, - default=42, - help="Global random seed.", - ) - p_run.add_argument( - "--dry-run", - action="store_true", - help="Compute placement without writing masks.", - ) - p_run.add_argument( - "--n-jobs", - type=int, - default=1, - help="Number of parallel workers (across cases).", - ) - p_run.add_argument( - "--verbose", - "-v", - action="count", - default=0, - help="Increase logging verbosity.", - ) - - # ── verify ──────────────────────────────────────────────────────────── - p_verify = sub.add_parser( - "verify", - help="Verify outputs from a previous run.", - ) - p_verify.add_argument( - "--output-dir", - "-o", - required=True, - help="Output directory to verify.", - ) - p_verify.add_argument( - "--manifest", - "-m", - default=None, - help="Original manifest for cross-referencing (optional).", - ) - - args = parser.parse_args(argv) - - if args.command is None: - parser.print_help() - return 0 - - # Set up logging - level = logging.WARNING - if hasattr(args, "verbose"): - if args.verbose == 1: - level = logging.INFO - elif args.verbose >= 2: - level = logging.DEBUG - - logging.basicConfig( - level=level, - format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", - datefmt="%H:%M:%S", - ) - - if args.command == "run": - return _cmd_run(args) - elif args.command == "verify": - return _cmd_verify(args) - else: - parser.print_help() - return 1 - - -def _cmd_run(args: argparse.Namespace) -> int: - """Execute the insertion pipeline.""" - from itrialspace.mask_inserter.inserter import insert_manifest - - records = insert_manifest( - manifest_path=args.manifest, - output_dir=args.output_dir, - config_path=args.config, - base_dir=args.base_dir, - trial_name=args.trial_name, - seed=args.seed, - dry_run=args.dry_run, - n_jobs=args.n_jobs, - ) - - n_ok = sum(1 for r in records if r.status == "success") - n_fail = sum(1 for r in records if r.status == "failed") - n_dry = sum(1 for r in records if r.status == "dry_run") - - print(f"\niTrialSpace Mask Inserter — {'DRY RUN' if args.dry_run else 'COMPLETE'}") - print(f" Total rows: {len(records)}") - print(f" Success: {n_ok}") - print(f" Failed: {n_fail}") - if n_dry: - print(f" Dry-run: {n_dry}") - print(f" Output dir: {args.output_dir}") - - if n_fail > 0: - print("\nFailed cases:") - for r in records: - if r.status == "failed": - print(f" {r.case_id}/nodule_{r.nodule_idx}: {r.reason}") - - return 1 if n_fail > 0 and n_ok == 0 else 0 - - -def _cmd_verify(args: argparse.Namespace) -> int: - """Verify outputs from a previous run.""" - output_dir = args.output_dir - audit_path = os.path.join(output_dir, "audit.json") - - if not os.path.isfile(audit_path): - print(f"ERROR: No audit.json found in {output_dir}") - return 1 - - with open(audit_path) as f: - audit = json.load(f) - - records = audit.get("records", []) - print(f"Verifying {len(records)} insertion records from {audit_path}") - - missing_nodule_masks = 0 - missing_combined = 0 - total_success = 0 - seen_combined = set() - - for rec in records: - if rec.get("status") != "success": - continue - total_success += 1 - - # Per-nodule mask (optional — may not be saved) - mask_path = rec.get("output_mask_path", "") - if mask_path and not os.path.isfile(mask_path): - missing_nodule_masks += 1 - - # Combined mask (one per case) - combined_path = rec.get("output_combined_path", "") - if combined_path and combined_path not in seen_combined: - seen_combined.add(combined_path) - if not os.path.isfile(combined_path): - missing_combined += 1 - print(f" MISSING combined: {combined_path}") - - print("\nVerification:") - print(f" Successful insertions: {total_success}") - print( - f" Combined masks: {len(seen_combined)} expected, " - f"{len(seen_combined) - missing_combined} found" - ) - if missing_combined: - print(f" Missing combined: {missing_combined}") - - if args.manifest: - import pandas as pd - - df = pd.read_csv(args.manifest) - n_cases = df["case_id"].nunique() if "case_id" in df.columns else len(df) - print(f" Manifest rows: {len(df)} ({n_cases} unique cases)") - print( - f" Coverage: {total_success}/{len(df)} " - f"({100*total_success/max(len(df),1):.1f}%)" - ) - - return 1 if missing_combined > 0 else 0 - - -def _get_version() -> str: - try: - from itrialspace.mask_inserter import __version__ - - return __version__ - except ImportError: - return "unknown" - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/itrialspace/src/itrialspace/mask_inserter/config/defaults.yaml b/itrialspace/src/itrialspace/mask_inserter/config/defaults.yaml deleted file mode 100644 index 2035657fa4cdbd99f3db7c794fd23b2868fcbdaa..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/config/defaults.yaml +++ /dev/null @@ -1,113 +0,0 @@ -# iTrialSpace Mask Insertion Engine — defaults -# Override per-site via --config flag or INSERTER_CONFIG env var. - -# ── Lobe label mapping (VISTA3D integer labels) ───────────────────────────── -lobe_labels: - left_lung_upper_lobe: 28 - left_lung_lower_lobe: 29 - right_lung_upper_lobe: 30 - right_lung_middle_lobe: 31 - right_lung_lower_lobe: 32 - -# String ↔ integer aliases accepted in manifest ``insertion_lobe`` column. -# Keys are normalised lowercased names; values map to the canonical key above. -lobe_aliases: - lul: left_lung_upper_lobe - lll: left_lung_lower_lobe - rul: right_lung_upper_lobe - rml: right_lung_middle_lobe - rll: right_lung_lower_lobe - left_upper: left_lung_upper_lobe - left_lower: left_lung_lower_lobe - right_upper: right_lung_upper_lobe - right_middle: right_lung_middle_lobe - right_lower: right_lung_lower_lobe - -# Labels treated as "whole lung" for fallback placement. -lung_labels: [28, 29, 30, 31, 32] - -# ── Nodule output label ───────────────────────────────────────────────────── -# Integer value written into the host output mask for inserted nodule voxels. -# The intermediate binary mask (0/1) is converted to this label before writing. -# Default 23; change without code edits by overriding this value. -nodule_label_value: 23 - -# Future extension: per-nodule-type label mapping (unused for now). -# When populated, keys are nodule type strings and values are integer labels. -# Example: {"malignant": 23, "benign": 24} -nodule_type_to_label: {} - -# ── Placement parameters ──────────────────────────────────────────────────── -placement: - # Maximum search radius (voxels) when snapping an out-of-mask candidate to - # the nearest valid voxel inside the target mask. - max_snap_radius_vox: 25 - - # Minimum distance (mm) from the lung boundary that an insertion centre must - # satisfy. Set to 0 to disable. - min_pleural_dist_mm: 2.0 - - # If True, check for overlap with existing nodules in the combined mask and - # attempt to shift the placement to avoid it. - check_overlap: true - - # Maximum fraction of donor mask voxels allowed to overlap with an existing - # nodule mask before the placement is declared infeasible. - max_overlap_fraction: 0.05 - - # Maximum additional shift (voxels) attempted to resolve overlap collisions. - max_collision_shift_vox: 15 - -# ── Resampling parameters ─────────────────────────────────────────────────── -resample: - # Interpolation for binary masks: "nearest" (default) or "linear" then - # threshold. - interpolation: nearest - - # After resampling, voxels with value >= this threshold are set to 1. - binary_threshold: 0.5 - - # Remove connected components smaller than this (voxels) after resampling. - min_component_size_vox: 3 - - # Fill holes in the binary mask after resampling. - fill_holes: true - -# ── Output naming ─────────────────────────────────────────────────────────── -output: - # Flat directory — all combined masks in one folder, no subdirectories. - use_case_subdirs: false - - # Combined mask template. - # Delimiter convention: '--' separates fields, '-' separates key from value. - # Parsing: dict(f.split('-', 1) for f in stem.split('--')[1:] if '-' in f) - # Available placeholders: {trial_name}, {case_id}, {host_id}, {host_dataset}, {donor_id}. - # case_id is zero-padded to 4 digits. host_id is SHA-256[:8] when >20 chars. - combined_mask_template: "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz" - - # Whether to save individual per-nodule binary masks (in addition to the combined mask). - save_per_nodule_mask: false - - # Per-nodule mask template (only used when save_per_nodule_mask is true). - nodule_mask_template: "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz" - - # Audit log filename. - audit_name: audit.json - - # Compress NIfTI outputs. - compress: true - -# ── Optional CT intensity insertion (experimental, off by default) ────────── -ct_insertion: - enabled: false - blending_mode: poisson # poisson | direct | alpha - boundary_width_mm: 2.0 - -# ── Parallelism ───────────────────────────────────────────────────────────── -parallel: - backend: loky # loky | threading | sequential - n_jobs: 1 - verbose: 10 - -# ── Reproducibility ───────────────────────────────────────────────────────── -seed: 42 diff --git a/itrialspace/src/itrialspace/mask_inserter/inserter.py b/itrialspace/src/itrialspace/mask_inserter/inserter.py deleted file mode 100644 index 47b1471ee9faa7da9be1435ec526d341c67008eb..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/inserter.py +++ /dev/null @@ -1,693 +0,0 @@ -# -*- coding: utf-8 -*- -""" -inserter.py — Main orchestration for the mask insertion pipeline. - -Public API: - insert_case(row, ...) – process a single manifest row - insert_manifest(path, ...) – process an entire manifest CSV/JSON - -Workflow per row: - 1. Resolve paths (resolver_bridge) - 2. Load host organ segmentation → canonical RAS+ - 3. Compute placement (placement.py) - 4. Load donor nodule mask → canonical RAS+ - 5. Resample donor into host geometry (resample.py) - 6. Paste into combined mask; check collision - 7. Save per-nodule mask and update combined mask - 8. Return audit record -""" -from __future__ import annotations - -import hashlib -import json -import logging -import os -import time -from dataclasses import asdict, dataclass, field -from pathlib import Path -from typing import Any, Tuple - -import numpy as np -import pandas as pd - -try: - import yaml -except ImportError: - yaml = None # type: ignore[assignment] - -from itrialspace.mask_inserter.placement import ( - PlacementConfig, - check_overlap, - compute_placement, - make_seed, - resolve_collision, -) -from itrialspace.mask_inserter.resample import ( - ResampleConfig, - load_nifti_canonical, - resample_donor_to_host, - save_nifti, -) -from itrialspace.mask_inserter.resolver_bridge import ResolverBridge - -logger = logging.getLogger("itrialspace.mask_inserter") - - -def _compact_id(raw_id: str, max_len: int = 20) -> str: - """Shorten IDs longer than *max_len* to a deterministic 8-char hex hash.""" - s = str(raw_id) - if len(s) <= max_len: - return s - return hashlib.sha256(s.encode()).hexdigest()[:8] - - -# ── Configuration loading ───────────────────────────────────────────────── - -_DEFAULTS_YAML = Path(__file__).parent / "config" / "defaults.yaml" - - -def load_config(config_path: str | None = None) -> dict: - """Load YAML config, merging with defaults.""" - if yaml is None: - raise ImportError("pyyaml required: pip install pyyaml") - - with open(_DEFAULTS_YAML) as f: - defaults = yaml.safe_load(f) or {} - - if config_path: - with open(config_path) as f: - overrides = yaml.safe_load(f) or {} - defaults = _deep_merge(defaults, overrides) - - return defaults - - -def _deep_merge(base: dict, override: dict) -> dict: - """Recursively merge *override* into *base*.""" - result = base.copy() - for k, v in override.items(): - if isinstance(v, dict) and isinstance(result.get(k), dict): - result[k] = _deep_merge(result[k], v) - else: - result[k] = v - return result - - -def _placement_config_from_dict(d: dict) -> PlacementConfig: - p = d.get("placement", {}) - return PlacementConfig( - max_snap_radius_vox=p.get("max_snap_radius_vox", 25), - min_pleural_dist_mm=p.get("min_pleural_dist_mm", 2.0), - check_overlap=p.get("check_overlap", True), - max_overlap_fraction=p.get("max_overlap_fraction", 0.05), - max_collision_shift_vox=p.get("max_collision_shift_vox", 15), - ) - - -def _resample_config_from_dict(d: dict) -> ResampleConfig: - r = d.get("resample", {}) - return ResampleConfig( - interpolation=r.get("interpolation", "nearest"), - binary_threshold=r.get("binary_threshold", 0.5), - min_component_size_vox=r.get("min_component_size_vox", 3), - fill_holes=r.get("fill_holes", True), - ) - - -# ── Audit record ────────────────────────────────────────────────────────── - - -@dataclass -class InsertionAuditRecord: - """Audit trail for a single nodule insertion.""" - - case_id: str = "" - nodule_idx: int = 0 - is_primary: bool = True - companion_group_id: str = "" - status: str = "success" # success | skipped | failed - reason: str = "" - # Paths used - host_ct_path: str = "" - host_organ_seg_path: str = "" - donor_nodule_mask_path: str = "" - # Placement - insertion_lobe: str = "" - cc_pct: float = 0.0 - ml_pct: float = 0.0 - ap_pct: float = 0.0 - target_ijk: Tuple[int, int, int] | None = None - target_world_mm: Tuple[float, float, float] | None = None - snapped: bool = False - snap_distance_vox: float = 0.0 - pleural_dist_mm: float = 0.0 - overlap_fraction: float = 0.0 - placement_warnings: list = field(default_factory=list) - # Resample - scale_factor: float = 1.0 - donor_mask_voxels: int = 0 - resampled_mask_voxels: int = 0 - # Output - output_mask_path: str = "" - output_combined_path: str = "" - host_id_compact: str = "" - nodule_label_value: int = 23 - elapsed_sec: float = 0.0 - - -# ── Per-row insertion ───────────────────────────────────────────────────── - - -def insert_case( - row: pd.Series | dict, - *, - output_dir: str, - config: dict | None = None, - resolver: ResolverBridge | None = None, - existing_combined: np.ndarray | None = None, - existing_affine: np.ndarray | None = None, - trial_name: str = "unnamed", - seed: int = 42, - dry_run: bool = False, -) -> Tuple[InsertionAuditRecord, np.ndarray | None, np.ndarray | None]: - """Insert a single donor nodule into host space. - - Parameters - ---------- - row : Series or dict - One row from the CohortManifest. - output_dir : str - Root output directory. - config : dict - Merged configuration (see ``load_config``). - resolver : ResolverBridge - For path resolution. - existing_combined : ndarray, optional - Current combined mask for this host (updated in-place for multi-nodule). - existing_affine : ndarray, optional - Affine of the existing combined mask. - trial_name : str - seed : int - dry_run : bool - If True, compute placement but don't write files. - - Returns - ------- - (audit_record, updated_combined_mask, combined_affine) - """ - t0 = time.time() - if isinstance(row, dict): - row = pd.Series(row) - - cfg = config or load_config() - resolver = resolver or ResolverBridge() - placement_cfg = _placement_config_from_dict(cfg) - resample_cfg = _resample_config_from_dict(cfg) - - case_id = str(row.get("case_id", "unknown")) - nodule_idx = int(row.get("nodule_idx", 0)) - - audit = InsertionAuditRecord( - case_id=case_id, - nodule_idx=nodule_idx, - is_primary=bool(row.get("is_primary_nodule", True)), - companion_group_id=str(row.get("companion_group_id", "")), - insertion_lobe=str(row.get("insertion_lobe", "")), - cc_pct=float(row.get("insertion_lobe_cc_pct", 0)), - ml_pct=float(row.get("insertion_lobe_ml_pct", 0)), - ap_pct=float(row.get("insertion_lobe_ap_pct", 0)), - scale_factor=float(row.get("scale_factor", 1.0)), - ) - - # ── 1. Resolve paths ───────────────────────────────────────────────── - paths = resolver.resolve(row) - missing = paths.validate() - if missing: - audit.status = "failed" - audit.reason = f"Missing files: {missing}" - audit.elapsed_sec = time.time() - t0 - logger.warning("Row %s/%d: %s", case_id, nodule_idx, audit.reason) - return audit, existing_combined, existing_affine - - audit.host_ct_path = paths.host_ct - audit.host_organ_seg_path = paths.host_organ_seg - audit.donor_nodule_mask_path = paths.donor_nodule_mask - - # ── 2. Load host organ segmentation ────────────────────────────────── - try: - seg_data, seg_aff, seg_spacing = load_nifti_canonical(paths.host_organ_seg) - except Exception as e: - audit.status = "failed" - audit.reason = f"Failed to load organ seg: {e}" - audit.elapsed_sec = time.time() - t0 - return audit, existing_combined, existing_affine - - host_shape = seg_data.shape - host_spacing = seg_spacing - - # ── 2a. Shape guard: reset combined mask if host geometry changed ───── - # Multi-nodule cases (e.g. LUNA25) may span different CT series with - # different array shapes. When that happens we must re-initialise the - # combined mask from the current organ seg so that later overlap - # checks and voxel stamping don't crash on shape mismatches. - if existing_combined is not None and existing_combined.shape != host_shape: - logger.warning( - "Row %s/%d: host geometry changed from %s to %s — " - "re-initialising combined mask for this CT series.", - case_id, - nodule_idx, - existing_combined.shape, - host_shape, - ) - existing_combined = None - existing_affine = None - - # ── 2b. Sanity check: host seg should not already contain nodule label ─ - nodule_label_value = int(cfg.get("nodule_label_value", 23)) - if existing_combined is None and (seg_data == nodule_label_value).any(): - n_pre = int((seg_data == nodule_label_value).sum()) - logger.warning( - "Row %s/%d: host organ seg already contains %d voxels with " - "nodule label %d — these will be overwritten during insertion.", - case_id, - nodule_idx, - n_pre, - nodule_label_value, - ) - - # ── 3. Compute placement ───────────────────────────────────────────── - case_seed = make_seed(trial_name, case_id, nodule_idx, seed) - rng = np.random.default_rng(case_seed) - - lobe_labels = cfg.get("lobe_labels", None) - lobe_aliases = cfg.get("lobe_aliases", None) - lung_labels = cfg.get("lung_labels", None) - - placement = compute_placement( - seg_data=seg_data, - affine=seg_aff, - voxel_spacing_mm=host_spacing, - insertion_lobe=audit.insertion_lobe, - cc_pct=audit.cc_pct, - ml_pct=audit.ml_pct, - ap_pct=audit.ap_pct, - config=placement_cfg, - existing_combined_mask=existing_combined, - lobe_labels=lobe_labels, - lobe_aliases=lobe_aliases, - lung_labels=lung_labels, - rng=rng, - ) - - audit.target_ijk = placement.center_ijk - audit.target_world_mm = placement.center_world_mm - audit.snapped = placement.snapped - audit.snap_distance_vox = placement.snap_distance_vox - audit.pleural_dist_mm = placement.pleural_dist_mm - audit.placement_warnings = placement.warnings - - if not placement.is_feasible: - audit.status = "failed" - audit.reason = f"Placement infeasible: {placement.reason}" - audit.elapsed_sec = time.time() - t0 - logger.warning("Row %s/%d: %s", case_id, nodule_idx, audit.reason) - return audit, existing_combined, existing_affine - - if dry_run: - audit.status = "dry_run" - audit.elapsed_sec = time.time() - t0 - return audit, existing_combined, existing_affine - - # ── 4. Load donor nodule mask ──────────────────────────────────────── - try: - donor_data, donor_aff, donor_spacing = load_nifti_canonical(paths.donor_nodule_mask) - except Exception as e: - audit.status = "failed" - audit.reason = f"Failed to load donor mask: {e}" - audit.elapsed_sec = time.time() - t0 - return audit, existing_combined, existing_affine - - audit.donor_mask_voxels = int((donor_data > 0).sum()) - - # ── 5. Resample donor into host geometry ───────────────────────────── - scale_factor = audit.scale_factor - target_ijk = placement.center_ijk - - try: - host_nodule_mask = resample_donor_to_host( - donor_mask=donor_data, - donor_affine=donor_aff, - donor_spacing=donor_spacing, - host_shape=host_shape, - host_affine=seg_aff, - host_spacing=host_spacing, - target_center_ijk=target_ijk, - scale_factor=scale_factor, - config=resample_cfg, - ) - except Exception as e: - audit.status = "failed" - audit.reason = f"Resampling failed: {e}" - audit.elapsed_sec = time.time() - t0 - return audit, existing_combined, existing_affine - - audit.resampled_mask_voxels = int((host_nodule_mask > 0).sum()) - - # ── 6. Overlap check & collision resolution ────────────────────────── - if placement_cfg.check_overlap and existing_combined is not None: - frac, ok = check_overlap( - existing_combined, - host_nodule_mask, - placement_cfg.max_overlap_fraction, - ) - audit.overlap_fraction = frac - if not ok: - new_center = resolve_collision( - (seg_data > 0).astype(np.uint8), - existing_combined, - target_ijk, - max_shift=placement_cfg.max_collision_shift_vox, - rng=rng, - ) - if new_center is not None: - audit.placement_warnings.append( - f"Shifted from {target_ijk} to {new_center} to resolve collision." - ) - # Re-resample at new centre - host_nodule_mask = resample_donor_to_host( - donor_mask=donor_data, - donor_affine=donor_aff, - donor_spacing=donor_spacing, - host_shape=host_shape, - host_affine=seg_aff, - host_spacing=host_spacing, - target_center_ijk=new_center, - scale_factor=scale_factor, - config=resample_cfg, - ) - audit.target_ijk = new_center - audit.resampled_mask_voxels = int((host_nodule_mask > 0).sum()) - else: - audit.placement_warnings.append("Could not resolve collision; mask may overlap.") - - # ── 7. Optionally save per-nodule mask ───────────────────────────── - out_cfg = cfg.get("output", {}) - audit.nodule_label_value = nodule_label_value - - if out_cfg.get("save_per_nodule_mask", False): - if out_cfg.get("use_case_subdirs", False): - case_dir = os.path.join(output_dir, case_id) - else: - case_dir = output_dir - - mask_template = out_cfg.get( - "nodule_mask_template", - "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz", - ) - donor_id = str(row.get("donor_annotation_id", f"donor_{nodule_idx}")) - mask_name = mask_template.format( - case_id=str(case_id).zfill(4), - nodule_idx=nodule_idx, - donor_id=donor_id, - host_patient_id=str(row.get("host_patient_id", "")), - host_dataset=str(row.get("host_dataset", "")), - ) - mask_path = os.path.join(case_dir, mask_name) - - labelled_nodule_mask = np.where( - host_nodule_mask > 0, - np.int16(nodule_label_value), - np.int16(0), - ).astype(np.int16) - save_nifti(labelled_nodule_mask, seg_aff, mask_path, dtype=np.int16) - audit.output_mask_path = mask_path - - # ── 8. Update combined mask ────────────────────────────────────────── - if existing_combined is None: - # Initialise from the host organ segmentation so the combined mask - # carries full body context (lobe labels etc.) in addition to the - # inserted nodule voxels. - existing_combined = seg_data.astype(np.int16) - existing_affine = seg_aff - - # Stamp nodule voxels with the label value. - # Overlap check prevents overwriting an already-inserted nodule voxel; - # it does NOT block placement over organ-seg labels (lobe labels are - # overwritten by the nodule, which is the intended behaviour). - insert_where = host_nodule_mask > 0 - if placement_cfg.check_overlap: - # Only refuse to overwrite voxels that already carry the nodule label - # (i.e. a previous nodule in this companion group). - insert_where = insert_where & (existing_combined != nodule_label_value) - existing_combined[insert_where] = nodule_label_value - - audit.status = "success" - audit.elapsed_sec = time.time() - t0 - logger.info( - "Inserted %s/nodule_%d: %d voxels at %s (%.1fs)", - case_id, - nodule_idx, - audit.resampled_mask_voxels, - audit.target_ijk, - audit.elapsed_sec, - ) - return audit, existing_combined, existing_affine - - -# ── Manifest-level orchestration ────────────────────────────────────────── - - -def insert_manifest( - manifest_path: str, - output_dir: str, - *, - config_path: str | None = None, - resolver: ResolverBridge | None = None, - path_resolver: object = None, - base_dir: str | None = None, - trial_name: str | None = None, - seed: int | None = None, - dry_run: bool = False, - n_jobs: int = 1, -) -> list[InsertionAuditRecord]: - """Process an entire CohortManifest. - - Groups rows by case_id to handle multi-nodule companion groups, - processing nodules within a case sequentially (so the combined mask - accumulates correctly). - - Parameters - ---------- - manifest_path : str - Path to manifest CSV or JSON. - output_dir : str - Root output directory. - config_path : str, optional - YAML config overrides. - resolver : ResolverBridge, optional - path_resolver : object, optional - iTrialSpace PathResolver to wrap. - base_dir : str, optional - Fallback base directory for relative paths. - trial_name : str, optional - seed : int, optional - dry_run : bool - n_jobs : int - Parallelism (across cases, not within). - - Returns - ------- - list[InsertionAuditRecord] - """ - cfg = load_config(config_path) - seed = seed or cfg.get("seed", 42) - trial_name = trial_name or "unnamed" - - if resolver is None: - resolver = ResolverBridge(path_resolver=path_resolver, base_dir=base_dir) - - # Load manifest - df = _load_manifest_df(manifest_path) - logger.info( - "Loaded manifest with %d rows from %s", - len(df), - manifest_path, - ) - - # Group by case_id - if "case_id" not in df.columns: - raise ValueError("Manifest must have a 'case_id' column.") - - groups = list(df.groupby("case_id", sort=False)) - logger.info("Processing %d cases.", len(groups)) - - all_records: list[InsertionAuditRecord] = [] - out_cfg = cfg.get("output", {}) - - # Sequential per-case processing (multi-nodule must be sequential) - for case_id, case_df in groups: - if "nodule_idx" in case_df.columns: - case_df = case_df.sort_values("nodule_idx") - combined_mask = None - combined_aff = None - - # Track per-geometry combined masks for cases that span multiple - # CT series (e.g. LUNA25 patients with different-shaped CTs). - # Each entry: (mask_array, affine, [audit_record_indices]) - geo_masks: list[tuple[np.ndarray, np.ndarray | None, list[int]]] = [] - current_geo_audits: list[int] = [] - - for _, row in case_df.iterrows(): - prev_mask = combined_mask - prev_aff = combined_aff - - audit, combined_mask, combined_aff = insert_case( - row, - output_dir=output_dir, - config=cfg, - resolver=resolver, - existing_combined=combined_mask, - existing_affine=combined_aff, - trial_name=trial_name, - seed=seed, - dry_run=dry_run, - ) - - audit_idx = len(all_records) - all_records.append(audit) - - # Detect geometry reset: insert_case created a new combined - # mask array because the host shape changed. - if prev_mask is not None and combined_mask is not prev_mask: - geo_masks.append((prev_mask, prev_aff, current_geo_audits)) - current_geo_audits = [] - - current_geo_audits.append(audit_idx) - - # Finalise last geometry - if combined_mask is not None: - geo_masks.append((combined_mask, combined_aff, current_geo_audits)) - - # Save combined mask(s) per case - if not dry_run and geo_masks: - if out_cfg.get("use_case_subdirs", False): - case_dir = os.path.join(output_dir, str(case_id)) - else: - case_dir = output_dir - - first_row = case_df.iloc[0] - combined_template = out_cfg.get( - "combined_mask_template", - "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz", - ) - raw_host_id = str(first_row.get("host_patient_id", "")) - compact_host_id = _compact_id(raw_host_id) - - if len(case_df) > 1: - donor_id_str = f"Nnod{len(case_df)}" - else: - donor_id_str = str(first_row.get("donor_annotation_id", "")) - - base_combined_name = combined_template.format( - trial_name=str(first_row.get("trial_name", trial_name)), - case_id=str(case_id).zfill(4), - host_id=compact_host_id, - host_dataset=str(first_row.get("host_dataset", "")), - donor_id=donor_id_str, - ) - - multi_geo = len(geo_masks) > 1 - if multi_geo: - logger.info( - "Case %s spans %d CT geometries; saving separate " - "combined masks per geometry.", - case_id, - len(geo_masks), - ) - - for geo_idx, (mask, aff, audit_indices) in enumerate(geo_masks): - if not mask.any(): - continue - if aff is None: - aff = np.eye(4) - - # Append _ct{N} suffix for multi-geometry cases so each - # CT series gets its own combined mask file. - if multi_geo: - combined_name = base_combined_name.replace( - "_mask.nii.gz", - f"_ct{geo_idx}_mask.nii.gz", - ) - else: - combined_name = base_combined_name - - combined_path = os.path.join(case_dir, combined_name) - save_nifti(mask, aff, combined_path, dtype=np.int16) - - for ai in audit_indices: - all_records[ai].output_combined_path = combined_path - all_records[ai].host_id_compact = compact_host_id - - # Write audit JSON - if not dry_run: - audit_name = out_cfg.get("audit_name", "audit.json") - audit_path = os.path.join(output_dir, audit_name) - _write_audit(all_records, audit_path, trial_name, manifest_path) - - n_ok = sum(1 for r in all_records if r.status == "success") - n_fail = sum(1 for r in all_records if r.status == "failed") - logger.info( - "Done: %d success, %d failed, %d total.", - n_ok, - n_fail, - len(all_records), - ) - - return all_records - - -# ── Helpers ─────────────────────────────────────────────────────────────── - - -def _load_manifest_df(path: str) -> pd.DataFrame: - """Load manifest from CSV or JSON.""" - if path.endswith(".json"): - with open(path) as f: - data = json.load(f) - if isinstance(data, list): - return pd.DataFrame(data) - if "cases" in data: - return pd.DataFrame(data["cases"]) - raise ValueError("JSON manifest must be a list or have a 'cases' key.") - return pd.read_csv(path) - - -def _write_audit( - records: list[InsertionAuditRecord], - path: str, - trial_name: str, - manifest_path: str, -) -> None: - """Write audit trail as JSON.""" - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - data = { - "trial_name": trial_name, - "manifest_path": manifest_path, - "n_total": len(records), - "n_success": sum(1 for r in records if r.status == "success"), - "n_failed": sum(1 for r in records if r.status == "failed"), - "records": [_audit_to_dict(r) for r in records], - } - with open(path, "w") as f: - json.dump(data, f, indent=2, default=str) - logger.info("Audit written to %s", path) - - -def _audit_to_dict(r: InsertionAuditRecord) -> dict[str, Any]: - """Convert audit record to a JSON-safe dict.""" - d = asdict(r) - # Convert tuples to lists for JSON - for key in ("target_ijk", "target_world_mm"): - if d[key] is not None: - d[key] = list(d[key]) - return d diff --git a/itrialspace/src/itrialspace/mask_inserter/placement.py b/itrialspace/src/itrialspace/mask_inserter/placement.py deleted file mode 100644 index b5c11c39eee8c916bdbc0eb0bc789896b5d70cfc..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/placement.py +++ /dev/null @@ -1,627 +0,0 @@ -# -*- coding: utf-8 -*- -""" -placement.py — Percentile-to-voxel conversion, snapping, pleural-margin -enforcement, and overlap/collision avoidance for nodule insertion. - -Coordinate convention: all index operations are performed **after** -canonicalising both the host CT and organ-segmentation to RAS+ orientation -using ``nibabel.as_closest_canonical``. In RAS+: - - axis 0 → Right→Left (X / mediolateral) - axis 1 → Anterior→Posterior (Y / anteroposterior) - axis 2 → Inferior→Superior (Z / craniocaudal) - -Percentile mapping: - - voxel_i = i_min + (ml_pct / 100) × (i_max − i_min) - voxel_j = j_min + (ap_pct / 100) × (j_max − j_min) - voxel_k = k_min + (cc_pct / 100) × (k_max − k_min) - -where (i_min…i_max, j_min…j_max, k_min…k_max) is the bounding box of -the target structure mask in canonical index space. -""" -from __future__ import annotations - -import hashlib -from dataclasses import dataclass, field -from typing import Optional, Tuple - -import numpy as np -from scipy import ndimage - -# ── Data classes ────────────────────────────────────────────────────────── - - -@dataclass -class PlacementResult: - """Output of the placement algorithm.""" - - center_ijk: Optional[Tuple[int, int, int]] = None - center_world_mm: Optional[Tuple[float, float, float]] = None - is_feasible: bool = True - snapped: bool = False - snap_distance_vox: float = 0.0 - pleural_dist_mm: float = float("inf") - overlap_fraction: float = 0.0 - warnings: list = field(default_factory=list) - reason: str = "" - - -@dataclass -class PlacementConfig: - """Parameters governing placement decisions.""" - - max_snap_radius_vox: int = 25 - min_pleural_dist_mm: float = 2.0 - check_overlap: bool = True - max_overlap_fraction: float = 0.05 - max_collision_shift_vox: int = 15 - - -# ── Lobe label resolution ──────────────────────────────────────────────── - -# Canonical VISTA3D lobe labels. -DEFAULT_LOBE_LABELS = { - "left_lung_upper_lobe": 28, - "left_lung_lower_lobe": 29, - "right_lung_upper_lobe": 30, - "right_lung_middle_lobe": 31, - "right_lung_lower_lobe": 32, -} - -DEFAULT_LOBE_ALIASES = { - "lul": "left_lung_upper_lobe", - "lll": "left_lung_lower_lobe", - "rul": "right_lung_upper_lobe", - "rml": "right_lung_middle_lobe", - "rll": "right_lung_lower_lobe", - "left_upper": "left_lung_upper_lobe", - "left_lower": "left_lung_lower_lobe", - "right_upper": "right_lung_upper_lobe", - "right_middle": "right_lung_middle_lobe", - "right_lower": "right_lung_lower_lobe", -} - - -def resolve_lobe_label( - lobe_name: str, - lobe_labels: dict | None = None, - lobe_aliases: dict | None = None, -) -> int: - """Resolve a human-readable lobe name to its integer segmentation label. - - Parameters - ---------- - lobe_name : str - Raw value from the manifest ``insertion_lobe`` column. - lobe_labels : dict, optional - Canonical name → int mapping. Defaults to VISTA3D labels. - lobe_aliases : dict, optional - Alias → canonical name mapping. - - Returns - ------- - int Label ID in the organ segmentation. - - Raises - ------ - KeyError If the lobe name cannot be resolved. - """ - lobe_labels = lobe_labels or DEFAULT_LOBE_LABELS - lobe_aliases = lobe_aliases or DEFAULT_LOBE_ALIASES - - key = lobe_name.strip().lower().replace(" ", "_") - - # Direct hit - if key in lobe_labels: - return lobe_labels[key] - - # Alias - canonical = lobe_aliases.get(key) - if canonical and canonical in lobe_labels: - return lobe_labels[canonical] - - raise KeyError( - f"Cannot resolve lobe '{lobe_name}' (normalised='{key}'). " - f"Known lobes: {list(lobe_labels.keys())}; aliases: {list(lobe_aliases.keys())}" - ) - - -# ── Target mask extraction ──────────────────────────────────────────────── - - -def extract_target_mask( - seg_data: np.ndarray, - insertion_lobe: str, - lobe_labels: dict | None = None, - lobe_aliases: dict | None = None, - lung_labels: list[int] | None = None, -) -> Tuple[np.ndarray, str]: - """Extract a binary mask for the target structure. - - Strategy: - 1. If the target lobe label exists in ``seg_data``, use it. - 2. Else if the target *side* (left/right) is identifiable, use the union - of that side's lobes as fallback. - 3. Else use the whole-lung mask (union of all lobe labels). - 4. If nothing found, return an empty mask. - - Parameters - ---------- - seg_data : ndarray - 3-D integer organ segmentation (canonical RAS+ space). - insertion_lobe : str - Target lobe from the manifest. - lobe_labels, lobe_aliases : dict, optional - lung_labels : list[int], optional - Label IDs that are considered "lung parenchyma". - - Returns - ------- - (mask, fallback_level) where *fallback_level* is one of - ``"lobe"``, ``"side"``, ``"lung"``, or ``"empty"``. - """ - lobe_labels = lobe_labels or DEFAULT_LOBE_LABELS - lobe_aliases = lobe_aliases or DEFAULT_LOBE_ALIASES - lung_labels = lung_labels or list(lobe_labels.values()) - - # Attempt exact lobe - try: - label_id = resolve_lobe_label(insertion_lobe, lobe_labels, lobe_aliases) - except KeyError: - label_id = None - - if label_id is not None and np.any(seg_data == label_id): - return (seg_data == label_id).astype(np.uint8), "lobe" - - # Fallback: side - key = insertion_lobe.strip().lower().replace(" ", "_") - canonical = lobe_aliases.get(key, key) - if "left" in canonical: - side_ids = [v for k, v in lobe_labels.items() if "left" in k] - elif "right" in canonical: - side_ids = [v for k, v in lobe_labels.items() if "right" in k] - else: - side_ids = [] - - if side_ids: - side_mask = np.isin(seg_data, side_ids).astype(np.uint8) - if side_mask.any(): - return side_mask, "side" - - # Fallback: whole lung - lung_mask = np.isin(seg_data, lung_labels).astype(np.uint8) - if lung_mask.any(): - return lung_mask, "lung" - - return np.zeros_like(seg_data, dtype=np.uint8), "empty" - - -# ── Bounding-box helpers ────────────────────────────────────────────────── - - -def mask_bounding_box(mask: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: - """Axis-aligned bounding box of nonzero voxels. - - Returns (mins, maxs) each of shape (ndim,). Raises ValueError on empty. - """ - nz = np.argwhere(mask > 0) - if nz.size == 0: - raise ValueError("Empty mask — no bounding box.") - return nz.min(axis=0), nz.max(axis=0) - - -# ── Core percentile → voxel ────────────────────────────────────────────── - - -def percentile_to_voxel( - target_mask: np.ndarray, - cc_pct: float, - ml_pct: float, - ap_pct: float, -) -> Tuple[int, int, int]: - """Convert lobe-relative percentile coordinates to an initial voxel index. - - In RAS+ canonical space: - axis 0 = mediolateral (R→L) ← ml_pct - axis 1 = anteroposterior (A→P) ← ap_pct - axis 2 = craniocaudal (I→S) ← cc_pct - - **Coordinate reliability notes (iTrialSpace schema)**: - - cc_pct: clean 0-100 percentile; used directly for the K axis. - - ml_pct / ap_pct: known pipeline-normalisation bug — 93 %+ of values - fall outside [0, 100] in real datasets. When either is outside the - valid range the function falls back to the lobe centroid at the target - CC slab for the I/J axes, ensuring the initial candidate always lands - inside (or very close to) the lobe. - - Returns (i, j, k) in canonical index space. The initial candidate is - guaranteed to land inside (or within a few voxels of) the target mask. - """ - mins, maxs = mask_bounding_box(target_mask) - - # ── K axis: map cc_pct through *occupied* slices only ──────────────── - # The bounding-box range [k_min, k_max] can span large internal gaps - # (e.g. post-surgical anatomy in NSCLCR where lobes are fragmented). - # Interpolating within the bounding box would map cc_pct into a void. - # Instead, collect the k-slices that actually contain lobe voxels and - # use cc_pct to index into that sorted array. This guarantees k0 - # always lands on a slice with lobe tissue. - cc_pct_clamped = max(0.0, min(100.0, cc_pct)) - k_occupied = np.unique(np.nonzero(target_mask)[2]) - if len(k_occupied) == 1: - k0 = int(k_occupied[0]) - else: - idx = cc_pct_clamped / 100.0 * (len(k_occupied) - 1) - k0 = int(k_occupied[int(round(idx))]) - - # ── I/J axes: use percentile only when both values are in [0, 100] ─── - # Outside that range the values are mm-scale artefacts from the upstream - # normalisation bug; in that case use the centroid of lobe voxels in the - # CC slab around k0 (robust fallback). - # - # Even when ml/ap are in-range, the bounding-box interpolation can land - # outside a non-convex lobe cross-section. We start from the - # interpolated position but snap (i0, j0) to the nearest actual lobe - # voxel in the CC slab so the candidate is always inside the mask. - k_lo = max(0, k0 - 5) - k_hi = min(target_mask.shape[2], k0 + 6) - slab = target_mask[:, :, k_lo:k_hi] - nz = np.argwhere(slab) - if len(nz) == 0: - # Should not happen now that k0 is on an occupied slice, but - # keep the whole-lobe fallback for safety. - nz = np.argwhere(target_mask) - - if 0.0 <= ml_pct <= 100.0 and 0.0 <= ap_pct <= 100.0: - # Bounding-box interpolation → snap to nearest slab voxel - i_raw = mins[0] + (ml_pct / 100.0) * (maxs[0] - mins[0]) - j_raw = mins[1] + (ap_pct / 100.0) * (maxs[1] - mins[1]) - dists2d = ((nz[:, 0] - i_raw) ** 2 + (nz[:, 1] - j_raw) ** 2) ** 0.5 - nearest = nz[int(dists2d.argmin())] - i0, j0 = int(nearest[0]), int(nearest[1]) - else: - # Pick the lobe voxel nearest to the centroid within the CC slab. - ci = float(nz[:, 0].mean()) - cj = float(nz[:, 1].mean()) - dists2d = ((nz[:, 0] - ci) ** 2 + (nz[:, 1] - cj) ** 2) ** 0.5 - nearest = nz[int(dists2d.argmin())] - i0, j0 = int(nearest[0]), int(nearest[1]) - - return (i0, j0, k0) - - -# ── Snap to nearest valid voxel ────────────────────────────────────────── - - -def snap_to_mask( - target_mask: np.ndarray, - ijk: Tuple[int, int, int], - max_radius: int = 25, -) -> Tuple[Tuple[int, int, int], float]: - """Snap *ijk* to the nearest voxel inside *target_mask*. - - Uses a distance-transform approach for efficiency: compute the Euclidean - distance from the candidate point to all True voxels and pick the closest. - - Parameters - ---------- - target_mask : ndarray (bool / uint8) - ijk : (i, j, k) - max_radius : int Search radius in voxels. - - Returns - ------- - ((i, j, k), dist) – snapped index and distance in voxels. - Returns (ijk, 0.0) if already inside. - Returns (None, inf) if no valid voxel within radius. - """ - i, j, k = ijk - # Clamp to array bounds - shape = target_mask.shape - ic = max(0, min(i, shape[0] - 1)) - jc = max(0, min(j, shape[1] - 1)) - kc = max(0, min(k, shape[2] - 1)) - - if target_mask[ic, jc, kc]: - return (ic, jc, kc), 0.0 - - # Extract a local cube around the candidate - lo = np.array([ic, jc, kc]) - max_radius - hi = np.array([ic, jc, kc]) + max_radius + 1 - lo_clamped = np.maximum(lo, 0) - hi_clamped = np.minimum(hi, shape) - - local_mask = target_mask[ - lo_clamped[0] : hi_clamped[0], - lo_clamped[1] : hi_clamped[1], - lo_clamped[2] : hi_clamped[2], - ] - - nz = np.argwhere(local_mask > 0) - if nz.size == 0: - return None, float("inf") # type: ignore[return-value] - - # Shift to global coords, compute distance - nz_global = nz + lo_clamped[None, :] - dists = np.linalg.norm(nz_global - np.array([ic, jc, kc])[None, :], axis=1) - best = int(np.argmin(dists)) - best_dist = float(dists[best]) - - if best_dist > max_radius: - return None, float("inf") # type: ignore[return-value] - - best_ijk = tuple(int(x) for x in nz_global[best]) - return best_ijk, best_dist # type: ignore[return-value] - - -# ── Pleural distance enforcement ───────────────────────────────────────── - - -def compute_pleural_distance_map( - lung_mask: np.ndarray, - voxel_spacing_mm: Tuple[float, float, float], -) -> np.ndarray: - """Euclidean distance transform from the lung boundary into the interior. - - Returns an array of same shape as *lung_mask* where each voxel stores - its distance (mm) to the nearest lung-boundary voxel. - Voxels outside the lung have distance 0. - """ - # Interior voxels = lung_mask > 0 - dist = ndimage.distance_transform_edt( - lung_mask.astype(bool), - sampling=voxel_spacing_mm, - ) - return dist.astype(np.float32) - - -def enforce_pleural_margin( - target_mask: np.ndarray, - pleural_map: np.ndarray, - ijk: Tuple[int, int, int], - min_dist_mm: float, - max_shift: int = 15, -) -> Tuple[Tuple[int, int, int], float]: - """Move *ijk* inward if it violates the pleural safety margin. - - Searches among target-mask voxels within *max_shift* for the closest - one that satisfies the margin. - - Returns (new_ijk, pleural_dist_mm). - """ - i, j, k = ijk - shape = target_mask.shape - ic = max(0, min(i, shape[0] - 1)) - jc = max(0, min(j, shape[1] - 1)) - kc = max(0, min(k, shape[2] - 1)) - - current_dist = float(pleural_map[ic, jc, kc]) - if current_dist >= min_dist_mm: - return (ic, jc, kc), current_dist - - # Search nearby for a valid voxel - lo = np.maximum(np.array([ic, jc, kc]) - max_shift, 0) - hi = np.minimum(np.array([ic, jc, kc]) + max_shift + 1, shape) - - local_mask = target_mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] - local_pleu = pleural_map[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] - - # Candidate voxels: inside target mask AND satisfying margin - candidates = np.argwhere((local_mask > 0) & (local_pleu >= min_dist_mm)) - if candidates.size == 0: - # Relax: just pick deepest voxel inside target mask within region - in_mask = np.argwhere(local_mask > 0) - if in_mask.size == 0: - return (ic, jc, kc), current_dist - pleu_vals = local_pleu[in_mask[:, 0], in_mask[:, 1], in_mask[:, 2]] - best = int(np.argmax(pleu_vals)) - g = tuple(int(x) for x in (in_mask[best] + lo)) - return g, float(pleu_vals[best]) # type: ignore[return-value] - - # Pick closest candidate to original point - cand_global = candidates + lo[None, :] - dists = np.linalg.norm( - cand_global - np.array([ic, jc, kc])[None, :], - axis=1, - ) - best = int(np.argmin(dists)) - g = tuple(int(x) for x in cand_global[best]) - pdist = float(pleural_map[g[0], g[1], g[2]]) - return g, pdist # type: ignore[return-value] - - -# ── Overlap / collision check ───────────────────────────────────────────── - - -def check_overlap( - existing_mask: np.ndarray | None, - donor_mask_host: np.ndarray, - max_fraction: float = 0.05, -) -> Tuple[float, bool]: - """Compute overlap fraction between a new donor mask and existing nodules. - - Returns (fraction, is_acceptable). - """ - if existing_mask is None: - return 0.0, True - donor_vox = donor_mask_host > 0 - n_donor = int(donor_vox.sum()) - if n_donor == 0: - return 0.0, True - # Defensive: skip overlap check if shapes don't match (different CT series) - if existing_mask.shape != donor_mask_host.shape: - return 0.0, True - overlap = int((donor_vox & (existing_mask > 0)).sum()) - frac = overlap / n_donor - return frac, frac <= max_fraction - - -def resolve_collision( - target_mask: np.ndarray, - existing_mask: np.ndarray, - ijk: Tuple[int, int, int], - max_shift: int = 15, - rng: np.random.Generator | None = None, -) -> Tuple[int, int, int] | None: - """Attempt to shift *ijk* to avoid collision with existing nodules. - - Returns a new center or None if no collision-free spot found. - """ - rng = rng or np.random.default_rng(42) - shape = target_mask.shape - i, j, k = ijk - - lo = np.maximum(np.array([i, j, k]) - max_shift, 0) - hi = np.minimum(np.array([i, j, k]) + max_shift + 1, shape) - - local_target = target_mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] - local_exist = existing_mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] - - candidates = np.argwhere((local_target > 0) & (local_exist == 0)) - if candidates.size == 0: - return None - - cand_global = candidates + lo[None, :] - dists = np.linalg.norm( - cand_global - np.array([i, j, k])[None, :], - axis=1, - ) - # Sort by distance, pick from top-5 with slight randomness for diversity - order = np.argsort(dists)[:5] - pick = rng.choice(order) - return tuple(int(x) for x in cand_global[pick]) # type: ignore[return-value] - - -# ── Deterministic RNG seed ──────────────────────────────────────────────── - - -def make_seed( - trial_name: str, - case_id: str, - nodule_idx: int = 0, - global_seed: int = 42, -) -> int: - """Derive a deterministic seed from case identifiers. - - Uses SHA-256 truncated to 32 bits, mixed with the global seed. - """ - h = hashlib.sha256(f"{trial_name}|{case_id}|{nodule_idx}|{global_seed}".encode()).hexdigest() - return int(h[:8], 16) & 0x7FFFFFFF - - -# ── Top-level placement orchestrator ────────────────────────────────────── - - -def compute_placement( - seg_data: np.ndarray, - affine: np.ndarray, - voxel_spacing_mm: Tuple[float, float, float], - insertion_lobe: str, - cc_pct: float, - ml_pct: float, - ap_pct: float, - config: PlacementConfig | None = None, - existing_combined_mask: np.ndarray | None = None, - lobe_labels: dict | None = None, - lobe_aliases: dict | None = None, - lung_labels: list[int] | None = None, - rng: np.random.Generator | None = None, -) -> PlacementResult: - """Full placement pipeline: percentile → voxel → snap → pleural → collision. - - Parameters - ---------- - seg_data : ndarray - Host organ segmentation in canonical RAS+ space. - affine : ndarray (4×4) - Canonical RAS+ affine (voxel → world mm). - voxel_spacing_mm : (sx, sy, sz) - Voxel dimensions in mm along each RAS+ axis. - insertion_lobe, cc_pct, ml_pct, ap_pct : float - Target from the manifest. - config : PlacementConfig - existing_combined_mask : ndarray, optional - Existing nodule mask in host space (for overlap checking). - lobe_labels, lobe_aliases, lung_labels : dict / list, optional - rng : numpy Generator, optional - - Returns - ------- - PlacementResult - """ - cfg = config or PlacementConfig() - result = PlacementResult() - - # 1. Extract target mask - target_mask, fallback = extract_target_mask( - seg_data, - insertion_lobe, - lobe_labels, - lobe_aliases, - lung_labels, - ) - if fallback == "empty": - result.is_feasible = False - result.reason = "No lung voxels found in organ segmentation." - return result - if fallback != "lobe": - result.warnings.append(f"Lobe not found; using {fallback} fallback.") - - # 2. Percentile → initial voxel - try: - ijk0 = percentile_to_voxel(target_mask, cc_pct, ml_pct, ap_pct) - except ValueError as e: - result.is_feasible = False - result.reason = f"Percentile mapping failed: {e}" - return result - - # 3. Snap to target mask - ijk, snap_dist = snap_to_mask(target_mask, ijk0, cfg.max_snap_radius_vox) - if ijk is None: - result.is_feasible = False - result.reason = ( - f"Cannot snap to target mask within {cfg.max_snap_radius_vox} vox " - f"(initial candidate {ijk0})." - ) - return result - if snap_dist > 0: - result.snapped = True - result.snap_distance_vox = snap_dist - result.warnings.append( - f"Snapped {snap_dist:.1f} vox from initial candidate {ijk0} to {ijk}." - ) - - # 4. Pleural margin - if cfg.min_pleural_dist_mm > 0: - # Build lung mask for pleural distance - all_lung_labels = lung_labels or list((lobe_labels or DEFAULT_LOBE_LABELS).values()) - lung_mask = np.isin(seg_data, all_lung_labels).astype(np.uint8) - if lung_mask.any(): - pleural_map = compute_pleural_distance_map(lung_mask, voxel_spacing_mm) - ijk, pdist = enforce_pleural_margin( - target_mask, - pleural_map, - ijk, - cfg.min_pleural_dist_mm, - max_shift=cfg.max_collision_shift_vox, - ) - result.pleural_dist_mm = pdist - if pdist < cfg.min_pleural_dist_mm: - result.warnings.append( - f"Pleural margin {pdist:.1f} mm < {cfg.min_pleural_dist_mm} mm; " - "could not fully satisfy margin." - ) - - # 5. Collision check (deferred until donor mask is placed) - # We record the center; collision is re-checked in the inserter after - # the donor mask is pasted. - - result.center_ijk = ijk - - # Convert to world coords - ijk_h = np.array([ijk[0], ijk[1], ijk[2], 1.0]) - world = affine @ ijk_h - result.center_world_mm = tuple(float(x) for x in world[:3]) # type: ignore[assignment] - - return result diff --git a/itrialspace/src/itrialspace/mask_inserter/resample.py b/itrialspace/src/itrialspace/mask_inserter/resample.py deleted file mode 100644 index 54411ea9d3553cb97f9e0ec934805e62ec1535b0..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/resample.py +++ /dev/null @@ -1,321 +0,0 @@ -# -*- coding: utf-8 -*- -""" -resample.py — Donor mask extraction, scaling/resampling into host -geometry, and binary cleanup. - -The resampling pipeline: - -1. Load donor nodule mask and canonicalise to RAS+. -2. Extract the largest connected component (in case of multi-label artifacts). -3. Build a SimpleITK similarity or affine transform that: - a. Scales the donor by the manifest scale_factor (isotropic or per-axis). - b. Translates the donor centre to the target insertion point in host space. -4. Resample the donor mask onto the host CT grid using nearest-neighbour. -5. Apply binary cleanup: threshold, remove small components, fill holes. -6. Return the mask as a numpy array matching host shape. -""" -from __future__ import annotations - -from dataclasses import dataclass -from typing import Tuple - -import nibabel as nib -import numpy as np -from scipy import ndimage - - -@dataclass -class ResampleConfig: - """Parameters governing resampling behaviour.""" - - interpolation: str = "nearest" # nearest | linear - binary_threshold: float = 0.5 - min_component_size_vox: int = 3 - fill_holes: bool = True - - -# ── NIfTI helpers ───────────────────────────────────────────────────────── - - -def load_nifti_canonical(path: str) -> Tuple[np.ndarray, np.ndarray, Tuple[float, ...]]: - """Load a NIfTI file, canonicalise to RAS+. - - Returns (data, affine_4x4, voxel_spacing). - """ - img = nib.load(path) - img_can = nib.as_closest_canonical(img) - data = np.asarray(img_can.dataobj) - aff = img_can.affine.copy() - spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) - return data, aff, spacing - - -def save_nifti( - data: np.ndarray, - affine: np.ndarray, - path: str, - *, - dtype: np.dtype | type = np.uint8, -) -> None: - """Save a numpy array as a NIfTI file (optionally compressed).""" - import os - - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - img = nib.Nifti1Image(data.astype(dtype), affine) - nib.save(img, path) - - -# ── Connected-component extraction ─────────────────────────────────────── - - -def largest_connected_component(mask: np.ndarray) -> np.ndarray: - """Extract the largest connected component from a binary mask. - - Returns a uint8 mask with only the largest component set to 1. - """ - binary = (mask > 0).astype(np.uint8) - labelled, n_labels = ndimage.label(binary) - if n_labels <= 1: - return binary - - sizes = ndimage.sum(binary, labelled, range(1, n_labels + 1)) - biggest = int(np.argmax(sizes)) + 1 - return (labelled == biggest).astype(np.uint8) - - -# ── Centre of mass ──────────────────────────────────────────────────────── - - -def mask_centre_of_mass(mask: np.ndarray) -> Tuple[float, float, float]: - """Centre of mass of nonzero voxels in voxel coordinates.""" - com = ndimage.center_of_mass(mask.astype(float)) - return (float(com[0]), float(com[1]), float(com[2])) - - -# ── Donor bounding-box crop ────────────────────────────────────────────── - - -def crop_to_bbox( - mask: np.ndarray, - padding: int = 2, -) -> Tuple[np.ndarray, Tuple[int, int, int]]: - """Crop a 3-D mask to its tight bounding box plus padding. - - Returns (cropped_mask, origin_offset_ijk). - """ - nz = np.argwhere(mask > 0) - if nz.size == 0: - return mask, (0, 0, 0) - lo = np.maximum(nz.min(axis=0) - padding, 0) - hi = np.minimum(nz.max(axis=0) + padding + 1, mask.shape) - cropped = mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] - return cropped, tuple(int(x) for x in lo) # type: ignore[return-value] - - -# ── Scipy-based resampling ─────────────────────────────────────────────── - - -def resample_donor_to_host( - donor_mask: np.ndarray, - donor_affine: np.ndarray, - donor_spacing: Tuple[float, float, float], - host_shape: Tuple[int, int, int], - host_affine: np.ndarray, - host_spacing: Tuple[float, float, float], - target_center_ijk: Tuple[int, int, int], - scale_factor: float = 1.0, - config: ResampleConfig | None = None, -) -> np.ndarray: - """Resample a donor mask into host space. - - Algorithm: - 1. Extract largest connected component from donor mask. - 2. Crop to tight bounding box. - 3. Scale the cropped mask using scipy.ndimage.zoom (if scale_factor != 1). - 4. Adjust voxel sizes: zoom each axis by donor_spacing/host_spacing so - the physical size is preserved when pasted into host voxel grid. - 5. Paste the (scaled) donor into host space centred at target_center_ijk. - 6. Binary cleanup. - - Returns a uint8 array of shape ``host_shape``. - """ - cfg = config or ResampleConfig() - - # ── Extract largest component and crop ──────────────────────────────── - donor_lcc = largest_connected_component(donor_mask) - cropped, _ = crop_to_bbox(donor_lcc, padding=1) - - # ── Compute effective zoom factors ──────────────────────────────────── - # Two reasons to zoom: - # a) scale_factor from the manifest (e.g. grow/shrink the nodule) - # b) spacing mismatch between donor and host voxel grids - zoom_factors = tuple(scale_factor * (ds / hs) for ds, hs in zip(donor_spacing, host_spacing)) - - needs_zoom = any(abs(z - 1.0) > 0.01 for z in zoom_factors) - - if needs_zoom: - zoomed = ndimage.zoom( - cropped.astype(np.float32), - zoom_factors, - order=1, - ) - zoomed = (zoomed >= 0.5).astype(np.uint8) - else: - zoomed = cropped - - # ── Paste into host space ───────────────────────────────────────────── - result = _paste_cropped(zoomed, host_shape, target_center_ijk) - - # ── Binary cleanup ──────────────────────────────────────────────────── - result = binary_cleanup(result, cfg) - - return result - - -def _paste_cropped( - cropped: np.ndarray, - host_shape: Tuple[int, int, int], - center_ijk: Tuple[int, int, int], -) -> np.ndarray: - """Paste a cropped donor mask into host space centred at center_ijk.""" - result = np.zeros(host_shape, dtype=np.uint8) - d_shape = np.array(cropped.shape) - center = np.array(center_ijk) - - # Compute destination region (donor centre-of-mass → target centre) - donor_com = np.array(ndimage.center_of_mass((cropped > 0).astype(float))) - offset = np.round(center - donor_com).astype(int) - - dst_lo = offset - dst_hi = offset + d_shape - - # Clip to host bounds - src_lo = np.maximum(-dst_lo, 0) - src_hi = d_shape - np.maximum(dst_hi - np.array(host_shape), 0) - dst_lo_c = np.maximum(dst_lo, 0) - dst_hi_c = np.minimum(dst_hi, np.array(host_shape)) - - if np.all(src_lo < src_hi) and np.all(dst_lo_c < dst_hi_c): - result[ - dst_lo_c[0] : dst_hi_c[0], - dst_lo_c[1] : dst_hi_c[1], - dst_lo_c[2] : dst_hi_c[2], - ] = cropped[ - src_lo[0] : src_hi[0], - src_lo[1] : src_hi[1], - src_lo[2] : src_hi[2], - ] - - return result - - -# ── Binary mask cleanup ────────────────────────────────────────────────── - - -def binary_cleanup(mask: np.ndarray, config: ResampleConfig | None = None) -> np.ndarray: - """Threshold, remove small components, optionally fill holes.""" - cfg = config or ResampleConfig() - - # Threshold - binary = (mask >= cfg.binary_threshold).astype(np.uint8) - - # Remove small connected components - if cfg.min_component_size_vox > 0: - labelled, n = ndimage.label(binary) - if n > 0: - sizes = ndimage.sum(binary, labelled, range(1, n + 1)) - for idx, size in enumerate(sizes, start=1): - if size < cfg.min_component_size_vox: - binary[labelled == idx] = 0 - - # Fill holes - if cfg.fill_holes: - binary = ndimage.binary_fill_holes(binary).astype(np.uint8) - - return binary - - -# ── Direct paste (fallback / no-scale path) ────────────────────────────── - - -def paste_donor_direct( - donor_mask: np.ndarray, - host_shape: Tuple[int, int, int], - target_center_ijk: Tuple[int, int, int], -) -> np.ndarray: - """Paste a donor mask directly into host space at the given centre. - - Used when scale_factor == 1.0 and donor/host have identical spacing, - so no resampling is needed — just a simple array copy with bounds - clipping. - - Returns a uint8 array of shape ``host_shape``. - """ - donor_lcc = largest_connected_component(donor_mask) - donor_com = mask_centre_of_mass(donor_lcc) - - # Compute the offset to align donor COM with target centre - offset = np.array(target_center_ijk) - np.array(donor_com) - offset = np.round(offset).astype(int) - - result = np.zeros(host_shape, dtype=np.uint8) - - # Compute source and destination slicing - nz = np.argwhere(donor_lcc > 0) - if nz.size == 0: - return result - - for idx in range(len(nz)): - i, j, k = nz[idx] + offset - if 0 <= i < host_shape[0] and 0 <= j < host_shape[1] and 0 <= k < host_shape[2]: - result[i, j, k] = 1 - - return result - - -# ── Efficient paste using array slicing ────────────────────────────────── - - -def paste_donor_array( - donor_mask: np.ndarray, - host_shape: Tuple[int, int, int], - target_center_ijk: Tuple[int, int, int], -) -> np.ndarray: - """Faster paste using array slicing rather than per-voxel iteration. - - Centres the donor mask at target_center_ijk in host space. - Returns a uint8 array of shape ``host_shape``. - """ - donor_lcc = largest_connected_component(donor_mask) - donor_com = np.array(mask_centre_of_mass(donor_lcc)) - target = np.array(target_center_ijk, dtype=float) - - # Shift = how much to move donor indices to align COM with target - shift = np.round(target - donor_com).astype(int) - - # Compute valid overlap region - d_shape = np.array(donor_lcc.shape) - h_shape = np.array(host_shape) - - # Donor index ranges in host space - dst_lo = shift - dst_hi = shift + d_shape - - # Clip to host bounds - src_lo = np.maximum(-dst_lo, 0) - src_hi = d_shape - np.maximum(dst_hi - h_shape, 0) - dst_lo_clipped = np.maximum(dst_lo, 0) - dst_hi_clipped = np.minimum(dst_hi, h_shape) - - result = np.zeros(host_shape, dtype=np.uint8) - - # Check for valid overlap - if np.all(src_lo < src_hi) and np.all(dst_lo_clipped < dst_hi_clipped): - donor_crop = donor_lcc[src_lo[0] : src_hi[0], src_lo[1] : src_hi[1], src_lo[2] : src_hi[2]] - result[ - dst_lo_clipped[0] : dst_hi_clipped[0], - dst_lo_clipped[1] : dst_hi_clipped[1], - dst_lo_clipped[2] : dst_hi_clipped[2], - ] = donor_crop - - return result diff --git a/itrialspace/src/itrialspace/mask_inserter/resolver_bridge.py b/itrialspace/src/itrialspace/mask_inserter/resolver_bridge.py deleted file mode 100644 index 09bc5a640c44ae2cdb6fba6b1e362d98e2c77088..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/resolver_bridge.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -""" -resolver_bridge.py — Thin adapter between iTrialSpace's PathResolver -and the mask insertion engine. - -The CohortManifest carries *relative* or *pre-resolved* paths in columns: - - host_ct_path, host_organ_seg_path, - donor_ct_path, donor_nodule_mask_path, donor_refined_seg_path - -If paths are already absolute and exist on disk, we use them directly. -Otherwise, we fall back to PathResolver for resolution. -""" -from __future__ import annotations - -import os -from dataclasses import dataclass -from pathlib import Path -from typing import Optional - -import pandas as pd - - -@dataclass -class ResolvedPaths: - """All paths needed for a single insertion row.""" - - host_ct: str - host_organ_seg: str - donor_ct: str - donor_nodule_mask: str - donor_refined_seg: str = "" - - def validate(self) -> list[str]: - """Return list of missing files (empty if all OK).""" - missing = [] - for label, p in [ - ("host_ct", self.host_ct), - ("host_organ_seg", self.host_organ_seg), - ("donor_nodule_mask", self.donor_nodule_mask), - ]: - if not p or not os.path.isfile(p): - missing.append(f"{label}: {p}") - # donor_ct is optional (only needed for CT-level insertion) - if self.donor_ct and not os.path.isfile(self.donor_ct): - missing.append(f"donor_ct: {self.donor_ct}") - return missing - - -class ResolverBridge: - """Resolve manifest row paths, using PathResolver when needed. - - Usage:: - - bridge = ResolverBridge(path_resolver=my_resolver) - # or without PathResolver (paths must all be absolute already): - bridge = ResolverBridge() - - resolved = bridge.resolve(manifest_row) - """ - - def __init__( - self, - path_resolver: Optional[object] = None, - base_dir: Optional[str] = None, - ): - """ - Args: - path_resolver: An iTrialSpace ``PathResolver`` instance (optional). - base_dir: Fallback base directory for relative-path resolution. - """ - self._resolver = path_resolver - self._base_dir = base_dir or "" - - def resolve(self, row: pd.Series) -> ResolvedPaths: - """Resolve all paths for a manifest row. - - Logic per column: - 1. If the column value is an absolute path and exists → use as-is. - 2. If a PathResolver is available → delegate resolution. - 3. Else prepend base_dir and hope for the best. - """ - return ResolvedPaths( - host_ct=self._resolve_one( - row.get("host_ct_path", ""), - "ct", - row.get("host_dataset", ""), - row, - ), - host_organ_seg=self._resolve_one( - row.get("host_organ_seg_path", ""), - "organ_seg", - row.get("host_dataset", ""), - row, - ), - donor_ct=self._resolve_one( - row.get("donor_ct_path", ""), - "ct", - row.get("donor_dataset", ""), - row, - ), - donor_nodule_mask=self._resolve_one( - row.get("donor_nodule_mask_path", ""), - "nodule_mask", - row.get("donor_dataset", ""), - row, - ), - donor_refined_seg=self._resolve_one( - row.get("donor_refined_seg_path", ""), - "refined_seg", - row.get("donor_dataset", ""), - row, - ), - ) - - def _resolve_one( - self, - raw_value: str, - kind: str, - dataset: str, - row: pd.Series, - ) -> str: - """Resolve a single path column value.""" - raw_value = str(raw_value).strip() if pd.notna(raw_value) else "" - if not raw_value: - return "" - - # 1. Already absolute and exists - if os.path.isabs(raw_value) and os.path.exists(raw_value): - return raw_value - - # 2. PathResolver delegation - if self._resolver is not None and dataset: - try: - resolved = self._try_path_resolver(raw_value, kind, dataset, row) - if resolved and os.path.exists(resolved): - return resolved - except (KeyError, AttributeError, TypeError): - pass # fall through - - # 3. base_dir join - if self._base_dir: - joined = os.path.join(self._base_dir, raw_value) - if os.path.exists(joined): - return joined - - # 4. Return raw (caller will validate) - return raw_value - - def _try_path_resolver( - self, - raw_value: str, - kind: str, - dataset: str, - row: pd.Series, - ) -> str: - """Attempt to resolve via PathResolver API.""" - r = self._resolver - if kind == "ct": - return r.resolve_ct_path(dataset, raw_value) # type: ignore[union-attr] - elif kind == "organ_seg": - ct_path = str( - row.get("host_ct_path", "") if "host" in kind else row.get("donor_ct_path", "") - ) - ct_id = _extract_ct_id(ct_path) - return r.resolve_organ_seg_path(dataset, ct_id) # type: ignore[union-attr] - elif kind == "nodule_mask": - ann_id = str(row.get("donor_annotation_id", "")) - ct_path = str(row.get("donor_ct_path", "")) - ct_id = _extract_ct_id(ct_path) - return r.resolve_nodule_mask_path(dataset, ann_id, ct_id) # type: ignore[union-attr] - elif kind == "refined_seg": - ct_path = str(row.get("donor_ct_path", "")) - ct_id = _extract_ct_id(ct_path) - return r.resolve_refined_seg_path(dataset, ct_id) # type: ignore[union-attr] - return raw_value - - -def _extract_ct_id(ct_path: str) -> str: - """Extract ct_id from a path — basename without .nii.gz.""" - basename = os.path.basename(ct_path) - if basename.endswith(".nii.gz"): - return basename[:-7] - return Path(basename).stem diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__init__.py b/itrialspace/src/itrialspace/mask_inserter/tools/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index effa5214f31518cd6b6a7403d4b14f954652b022..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/list_manifests.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/list_manifests.cpython-310.pyc deleted file mode 100644 index b979b98fa7172b5eb051f81bb62f507cc2fe7b60..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/list_manifests.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/make_test_manifest.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/make_test_manifest.cpython-310.pyc deleted file mode 100644 index 0e4b57020230335869a1c2fa90310faa31a0a410..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/make_test_manifest.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/list_manifests.py b/itrialspace/src/itrialspace/mask_inserter/tools/list_manifests.py deleted file mode 100644 index eb9f6567b836b998a5d33e5dd2c9db325c8b704d..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/tools/list_manifests.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -""" -list_manifests.py — Recursively find manifest CSV/JSON files in a directory -and write a manifest list file (one path per line) for use with SLURM array jobs. - -Usage: - python list_manifests.py --dir $ITRIALSPACE_DATA_DIR/.../manifests/mode2_size_detection_curve \ - --output manifests_mode2.txt - - python list_manifests.py --dir $ITRIALSPACE_DATA_DIR/.../manifests/mode7_bootstrap_confidence \ - --output manifests_mode7.txt \ - --pattern "*.csv" -""" -from __future__ import annotations - -import argparse -import os -import sys -from pathlib import Path - - -def find_manifests( - directory: str | Path, - pattern: str = "*.csv", - also_json: bool = True, - exclude_patterns: list[str] | None = None, -) -> list[Path]: - """ - Recursively find manifest files in *directory*. - - Parameters - ---------- - directory : str or Path - Root directory to search. - pattern : str - Glob pattern for manifest files (default: ``*.csv``). - also_json : bool - Also search for ``*.json`` in addition to *pattern*. - exclude_patterns : list of str, optional - Skip files whose name contains any of these substrings - (e.g., ``["audit", "log", "metadata"]``). - - Returns - ------- - list of Path - Sorted list of absolute paths to discovered manifest files. - """ - directory = Path(directory).resolve() - if not directory.is_dir(): - print(f"ERROR: Not a directory: {directory}", file=sys.stderr) - sys.exit(1) - - exclude = exclude_patterns or [ - "audit", - "metadata", - "log", - "README", - "_run_config", - ] - - results: list[Path] = [] - - # Collect matching files - for pat in [pattern] + (["*.json"] if also_json else []): - for p in directory.rglob(pat): - if not p.is_file(): - continue - # Skip known non-manifest files - if any(ex.lower() in p.name.lower() for ex in exclude): - continue - results.append(p) - - # Deduplicate (in case pattern already includes json) and sort - results = sorted(set(results)) - - # When both CSV and JSON exist for the same stem, keep only the CSV to - # prevent duplicate array tasks that race on the same output directory. - if also_json: - stems_with_csv = {p.stem for p in results if p.suffix == ".csv"} - results = [p for p in results if not (p.suffix == ".json" and p.stem in stems_with_csv)] - - return results - - -def write_manifest_list(manifests: list[Path], output_path: str | Path) -> None: - """Write one manifest path per line to *output_path*.""" - output_path = Path(output_path) - output_path.parent.mkdir(parents=True, exist_ok=True) - - with open(output_path, "w") as f: - for m in manifests: - f.write(str(m) + "\n") - - -def main(): - parser = argparse.ArgumentParser( - description="Find cohort manifest CSV/JSON files and write a list file " - "for use with SLURM array jobs.", - ) - parser.add_argument( - "--dir", - "-d", - required=True, - help="Directory to search recursively for manifest files.", - ) - parser.add_argument( - "--output", - "-o", - required=True, - help="Output file path (one manifest path per line).", - ) - parser.add_argument( - "--pattern", - default="*.csv", - help="Glob pattern for manifest files (default: *.csv).", - ) - parser.add_argument( - "--no-json", - action="store_true", - help="Do not also search for *.json files.", - ) - parser.add_argument( - "--exclude", - nargs="*", - default=None, - help="Substrings to exclude from filenames (default: audit, metadata, log, README).", - ) - parser.add_argument( - "--dry-run", - action="store_true", - help="Print found manifests but do not write the output file.", - ) - parser.add_argument( - "--quiet", - "-q", - action="store_true", - help="Suppress informational output (still prints errors/warnings).", - ) - - args = parser.parse_args() - - manifests = find_manifests( - directory=args.dir, - pattern=args.pattern, - also_json=not args.no_json, - exclude_patterns=args.exclude, - ) - - print(f"Directory: {os.path.abspath(args.dir)}") - print(f"Pattern: {args.pattern}" + (" + *.json" if not args.no_json else "")) - print(f"Found: {len(manifests)} manifest(s)") - print() - - if len(manifests) == 0: - print("WARNING: No manifests found. Check the directory path.", file=sys.stderr) - sys.exit(0) - - if not args.quiet: - for i, m in enumerate(manifests): - print(f" [{i:3d}] {m}") - - if args.dry_run: - if not args.quiet: - print(f"\n(dry-run) Would write to: {args.output}") - else: - write_manifest_list(manifests, args.output) - if not args.quiet: - print(f"\nWritten to: {args.output}") - print("\nTo submit as a SLURM array job:") - print(f" sbatch --array=0-{len(manifests) - 1} modeX_insert_masks_array.sub") - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/make_test_manifest.py b/itrialspace/src/itrialspace/mask_inserter/tools/make_test_manifest.py deleted file mode 100644 index 2b0c67d85d8590759ef54db0201d994ae3190092..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/mask_inserter/tools/make_test_manifest.py +++ /dev/null @@ -1,290 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -make_test_manifest.py — Generate a minimal test manifest (1–3 rows) -pointing to real host CTs and donor nodule masks on the server. - -Usage: - python itrialspace_mask_inserter/tools/make_test_manifest.py \ - --output $ITRIALSPACE_DATA_DIR/test_manifest.csv \ - [--base-dir $ITRIALSPACE_DATA_DIR] \ - [--n-rows 2] \ - [--dataset LUNA25] - -The script uses iTrialSpace's PathResolver to discover real data paths, -picks 1 host CT + 1 donor nodule from the specified (or first available) -dataset, and writes a CSV with absolute paths. -""" -from __future__ import annotations - -import argparse -import os -import sys -from pathlib import Path - -import numpy as np -import pandas as pd - - -def _find_project_root() -> str: - """Walk up from this script to find the itrialspace package root.""" - here = Path(__file__).resolve().parent - for candidate in [here.parent.parent, here.parent.parent.parent]: - if (candidate / "itrialspace" / "site" / "path_resolver.py").exists(): - return str(candidate) - return str(here.parent.parent) - - -def main(): - parser = argparse.ArgumentParser( - description="Generate a minimal test manifest for full-volume integration tests.", - ) - parser.add_argument( - "--output", - "-o", - required=True, - help="Output CSV path.", - ) - parser.add_argument( - "--base-dir", - default=None, - help="iTrialSpace data base directory. " "Default: $ITRIALSPACE_DATA_DIR", - ) - parser.add_argument( - "--dataset", - default=None, - help="Dataset to pick host/donor from (e.g. LUNA25, DLCS24). " - "Default: first dataset with available profile CSV.", - ) - parser.add_argument( - "--n-rows", - type=int, - default=2, - help="Number of manifest rows to generate (default: 2).", - ) - parser.add_argument( - "--seed", - type=int, - default=42, - help="Random seed for reproducible selection.", - ) - args = parser.parse_args() - - base_dir = args.base_dir or ( - os.environ.get("ITRIALSPACE_DATA_DIR") or os.path.expanduser("~/.itrialspace/data") - ) - - # Try to import PathResolver - project_root = _find_project_root() - sys.path.insert(0, project_root) - - try: - from itrialspace.site.path_resolver import PathResolver - - resolver = PathResolver(base_dir=base_dir) - print(f"PathResolver loaded. Base dir: {resolver.base_dir}") - print(f"Available datasets: {resolver.available_datasets}") - except Exception as e: - print(f"WARNING: Could not load PathResolver: {e}") - print("Falling back to manual path construction.") - resolver = None - - # Pick dataset - dataset = args.dataset - if dataset is None and resolver is not None: - dataset = _pick_dataset(resolver) - if dataset is None: - dataset = "LUNA25" - print(f"Using dataset: {dataset}") - - # Load profile CSV to find real nodules - rng = np.random.default_rng(args.seed) - rows = _build_rows(resolver, base_dir, dataset, args.n_rows, rng) - - if not rows: - print("ERROR: Could not build any manifest rows. Check data paths.") - sys.exit(1) - - df = pd.DataFrame(rows) - os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) - df.to_csv(args.output, index=False) - print(f"\nWrote {len(df)} rows to {args.output}") - print(df[["case_id", "host_ct_path", "donor_nodule_mask_path", "insertion_lobe"]].to_string()) - - -def _pick_dataset(resolver) -> str | None: - """Pick the first dataset that has a readable profile CSV.""" - for ds in resolver.available_datasets: - csv_path = resolver.resolve_profile_csv_path(ds) - if os.path.isfile(csv_path): - return ds - return None - - -def _build_rows( - resolver, - base_dir: str, - dataset: str, - n_rows: int, - rng: np.random.Generator, -) -> list[dict]: - """Build manifest rows from real data.""" - # Load profile to find nodule info - if resolver is not None: - profile_path = resolver.resolve_profile_csv_path(dataset) - else: - profile_path = os.path.join(base_dir, "profiles", f"{dataset}_nodule_profiles.csv") - - if not os.path.isfile(profile_path): - print(f"WARNING: Profile CSV not found at {profile_path}") - return _build_rows_manual(base_dir, dataset, n_rows, rng) - - print(f"Loading profile: {profile_path}") - prof = pd.read_csv(profile_path) - print(f" {len(prof)} nodules in {dataset}") - - # Filter to nodules with valid lobe data - valid = prof.dropna(subset=["ct_path"]) - if "reinsertion_lobe" in valid.columns: - valid = valid[valid["reinsertion_lobe"].notna()] - if len(valid) == 0: - print("WARNING: No valid nodules after filtering.") - return [] - - # Sample - n = min(n_rows, len(valid)) - sample = valid.sample(n=n, random_state=int(rng.integers(0, 2**31))) - - rows = [] - for idx, (_, nod) in enumerate(sample.iterrows()): - ct_path_rel = str(nod["ct_path"]) - ct_id = os.path.basename(ct_path_rel).replace(".nii.gz", "") - - # Resolve paths - if resolver is not None: - host_ct = resolver.resolve_ct_path(dataset, ct_path_rel) - host_seg = resolver.resolve_organ_seg_path(dataset, ct_id) - ann_id = str(nod.get("annotation_id", ct_id)) if "annotation_id" in nod.index else ct_id - donor_mask = resolver.resolve_nodule_mask_path(dataset, ann_id, ct_id) - else: - host_ct = os.path.join(base_dir, "raw_ct", ct_path_rel) - host_seg = os.path.join( - base_dir, "masks", dataset, "refined_seg", f"{ct_id}_seg.nii.gz" - ) - donor_mask = os.path.join(base_dir, "masks", dataset, "nodule_seg", f"{ct_id}.nii.gz") - - lobe = str(nod.get("reinsertion_lobe", nod.get("lobe_name", "right_lung_upper_lobe"))) - cc_pct = float(nod.get("reinsertion_lobe_cc_pct", nod.get("lobe_cc_pct", 50.0))) - ml_pct = float(nod.get("reinsertion_lobe_ml_pct", nod.get("lobe_ml_pct", 50.0))) - ap_pct = float(nod.get("reinsertion_lobe_ap_pct", nod.get("lobe_ap_pct", 50.0))) - - # Clamp percentiles to [0, 100] - cc_pct = max(0.0, min(100.0, cc_pct)) - ml_pct = max(0.0, min(100.0, ml_pct)) - ap_pct = max(0.0, min(100.0, ap_pct)) - - rows.append( - { - "case_id": f"test_case_{idx:03d}", - "nodule_idx": 0, - "is_primary_nodule": True, - "companion_group_id": "", - "trial_name": "integration_test", - "host_dataset": dataset, - "host_patient_id": ct_id, - "host_ct_path": host_ct, - "host_organ_seg_path": host_seg, - "donor_dataset": dataset, - "donor_annotation_id": ( - str(nod.get("annotation_id", ct_id)) if "annotation_id" in nod.index else ct_id - ), - "donor_patient_id": ct_id, - "donor_ct_path": host_ct, - "donor_nodule_mask_path": donor_mask, - "donor_refined_seg_path": "", - "insertion_lobe": lobe, - "insertion_lobe_cc_pct": cc_pct, - "insertion_lobe_ml_pct": ml_pct, - "insertion_lobe_ap_pct": ap_pct, - "insertion_mode": "profile_faithful", - "scale_factor": 1.0, - "warp_applied": "none", - "effective_diam_mm": float( - nod.get("reinsertion_nodule_diam_mm", nod.get("nodule_mean_diam_mm", 8.0)) - ), - "nodule_diam_mm": float(nod.get("nodule_mean_diam_mm", 8.0)), - "label": ( - int(nod["label"]) if "label" in nod.index and pd.notna(nod.get("label")) else 0 - ), - } - ) - - return rows - - -def _build_rows_manual( - base_dir: str, - dataset: str, - n_rows: int, - rng: np.random.Generator, -) -> list[dict]: - """Fallback: scan directories directly.""" - ct_dir = os.path.join(base_dir, "raw_ct", dataset) - if not os.path.isdir(ct_dir): - print(f"WARNING: CT directory not found: {ct_dir}") - return [] - - cts = [f for f in os.listdir(ct_dir) if f.endswith(".nii.gz")] - if not cts: - return [] - - rng.shuffle(cts) # type: ignore[arg-type] - rows = [] - for idx, ct_file in enumerate(cts[:n_rows]): - ct_id = ct_file.replace(".nii.gz", "") - rows.append( - { - "case_id": f"test_case_{idx:03d}", - "nodule_idx": 0, - "is_primary_nodule": True, - "companion_group_id": "", - "trial_name": "integration_test", - "host_dataset": dataset, - "host_patient_id": ct_id, - "host_ct_path": os.path.join(ct_dir, ct_file), - "host_organ_seg_path": os.path.join( - base_dir, - "masks", - dataset, - "refined_seg", - f"{ct_id}_seg.nii.gz", - ), - "donor_dataset": dataset, - "donor_annotation_id": ct_id, - "donor_patient_id": ct_id, - "donor_ct_path": os.path.join(ct_dir, ct_file), - "donor_nodule_mask_path": os.path.join( - base_dir, - "masks", - dataset, - "nodule_seg", - f"{ct_id}.nii.gz", - ), - "donor_refined_seg_path": "", - "insertion_lobe": "right_lung_upper_lobe", - "insertion_lobe_cc_pct": 50.0, - "insertion_lobe_ml_pct": 50.0, - "insertion_lobe_ap_pct": 50.0, - "insertion_mode": "profile_faithful", - "scale_factor": 1.0, - "warp_applied": "none", - "effective_diam_mm": 8.0, - "nodule_diam_mm": 8.0, - "label": 0, - } - ) - return rows - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/query/__init__.py b/itrialspace/src/itrialspace/query/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/query/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/query/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 16f99d21b7d96bd31c8217c2a992e10cf315f5f8..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/query/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/query/__pycache__/matcher.cpython-310.pyc b/itrialspace/src/itrialspace/query/__pycache__/matcher.cpython-310.pyc deleted file mode 100644 index 7a32d349a84133051d4f50eba4713f55a17d8540..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/query/__pycache__/matcher.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/query/__pycache__/query_api.cpython-310.pyc b/itrialspace/src/itrialspace/query/__pycache__/query_api.cpython-310.pyc deleted file mode 100644 index 01f52f597c70edb2f5e7e2c5f7e9523c44e73456..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/query/__pycache__/query_api.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/query/matcher.py b/itrialspace/src/itrialspace/query/matcher.py deleted file mode 100644 index 340cdea8f4de5240910d13640e8a207db397f5b3..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/query/matcher.py +++ /dev/null @@ -1,180 +0,0 @@ -""" -ReinsertionMatcher — given a target anatomy, find the best matching donor nodule. - -Uses the `reinsertion_*` columns (100% complete across all 8 datasets) -as the match space so no anatomical re-computation is needed at insert time. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Optional - -import pandas as pd - - -@dataclass -class ReinsertionTarget: - """ - Describes where you want to place a nodule in a target CT. - - Fields map directly to the reinsertion_* columns in the index. - Only `lobe` is required — all others are optional soft constraints. - """ - - lobe: str # required — e.g. 'right_lung_upper_lobe' - lobe_cc_pct: Optional[float] = None # craniocaudal % within lobe (0=apex, 100=base) - pleural_dist_mm: Optional[float] = None # desired pleural distance - diameter_mm: Optional[float] = None # desired nodule diameter - label: Optional[int] = None # 0=benign, 1=malignant, None=any - lung_zone: Optional[str] = None # 'upper_zone' | 'middle_zone' | 'lower_zone' - lung_side: Optional[str] = None # 'left' | 'right' - exclude_datasets: list[str] = field(default_factory=list) - include_datasets: list[str] = field(default_factory=list) # empty = all - - -@dataclass -class MatchResult: - """A single match result with its score.""" - - annotation_id: str - dataset: str - ct_path: str - score: float # lower = better match - lobe: str - diameter_mm: float - pleural_mm: Optional[float] - lobe_cc_pct: float - label: Optional[int] - row: pd.Series = field(repr=False) # full row for downstream use - - def __repr__(self) -> str: - lbl = {0: "benign", 1: "malignant", None: "unlabelled"}[self.label] - return ( - f"MatchResult(score={self.score:.3f} | {self.dataset} | " - f"{self.annotation_id} | {self.diameter_mm:.1f}mm | " - f"{self.lobe} | {lbl})" - ) - - -class ReinsertionMatcher: - """ - Anatomy-based nearest-neighbour matcher over the reinsertion index. - - Match score (lower = better): - - score = w_lobe * (0 if lobe matches else lobe_penalty) - + w_cc * |lobe_cc_pct - target.lobe_cc_pct| / 100 - + w_pleural * |pleural_dist_mm - target.pleural_dist_mm| / max_pleural - + w_diam * |diameter_mm - target.diameter_mm| / max_diam - - All weights and penalty values are configurable. - """ - - DEFAULT_WEIGHTS = { - "w_cc": 1.0, - "w_pleural": 0.8, - "w_diam": 0.6, - "lobe_penalty": 5.0, # added to score when lobe doesn't match - } - - def __init__(self, index, weights: Optional[dict] = None): - """ - Args: - index: NoduleIndex instance - weights: override default scoring weights - """ - from itrialspace.index.nodule_index import NoduleIndex - - if not isinstance(index, NoduleIndex): - raise TypeError("index must be a NoduleIndex") - self._df = index.df - self._w = {**self.DEFAULT_WEIGHTS, **(weights or {})} - - def find_best(self, target: ReinsertionTarget) -> Optional[MatchResult]: - """Return the single best matching nodule.""" - results = self.find_top_k(target, k=1) - return results[0] if results else None - - def find_top_k(self, target: ReinsertionTarget, k: int = 10) -> list[MatchResult]: - """Return the top-k matching nodules, sorted by score ascending.""" - candidates = self._filter_candidates(target) - if candidates.empty: - return [] - - scores = self._score(candidates, target) - candidates = candidates.copy() - candidates["_score"] = scores - candidates = candidates.nsmallest(k, "_score") - - results = [] - for _, row in candidates.iterrows(): - results.append( - MatchResult( - annotation_id=str(row.get("annotation_id", "")), - dataset=str(row.get("dataset", "")), - ct_path=str(row.get("ct_path", "")), - score=float(row["_score"]), - lobe=str(row.get("reinsertion_lobe", "")), - diameter_mm=float(row.get("reinsertion_nodule_diam_mm", 0)), - pleural_mm=row.get("reinsertion_pleural_dist_mm"), - lobe_cc_pct=float(row.get("reinsertion_lobe_cc_pct", 0)), - label=(int(row["label"]) if pd.notna(row.get("label")) else None), - row=row, - ) - ) - return results - - def _filter_candidates(self, target: ReinsertionTarget) -> pd.DataFrame: - """Apply hard filters before scoring.""" - mask = pd.Series(True, index=self._df.index) - - # Dataset filters - if target.exclude_datasets: - mask &= ~self._df["dataset"].isin(target.exclude_datasets) - if target.include_datasets: - mask &= self._df["dataset"].isin(target.include_datasets) - - # Label filter (hard) - if target.label is not None: - mask &= self._df["label"] == target.label - - # Zone filter (hard if specified) - if target.lung_zone: - mask &= self._df["reinsertion_lung_zone"] == target.lung_zone - - # Side filter (hard if specified) - if target.lung_side: - mask &= self._df["reinsertion_lung_side"] == target.lung_side - - return self._df[mask].copy() - - def _score(self, df: pd.DataFrame, target: ReinsertionTarget) -> pd.Series: - """Compute match score for each candidate row.""" - w = self._w - score = pd.Series(0.0, index=df.index) - - # Lobe match (soft penalty if no hard filter was applied) - lobe_match = df["reinsertion_lobe"] == target.lobe - score += (~lobe_match).astype(float) * w["lobe_penalty"] - - # Craniocaudal position within lobe - if target.lobe_cc_pct is not None: - cc_diff = (df["reinsertion_lobe_cc_pct"] - target.lobe_cc_pct).abs() / 100.0 - score += w["w_cc"] * cc_diff - - # Pleural distance - if target.pleural_dist_mm is not None: - max_p = max(df["reinsertion_pleural_dist_mm"].max(), 1.0) - pl_diff = ( - df["reinsertion_pleural_dist_mm"].fillna(max_p) - target.pleural_dist_mm - ).abs() / max_p - score += w["w_pleural"] * pl_diff - - # Diameter - if target.diameter_mm is not None: - max_d = max(df["reinsertion_nodule_diam_mm"].max(), 1.0) - d_diff = (df["reinsertion_nodule_diam_mm"] - target.diameter_mm).abs() / max_d - score += w["w_diam"] * d_diff - - return score diff --git a/itrialspace/src/itrialspace/query/query_api.py b/itrialspace/src/itrialspace/query/query_api.py deleted file mode 100644 index b58a8584f5bbe2a3fb528ad48337357875c64da9..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/query/query_api.py +++ /dev/null @@ -1,316 +0,0 @@ -""" -NoduleQuery — fluent builder API for querying the NoduleIndex. - -Usage: - results = ( - idx.query() - .datasets(['DLCS24', 'LUNA25']) - .label(1) - .lobe('right_lung_upper_lobe') - .diameter(min=8.0, max=20.0) - .pleural_distance(max=10.0) - .sample(n=100, seed=42) - .fetch() - ) -""" - -from __future__ import annotations - -from typing import Optional, Union - -import pandas as pd - -from itrialspace.core.profile import NoduleProfile -from itrialspace.site.spec import validate_dataset_names - - -class NoduleQuery: - """ - Fluent query builder. All filter methods return `self` for chaining. - Call `.fetch()` or `.count()` to execute. - """ - - def __init__(self, df: pd.DataFrame): - self._df = df - self._mask = pd.Series(True, index=df.index) - self._sample_n: Optional[int] = None - self._sample_seed: Optional[int] = None - - # ── Dataset filters ──────────────────────────────────────────────────────── - - def datasets(self, names: Union[str, list[str]]) -> "NoduleQuery": - """Include only these datasets.""" - if isinstance(names, str): - names = [names] - validate_dataset_names(names) - self._mask &= self._df["dataset"].isin(names) - return self - - def exclude_datasets(self, names: Union[str, list[str]]) -> "NoduleQuery": - """Exclude these datasets.""" - if isinstance(names, str): - names = [names] - self._mask &= ~self._df["dataset"].isin(names) - return self - - # ── Label filters ────────────────────────────────────────────────────────── - - def label(self, val: Optional[int]) -> "NoduleQuery": - """Filter by label: 0=benign, 1=malignant, None=unlabelled.""" - if val is None: - self._mask &= self._df["label"].isna() - else: - self._mask &= self._df["label"] == val - return self - - def labelled(self) -> "NoduleQuery": - """Only rows with a non-null label.""" - self._mask &= self._df["label"].notna() - return self - - # ── Anatomy filters ──────────────────────────────────────────────────────── - - def lobe(self, names: Union[str, list[str]]) -> "NoduleQuery": - """Filter by lobe_name.""" - if isinstance(names, str): - names = [names] - self._mask &= self._df["lobe_name"].isin(names) - return self - - def lung_side(self, side: str) -> "NoduleQuery": - """'left' or 'right'.""" - self._mask &= self._df["lung_side"] == side - return self - - def lung_zone(self, zone: Union[str, list[str]]) -> "NoduleQuery": - """'upper_zone', 'middle_zone', or 'lower_zone'.""" - if isinstance(zone, str): - zone = [zone] - self._mask &= self._df["lung_zone"].isin(zone) - return self - - def central_peripheral(self, val: str) -> "NoduleQuery": - """'central' or 'peripheral'.""" - self._mask &= self._df["central_peripheral"] == val - return self - - # ── Size filters ─────────────────────────────────────────────────────────── - - def diameter(self, min: Optional[float] = None, max: Optional[float] = None) -> "NoduleQuery": - """Filter by nodule_mean_diam_mm.""" - if min is not None: - self._mask &= self._df["nodule_mean_diam_mm"] >= min - if max is not None: - self._mask &= self._df["nodule_mean_diam_mm"] <= max - return self - - def volume(self, min: Optional[float] = None, max: Optional[float] = None) -> "NoduleQuery": - """Filter by nodule_vol_mm3.""" - if min is not None: - self._mask &= self._df["nodule_vol_mm3"].fillna(0) >= min - if max is not None: - self._mask &= self._df["nodule_vol_mm3"].fillna(0) <= max - return self - - # ── Distance filters ─────────────────────────────────────────────────────── - - def pleural_distance( - self, min: Optional[float] = None, max: Optional[float] = None - ) -> "NoduleQuery": - """Filter by pleural_distance_mm.""" - col = self._df["pleural_distance_mm"] - if min is not None: - self._mask &= col.fillna(999) >= min - if max is not None: - self._mask &= col.fillna(999) <= max - return self - - def airway_distance( - self, min: Optional[float] = None, max: Optional[float] = None - ) -> "NoduleQuery": - """Filter by airway_distance_mm.""" - col = self._df["airway_distance_mm"] - if min is not None: - self._mask &= col.fillna(999) >= min - if max is not None: - self._mask &= col.fillna(999) <= max - return self - - # ── Reinsertion filters (primary index — 100% complete) ──────────────────── - - def reinsertion_lobe(self, name: Union[str, list[str]]) -> "NoduleQuery": - """Filter by reinsertion_lobe.""" - if isinstance(name, str): - name = [name] - self._mask &= self._df["reinsertion_lobe"].isin(name) - return self - - def reinsertion_zone(self, zone: Union[str, list[str]]) -> "NoduleQuery": - """Filter by reinsertion_lung_zone.""" - if isinstance(zone, str): - zone = [zone] - self._mask &= self._df["reinsertion_lung_zone"].isin(zone) - return self - - def reinsertion_side(self, side: str) -> "NoduleQuery": - """Filter by reinsertion_lung_side.""" - self._mask &= self._df["reinsertion_lung_side"] == side - return self - - def reinsertion_diameter( - self, min: Optional[float] = None, max: Optional[float] = None - ) -> "NoduleQuery": - """Filter by reinsertion_nodule_diam_mm.""" - col = self._df["reinsertion_nodule_diam_mm"] - if min is not None: - self._mask &= col >= min - if max is not None: - self._mask &= col <= max - return self - - def reinsertion_pleural( - self, min: Optional[float] = None, max: Optional[float] = None - ) -> "NoduleQuery": - """Filter by reinsertion_pleural_dist_mm.""" - col = self._df["reinsertion_pleural_dist_mm"] - if min is not None: - self._mask &= col.fillna(999) >= min - if max is not None: - self._mask &= col.fillna(999) <= max - return self - - def reinsertion_cc_pct( - self, min: Optional[float] = None, max: Optional[float] = None - ) -> "NoduleQuery": - """Filter by reinsertion_lobe_cc_pct (craniocaudal position within lobe).""" - col = self._df["reinsertion_lobe_cc_pct"] - if min is not None: - self._mask &= col >= min - if max is not None: - self._mask &= col <= max - return self - - # ── Multi-nodule filters ───────────────────────────────────────────────── - - def n_nodules_in_patient( - self, min: Optional[int] = None, max: Optional[int] = None - ) -> "NoduleQuery": - """Filter by number of nodules in the source patient.""" - col = self._df["n_nodules_in_patient"] - if min is not None: - self._mask &= col >= min - if max is not None: - self._mask &= col <= max - return self - - # ── Sampling ─────────────────────────────────────────────────────────────── - - def sample(self, n: int, seed: Optional[int] = None) -> "NoduleQuery": - """Random sample of n results (applied at fetch time).""" - self._sample_n = n - self._sample_seed = seed - return self - - # ── Execute ──────────────────────────────────────────────────────────────── - - def fetch(self) -> pd.DataFrame: - """Execute query and return matching rows as a DataFrame.""" - result = self._df[self._mask].copy() - if self._sample_n is not None: - n = min(self._sample_n, len(result)) - result = result.sample(n=n, random_state=self._sample_seed) - return result.reset_index(drop=True) - - def count(self) -> int: - """Return count without fetching data.""" - return int(self._mask.sum()) - - def exists(self) -> bool: - """Return True if any rows match.""" - return self.count() > 0 - - def fetch_profiles(self) -> list[NoduleProfile]: - """ - Execute query and return matching rows as NoduleProfile objects. - Note: slower than fetch() — use for small result sets. - """ - from itrialspace.io.loader import _b, _f, _i, _s - - profiles = [] - for _, row in self.fetch().iterrows(): - ds = row.get("dataset", "unknown") - from itrialspace.core.schema import CORE_COLS - - core_set = set(CORE_COLS) | { - "ct_path", - "dataset", - "patient_id", - "annotation_id", - "label", - } - meta = {k: v for k, v in row.items() if k not in core_set and not k.startswith("_")} - p = NoduleProfile( - annotation_id=str(row.get("annotation_id", "")), - patient_id=str(row.get("patient_id", "")), - dataset=ds, - ct_path=_s(row.get("ct_path")), - label=_i(row.get("label")), - coord_x=_f(row.get("coordX"), 0.0), - coord_y=_f(row.get("coordY"), 0.0), - coord_z=_f(row.get("coordZ"), 0.0), - w=_f(row.get("w"), 0.0), - h=_f(row.get("h"), 0.0), - d=_f(row.get("d"), 0.0), - nodule_mean_diam_mm=_f(row.get("nodule_mean_diam_mm"), 0.0), - nodule_vol_mm3=_f(row.get("nodule_vol_mm3")), - lobe_name=_s(row.get("lobe_name"), "unknown"), - lung_side=_s(row.get("lung_side"), "unknown"), - lung_zone=_s(row.get("lung_zone"), "unknown"), - organ_label_id=_i(row.get("organ_label_id"), 0), - organ_label_name=_s(row.get("organ_label_name")), - central_peripheral=_s(row.get("central_peripheral"), "unknown"), - nearby_organs_10mm=_s(row.get("nearby_organs_10mm")) or None, - cranio_caudal_pct=_f(row.get("cranio_caudal_pct")), - mediolateral_pct=_f(row.get("mediolateral_pct")), - anteroposterior_pct=_f(row.get("anteroposterior_pct")), - lobe_cc_pct=_f(row.get("lobe_cc_pct")), - lobe_ml_pct=_f(row.get("lobe_ml_pct")), - lobe_ap_pct=_f(row.get("lobe_ap_pct")), - dist_to_trachea_mm=_f(row.get("dist_to_trachea_mm")), - dist_to_aorta_mm=_f(row.get("dist_to_aorta_mm")), - dist_to_heart_mm=_f(row.get("dist_to_heart_mm")), - dist_to_esophagus_mm=_f(row.get("dist_to_esophagus_mm")), - dist_to_pulmonary_vein_mm=_f(row.get("dist_to_pulmonary_vein_mm")), - dist_to_superior_vena_cava_mm=_f(row.get("dist_to_superior_vena_cava_mm")), - pleural_distance_mm=_f(row.get("pleural_distance_mm")), - airway_distance_mm=_f(row.get("airway_distance_mm")), - n_nodules_in_patient=_i(row.get("n_nodules_in_patient"), 1), - nearest_nodule_id=_s(row.get("nearest_nodule_id")) or None, - nearest_nodule_dist_mm=_f(row.get("nearest_nodule_dist_mm")), - nearest_dx_mm=_f(row.get("nearest_dx_mm")), - nearest_dy_mm=_f(row.get("nearest_dy_mm")), - nearest_dz_mm=_f(row.get("nearest_dz_mm")), - all_nodule_ids=_s(row.get("all_nodule_ids")) or None, - all_nodule_dists_mm=_s(row.get("all_nodule_dists_mm")) or None, - ipsilateral=_b(row.get("ipsilateral")), - nearest_same_lobe=_b(row.get("nearest_same_lobe")), - bilateral_distribution=_b(row.get("bilateral_distribution")) or False, - reinsertion_lobe=_s(row.get("reinsertion_lobe"), "unknown"), - reinsertion_lung_side=_s(row.get("reinsertion_lung_side"), "unknown"), - reinsertion_lung_zone=_s(row.get("reinsertion_lung_zone"), "unknown"), - reinsertion_lobe_cc_pct=_f(row.get("reinsertion_lobe_cc_pct"), 0.0), - reinsertion_lobe_ml_pct=_f(row.get("reinsertion_lobe_ml_pct"), 0.0), - reinsertion_lobe_ap_pct=_f(row.get("reinsertion_lobe_ap_pct"), 0.0), - reinsertion_lung_cc_pct=_f(row.get("reinsertion_lung_cc_pct"), 0.0), - reinsertion_lung_ml_pct=_f(row.get("reinsertion_lung_ml_pct"), 0.0), - reinsertion_lung_ap_pct=_f(row.get("reinsertion_lung_ap_pct"), 0.0), - reinsertion_pleural_dist_mm=_f(row.get("reinsertion_pleural_dist_mm")), - reinsertion_airway_dist_mm=_f(row.get("reinsertion_airway_dist_mm")), - reinsertion_nodule_diam_mm=_f(row.get("reinsertion_nodule_diam_mm"), 0.0), - meta=meta, - ) - profiles.append(p) - return profiles - - def __repr__(self) -> str: - return f"NoduleQuery(matching={self.count():,} rows)" diff --git a/itrialspace/src/itrialspace/site/__init__.py b/itrialspace/src/itrialspace/site/__init__.py deleted file mode 100644 index abfec7541a036754273f64ca304922c538a7bd85..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -iTrialSpace — Synthetic Imaging Trial Engine. - -Manufactures cohort manifests for synthetic CT trials on top of -the itrialspace nodule profile index. Supports 10 scientific trial modes -with multi-nodule companion inclusion. -""" - -from itrialspace.site import trial_modes -from itrialspace.site.cohort_builder import CohortBuilder -from itrialspace.site.insertion_planner import InsertionPlan, InsertionPlanner -from itrialspace.site.knowledge_base import TrialKnowledgeBase -from itrialspace.site.manifest import CohortManifest -from itrialspace.site.path_resolver import PathResolver -from itrialspace.site.sampling import DistributionSampler -from itrialspace.site.spec import ( - DemographicSpec, - InsertionSpec, - NoduleSpec, - SizeDistribution, - TrialSpec, -) -from itrialspace.site.validation import SpecValidator - -__all__ = [ - "TrialSpec", - "NoduleSpec", - "DemographicSpec", - "SizeDistribution", - "InsertionSpec", - "PathResolver", - "DistributionSampler", - "TrialKnowledgeBase", - "InsertionPlanner", - "InsertionPlan", - "CohortManifest", - "SpecValidator", - "CohortBuilder", - "trial_modes", -] diff --git a/itrialspace/src/itrialspace/site/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index a8fdaa58479365da92b9e154975a83f237e3dafc..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/cohort_builder.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/cohort_builder.cpython-310.pyc deleted file mode 100644 index 6fcd9c165a27fa922095e6674d07d3584fd02d21..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/cohort_builder.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/insertion_planner.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/insertion_planner.cpython-310.pyc deleted file mode 100644 index 3e3be66026fcff4432aecaa7351522b110222c4a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/insertion_planner.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/knowledge_base.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/knowledge_base.cpython-310.pyc deleted file mode 100644 index 96876ecc129d6c06ced14316247acf1f6d335730..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/knowledge_base.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/manifest.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/manifest.cpython-310.pyc deleted file mode 100644 index c82b4038f49e7b95c7acb7a996eb391e0056e8c5..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/manifest.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/path_resolver.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/path_resolver.cpython-310.pyc deleted file mode 100644 index 3fd0774b345309fea8e0e4f2fa214e21fefa4973..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/path_resolver.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/sampling.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/sampling.cpython-310.pyc deleted file mode 100644 index 55a4a2445074a7450909938b10a932821b0b569f..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/sampling.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/spec.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/spec.cpython-310.pyc deleted file mode 100644 index b3769138852bd4f217dbcb36a2750497856a3470..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/spec.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/trial_modes.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/trial_modes.cpython-310.pyc deleted file mode 100644 index 6d83c82f9ed69fd1dcc63821827a0a94b4804d6c..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/trial_modes.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/validation.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/validation.cpython-310.pyc deleted file mode 100644 index 70f2677543ecc2772ee98e7f8b0552699ab7b677..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/site/__pycache__/validation.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/site/cohort_builder.py b/itrialspace/src/itrialspace/site/cohort_builder.py deleted file mode 100644 index 9d0c78877848d0c30c41456faebae6bf2d18aabe..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/cohort_builder.py +++ /dev/null @@ -1,1536 +0,0 @@ -""" -CohortBuilder — the main orchestrator. - -Resolves a TrialSpec into a CohortManifest by: -1. Validating the spec -2. Selecting nodule and host pools via NoduleQuery -3. Assigning labels and sizes -4. Pairing hosts with donors (native/matched/synthetic) -5. Planning insertions -6. Resolving file paths -7. Assembling the manifest -""" - -from __future__ import annotations - -import os -import warnings -from typing import Optional - -import numpy as np -import pandas as pd - -from itrialspace.index.nodule_index import NoduleIndex -from itrialspace.query.matcher import ReinsertionMatcher, ReinsertionTarget -from itrialspace.site.insertion_planner import InsertionPlanner -from itrialspace.site.manifest import CohortManifest -from itrialspace.site.path_resolver import PathResolver -from itrialspace.site.sampling import DistributionSampler, _diameter_to_bucket -from itrialspace.site.spec import ( - HISTOPATH_DATASETS, - LABEL_SOURCE_MAP, - POPULATION_TYPE_MAP, - SCREENING_DATASETS, - DigitalTwinCompleteSpec, - DigitalTwinCrossSpec, - DigitalTwinIsolationSpec, - TrialSpec, -) -from itrialspace.site.validation import SpecValidator - -# Demographics column mapping per dataset (meta column names → manifest columns) -_DEMO_COL_MAP: dict[str, dict[str, str]] = { - "DLCS24": { - "Age": "patient_age", - "Sex": "patient_sex", - "Smoking Status (Current/Former/Never/Unknown)": "smoking_status", - }, - "LUNA25": {"age": "patient_age", "gender": "patient_sex"}, - "IMDCT": {}, - "NSCLCR": {}, - "LUNGx": {}, - "LNDbv4": {}, - "LUNA16": {}, -} - - -class CohortBuilder: - """Resolves a TrialSpec into a CohortManifest.""" - - def __init__(self, index: NoduleIndex, path_resolver: PathResolver): - self._index = index - self._resolver = path_resolver - self._matcher = ReinsertionMatcher(index) - self._planner = InsertionPlanner(index.df) - - def build(self, spec: TrialSpec, verbose: bool = True) -> CohortManifest: - """Main entry point: TrialSpec → CohortManifest. - - If spec.n_bootstrap > 1, returns the first bootstrap replicate. - Use build_all() for multiple replicates. - """ - # Validate - validator = SpecValidator(self._index.df) - errors = validator.validate(spec) - if errors: - raise ValueError("Invalid TrialSpec:\n" + "\n".join(f" - {e}" for e in errors)) - - if verbose: - report = validator.feasibility_report(spec) - if report["warnings"]: - for w in report["warnings"]: - warnings.warn(f"iTrialSpace feasibility: {w}") - print( - f"Pool: {report['pool_size']} nodules | " - f"Malignant: {report['malignant_pool']} | " - f"Benign: {report['benign_pool']}" - ) - - rng = np.random.default_rng(spec.seed) - - # Build based on mode - if spec.cohort_mode == "native": - rows = self._build_native(spec, rng, verbose) - elif spec.cohort_mode == "matched": - rows = self._build_matched(spec, rng, verbose) - elif spec.cohort_mode == "synthetic": - rows = self._build_synthetic(spec, rng, verbose) - else: - raise ValueError(f"Unknown cohort_mode: {spec.cohort_mode}") - - df = pd.DataFrame(rows) - return CohortManifest(df, spec) - - def build_all(self, spec: TrialSpec, verbose: bool = False) -> list[CohortManifest]: - """Build multiple bootstrap replicates.""" - manifests = [] - for i in range(spec.n_bootstrap): - boot_spec = TrialSpec( - **{ - **spec.__dict__, - "seed": spec.seed + i, - } - ) - manifest = self.build(boot_spec, verbose=verbose) - # Tag bootstrap_id - manifest.df["bootstrap_id"] = i - manifests.append(manifest) - return manifests - - # ── Mode: Native ────────────────────────────────────────────────────────── - - def _build_native(self, spec: TrialSpec, rng: np.random.Generator, verbose: bool) -> list[dict]: - """Patient + their own nodule. No cross-patient mixing.""" - pool = self._select_nodule_pool(spec) - - if spec.malignancy_prevalence is not None: - pool = self._sample_by_prevalence(pool, spec, rng) - else: - pool = self._sample_pool(pool, spec.n_cases, rng) - - rows = [] - for case_id, (_, nod) in enumerate(pool.iterrows()): - case_rows = self._build_case_rows( - case_id=case_id, - spec=spec, - donor_row=nod, - host_row=nod, # same patient - target_diam_mm=None, - rng=rng, - ) - rows.extend(case_rows) - - return rows - - # ── Mode: Matched ───────────────────────────────────────────────────────── - - def _build_matched( - self, spec: TrialSpec, rng: np.random.Generator, verbose: bool - ) -> list[dict]: - """Host CT + anatomically-matched donor nodule via ReinsertionMatcher.""" - host_pool = self._select_host_pool(spec) - donor_pool = self._select_nodule_pool(spec) - - # Sample target sizes - target_sizes = self._sample_target_sizes(spec, rng) - - # Sample labels - labels = self._sample_label_assignments(spec, rng) - - # Sample hosts - n = spec.n_cases - if len(host_pool) < n: - host_indices = rng.choice(len(host_pool), size=n, replace=True) - else: - host_indices = rng.choice(len(host_pool), size=n, replace=False) - - rows = [] - for case_id in range(n): - host_row = host_pool.iloc[host_indices[case_id]] - target_diam = target_sizes[case_id] if target_sizes is not None else None - label = labels[case_id] if labels is not None else None - - # Build reinsertion target for matching - target = ReinsertionTarget( - lobe=str(host_row.get("reinsertion_lobe", "right_lung_upper_lobe")), - lobe_cc_pct=float(host_row.get("reinsertion_lobe_cc_pct", 50)), - diameter_mm=target_diam, - label=label, - include_datasets=spec.donor_datasets or [], - exclude_datasets=spec.exclude_datasets or [], - ) - - match = self._matcher.find_best(target) - if match is None: - # Fallback: relax label constraint - target.label = None - match = self._matcher.find_best(target) - - if match is None: - if verbose: - warnings.warn(f"Case {case_id}: no donor found, skipping") - continue - - case_rows = self._build_case_rows( - case_id=case_id, - spec=spec, - donor_row=match.row, - host_row=host_row, - target_diam_mm=target_diam, - rng=rng, - label_override=label, - ) - rows.extend(case_rows) - - return rows - - # ── Mode: Synthetic ─────────────────────────────────────────────────────── - - def _build_synthetic( - self, spec: TrialSpec, rng: np.random.Generator, verbose: bool - ) -> list[dict]: - """Any nodule + any host CT, paired independently.""" - donor_pool = self._select_nodule_pool(spec) - host_pool = self._select_host_pool(spec) - - target_sizes = self._sample_target_sizes(spec, rng) - labels = self._sample_label_assignments(spec, rng) - - n = spec.n_cases - - rows = [] - for case_id in range(n): - label = labels[case_id] if labels is not None else None - target_diam = target_sizes[case_id] if target_sizes is not None else None - - # Select donor matching label and size - donor_row = self._find_donor(donor_pool, label, target_diam, rng) - if donor_row is None: - if verbose: - warnings.warn(f"Case {case_id}: no suitable donor, skipping") - continue - - # Select host randomly - host_idx = rng.integers(0, len(host_pool)) - host_row = host_pool.iloc[host_idx] - - case_rows = self._build_case_rows( - case_id=case_id, - spec=spec, - donor_row=donor_row, - host_row=host_row, - target_diam_mm=target_diam, - rng=rng, - label_override=label, - ) - rows.extend(case_rows) - - return rows - - # ── Pool selection ──────────────────────────────────────────────────────── - - def _filter_missing_masks( - self, - pool: pd.DataFrame, - dataset: str, - verbose: bool = True, - ) -> pd.DataFrame: - """Drop rows whose nodule mask file does not exist on disk. - - This prevents downstream insertion failures caused by annotations - in the NoduleIndex that lack a corresponding segmentation mask - (upstream data gap). Skipped when the mask directory doesn't exist - (e.g. in unit-test environments with synthetic data). - """ - mask_dir = os.path.join(self._resolver._base_dir, "masks", dataset, "nodule_seg") - if not os.path.isdir(mask_dir): - return pool - - mask_exists = pool.apply( - lambda row: os.path.isfile( - self._resolver.resolve_nodule_mask_path( - dataset, - str(row["annotation_id"]), - ct_id=PathResolver.extract_ct_id(str(row.get("ct_path", ""))), - ) - ), - axis=1, - ) - n_missing = (~mask_exists).sum() - if n_missing > 0 and verbose: - dropped = pool.loc[~mask_exists, "annotation_id"].tolist() - print(f" ⚠ Dropped {n_missing} annotation(s) with missing nodule masks: " f"{dropped}") - return pool[mask_exists].reset_index(drop=True) - - def _select_nodule_pool(self, spec: TrialSpec) -> pd.DataFrame: - """Use NoduleQuery to build the donor nodule pool.""" - q = self._index.query() - - # Dataset constraints - ds = spec.donor_datasets or spec.source_datasets - if ds: - q = q.datasets(ds) - if spec.exclude_datasets: - q = q.exclude_datasets(spec.exclude_datasets) - - # Training exclusion — remove datasets the model was trained on - if spec.exclude_training_datasets: - q = q.exclude_datasets(spec.exclude_training_datasets) - - # Nodule spec constraints - ns = spec.nodule_spec - if ns: - if ns.diameter_range: - q = q.reinsertion_diameter(min=ns.diameter_range[0], max=ns.diameter_range[1]) - if ns.lobe: - q = q.reinsertion_lobe(ns.lobe) - if ns.zone: - q = q.reinsertion_zone(ns.zone) - if ns.side: - q = q.reinsertion_side(ns.side) - if ns.pleural_distance_range: - q = q.reinsertion_pleural( - min=ns.pleural_distance_range[0], - max=ns.pleural_distance_range[1], - ) - if ns.exclude_all_malignant_datasets: - q = q.exclude_datasets(["NSCLCR"]) - - # Label source filter: histopathology, radiology, or all - if ns.label_source and ns.label_source != "all": - allowed = LABEL_SOURCE_MAP.get(ns.label_source) - if allowed: - q = q.datasets(allowed) - elif ns.require_histopath_label: # deprecated fallback - q = q.datasets(HISTOPATH_DATASETS) - - # Population type filter: screening, diagnostic, or all - if ns.population_type and ns.population_type != "all": - allowed = POPULATION_TYPE_MAP.get(ns.population_type) - if allowed: - q = q.datasets(allowed) - - # Multi-nodule filter - if ns.n_nodules_filter == "single_only": - q = q.n_nodules_in_patient(min=1, max=1) - elif ns.n_nodules_filter == "multi_only": - q = q.n_nodules_in_patient(min=2) - - pool = q.fetch() - - # Filter out annotations whose mask files are missing on disk. - # This prevents deterministic Stage-2 failures for all build paths - # (modes 1-10 synthetic/matched/native AND digital-twin modes). - if hasattr(self, "_resolver") and hasattr(self._resolver, "_base_dir"): - datasets = pool["dataset"].unique() if "dataset" in pool.columns else [] - parts = [] - for ds in datasets: - ds_mask = pool["dataset"] == ds - ds_pool = pool[ds_mask] - filtered = self._filter_missing_masks(ds_pool, ds, verbose=True) - parts.append(filtered) - if parts: - pool = pd.concat(parts, ignore_index=True) - - return pool - - def _select_host_pool(self, spec: TrialSpec) -> pd.DataFrame: - """Select unique patient CTs for the host pool.""" - q = self._index.query() - - ds = spec.host_datasets or spec.source_datasets - if ds: - q = q.datasets(ds) - if spec.exclude_datasets: - q = q.exclude_datasets(spec.exclude_datasets) - - # Training exclusion — remove datasets the model was trained on - if spec.exclude_training_datasets: - q = q.exclude_datasets(spec.exclude_training_datasets) - - # Population type filter applies to hosts too - ns = spec.nodule_spec - if ns and ns.population_type and ns.population_type != "all": - allowed = POPULATION_TYPE_MAP.get(ns.population_type) - if allowed: - q = q.datasets(allowed) - - pool = q.fetch() - # Deduplicate to one row per patient (first nodule row) - pool = pool.drop_duplicates(subset=["patient_id", "ct_path"], keep="first") - - # Filter out hosts whose organ segmentation file is missing on disk. - # This prevents deterministic Stage-2 "Failed to load organ seg" errors. - if hasattr(self, "_resolver") and hasattr(self._resolver, "_base_dir"): - - def _has_organ_seg(row): - seg_path = self._resolver.resolve_organ_seg_path( - str(row.get("dataset", "")), - PathResolver.extract_ct_id(str(row.get("ct_path", ""))), - ) - return os.path.isfile(seg_path) - - seg_exists = pool.apply(_has_organ_seg, axis=1) - n_missing = (~seg_exists).sum() - if n_missing > 0: - dropped_ids = pool.loc[~seg_exists, "patient_id"].tolist() - print( - f" \u26a0 Dropped {n_missing} host(s) with missing organ " - f"segmentations: {dropped_ids}" - ) - pool = pool[seg_exists].reset_index(drop=True) - - return pool.reset_index(drop=True) - - # ── Sampling helpers ────────────────────────────────────────────────────── - - def _sample_by_prevalence( - self, pool: pd.DataFrame, spec: TrialSpec, rng: np.random.Generator - ) -> pd.DataFrame: - """Sample from pool respecting malignancy prevalence.""" - prev = spec.malignancy_prevalence - if prev is None: - return self._sample_pool(pool, spec.n_cases, rng) - - n = spec.n_cases - n_mal = int(round(n * prev)) - n_ben = n - n_mal - - mal_pool = pool[pool["label"] == 1] - ben_pool = pool[pool["label"] == 0] - - mal_n = min(n_mal, len(mal_pool)) - ben_n = min(n_ben, len(ben_pool)) - - mal_sample = ( - mal_pool.sample(n=mal_n, random_state=rng.integers(2**31)) - if mal_n > 0 - else mal_pool.iloc[:0] - ) - ben_sample = ( - ben_pool.sample(n=ben_n, random_state=rng.integers(2**31)) - if ben_n > 0 - else ben_pool.iloc[:0] - ) - - result = pd.concat([mal_sample, ben_sample], ignore_index=True) - return result.sample(frac=1, random_state=rng.integers(2**31)).reset_index(drop=True) - - def _sample_pool(self, pool: pd.DataFrame, n: int, rng: np.random.Generator) -> pd.DataFrame: - """Simple random sample from pool.""" - replace = len(pool) < n - return pool.sample(n=n, replace=replace, random_state=rng.integers(2**31)).reset_index( - drop=True - ) - - def _sample_target_sizes( - self, spec: TrialSpec, rng: np.random.Generator - ) -> Optional[np.ndarray]: - """Sample target diameters from spec if size distribution is defined.""" - ns = spec.nodule_spec - if ns and ns.size_distribution: - sd = ns.size_distribution - if sd.bucket_weights: - return DistributionSampler.sample_size_from_buckets( - sd.bucket_weights, spec.n_cases, rng - ) - elif sd.mean_log_mm is not None and sd.std_log_mm is not None: - return DistributionSampler.sample_size_lognormal( - spec.n_cases, sd.mean_log_mm, sd.std_log_mm, sd.min_mm, sd.max_mm, rng - ) - return None - - def _sample_label_assignments( - self, spec: TrialSpec, rng: np.random.Generator - ) -> Optional[np.ndarray]: - """Sample label assignments from prevalence.""" - if spec.malignancy_prevalence is not None: - return DistributionSampler.sample_labels(spec.n_cases, spec.malignancy_prevalence, rng) - return None - - def _find_donor( - self, - pool: pd.DataFrame, - label: Optional[int], - target_diam: Optional[float], - rng: np.random.Generator, - ) -> Optional[pd.Series]: - """Find a suitable donor nodule from the pool.""" - candidates = pool - - # Filter by label - if label is not None: - label_match = candidates[candidates["label"] == label] - if len(label_match) > 0: - candidates = label_match - - # Filter by size (within 50% tolerance for initial search) - if target_diam is not None and len(candidates) > 5: - lo = target_diam * 0.5 - hi = target_diam * 2.0 - size_match = candidates[ - (candidates["reinsertion_nodule_diam_mm"] >= lo) - & (candidates["reinsertion_nodule_diam_mm"] <= hi) - ] - if len(size_match) > 0: - candidates = size_match - - if len(candidates) == 0: - return None - - idx = rng.integers(0, len(candidates)) - return candidates.iloc[idx] - - # ── Companion resolution ───────────────────────────────────────────────── - - def _resolve_companions( - self, - primary_row: pd.Series, - spec: TrialSpec, - ) -> list[pd.Series]: - """Find companion nodules from the same donor patient. - - Uses the all_nodule_ids field (comma-delimited annotation IDs) - to look up sibling nodules in the index DataFrame. - - Returns list of pd.Series rows (excluding the primary itself). - Skipped in native mode (nodules already exist in the CT). - """ - if spec.companion_strategy == "none": - return [] - if spec.cohort_mode == "native": - return [] - - all_ids_str = primary_row.get("all_nodule_ids") - if pd.isna(all_ids_str) or not all_ids_str: - return [] - - all_ids = [aid.strip() for aid in str(all_ids_str).split(",")] - primary_id = str(primary_row.get("annotation_id", "")) - companion_ids = [aid for aid in all_ids if aid and aid != primary_id] - - if not companion_ids: - return [] - - # Look up companions in the full index - idx_df = self._index.df - companions = idx_df[idx_df["annotation_id"].isin(companion_ids)] - - # Apply strategy filter - if spec.companion_strategy == "ipsilateral": - primary_side = primary_row.get("reinsertion_lung_side", "") - companions = companions[companions["reinsertion_lung_side"] == primary_side] - elif spec.companion_strategy == "same_lobe": - primary_lobe = primary_row.get("reinsertion_lobe", "") - companions = companions[companions["reinsertion_lobe"] == primary_lobe] - # "all_companions" → no further filter - - return [row for _, row in companions.iterrows()] - - # ── Case row assembly ───────────────────────────────────────────────────── - - def _build_case_rows( - self, - case_id: int, - spec: TrialSpec, - donor_row: pd.Series, - host_row: pd.Series, - target_diam_mm: Optional[float], - rng: np.random.Generator, - label_override: Optional[int] = None, - ) -> list[dict]: - """Assemble manifest rows for a case, including any companions.""" - primary = self._build_single_row( - case_id=case_id, - spec=spec, - donor_row=donor_row, - host_row=host_row, - target_diam_mm=target_diam_mm, - rng=rng, - label_override=label_override, - nodule_idx=0, - is_primary=True, - ) - rows = [primary] - - # Resolve companions - companions = self._resolve_companions(donor_row, spec) - for i, comp_row in enumerate(companions): - comp = self._build_single_row( - case_id=case_id, - spec=spec, - donor_row=comp_row, - host_row=host_row, - target_diam_mm=None, # companions keep original size - rng=rng, - label_override=None, # companions keep their own label - nodule_idx=i + 1, - is_primary=False, - ) - rows.append(comp) - - # Set n_nodules_in_case on all rows - n = len(rows) - for r in rows: - r["n_nodules_in_case"] = n - r["companion_group_id"] = case_id - - return rows - - def _build_single_row( - self, - case_id: int, - spec: TrialSpec, - donor_row: pd.Series, - host_row: pd.Series, - target_diam_mm: Optional[float], - rng: np.random.Generator, - label_override: Optional[int] = None, - nodule_idx: int = 0, - is_primary: bool = True, - ) -> dict: - """Assemble a single manifest row.""" - # Insertion planning - plan = self._planner.plan( - nodule_row=donor_row, - mode=spec.insertion_mode, - target_diam_mm=target_diam_mm, - insertion_spec=spec.insertion_spec, - rng=rng, - ) - - # Path resolution - host_ds = str(host_row.get("dataset", "")) - donor_ds = str(donor_row.get("dataset", "")) - host_ct_rel = str(host_row.get("ct_path", "")) - donor_ct_rel = str(donor_row.get("ct_path", "")) - donor_ann_id = str(donor_row.get("annotation_id", "")) - host_ct_id = PathResolver.extract_ct_id(host_ct_rel) - donor_ct_id = PathResolver.extract_ct_id(donor_ct_rel) - - # Label - if label_override is not None: - label = label_override - else: - raw_label = donor_row.get("label") - label = int(raw_label) if pd.notna(raw_label) else None - - # Diameter - donor_diam = float(donor_row.get("reinsertion_nodule_diam_mm", 0)) - effective_diam = plan.effective_diam_mm if plan.effective_diam_mm > 0 else donor_diam - - # Size bucket - size_bucket = _diameter_to_bucket(effective_diam) if effective_diam > 0 else "" - - # Population type and label source - population_type = "screening" if donor_ds in SCREENING_DATASETS else "diagnostic" - label_source = "histopathology" if donor_ds in HISTOPATH_DATASETS else "radiology" - - # Demographics extraction - patient_age, patient_sex, smoking_status, pack_years = self._extract_demographics( - host_row, host_ds - ) - - return { - # Case identity - "case_id": case_id, - "nodule_idx": nodule_idx, - "is_primary_nodule": is_primary, - "n_nodules_in_case": 1, # updated by _build_case_rows - "companion_group_id": case_id, # updated by _build_case_rows - "trial_name": spec.trial_name, - "trial_template": spec.trial_template or "", - "bootstrap_id": 0, - # Host CT - "host_patient_id": str(host_row.get("patient_id", "")), - "host_dataset": host_ds, - "host_ct_path": self._resolver.resolve_ct_path(host_ds, host_ct_rel), - "host_organ_seg_path": self._resolver.resolve_organ_seg_path(host_ds, host_ct_id), - # Donor nodule - "donor_patient_id": str(donor_row.get("patient_id", "")), - "donor_annotation_id": donor_ann_id, - "donor_dataset": donor_ds, - "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( - donor_ds, donor_ann_id, ct_id=donor_ct_id - ), - "donor_ct_path": self._resolver.resolve_ct_path(donor_ds, donor_ct_rel), - "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( - donor_ds, donor_ct_id - ), - # Insertion - "insertion_coord_x": plan.insertion_coord_x, - "insertion_coord_y": plan.insertion_coord_y, - "insertion_coord_z": plan.insertion_coord_z, - "insertion_lobe": plan.insertion_lobe, - "insertion_lobe_cc_pct": plan.insertion_lobe_cc_pct, - "insertion_lobe_ml_pct": plan.insertion_lobe_ml_pct, - "insertion_lobe_ap_pct": plan.insertion_lobe_ap_pct, - "insertion_mode": plan.insertion_mode, - # Nodule characteristics - "nodule_diam_mm": donor_diam, - "effective_diam_mm": effective_diam, - "scale_factor": plan.scale_factor, - "warp_applied": plan.warp_applied, - "label": label, - # Anatomy - "nodule_lobe_name": str(donor_row.get("reinsertion_lobe", "")), - "nodule_lung_side": str(donor_row.get("reinsertion_lung_side", "")), - "nodule_lung_zone": str(donor_row.get("reinsertion_lung_zone", "")), - "nodule_central_peripheral": str(donor_row.get("central_peripheral", "")), - "pleural_distance_mm": donor_row.get("reinsertion_pleural_dist_mm"), - # Demographics - "patient_age": patient_age, - "patient_sex": patient_sex, - "smoking_status": smoking_status, - "pack_years": pack_years, - # Cohort metadata - "cohort_mode": spec.cohort_mode, - "size_bucket": size_bucket, - "population_type": population_type, - "label_source": label_source, - } - - @staticmethod - def _extract_demographics( - row: pd.Series, dataset: str - ) -> tuple[Optional[float], Optional[str], Optional[str], Optional[float]]: - """Extract demographics from meta columns (best-effort).""" - col_map = _DEMO_COL_MAP.get(dataset, {}) - - age = None - sex = None - smoking = None - pack_years = None - - for src_col, tgt in col_map.items(): - val = row.get(src_col) - if pd.isna(val) if isinstance(val, float) else (val is None): - continue - if tgt == "patient_age": - try: - age = float(val) - except (ValueError, TypeError): - pass - elif tgt == "patient_sex": - sex = str(val) - elif tgt == "smoking_status": - smoking = str(val) - elif tgt == "pack_years": - try: - pack_years = float(val) - except (ValueError, TypeError): - pass - - return age, sex, smoking, pack_years - - # ── Digital twin isolation ──────────────────────────────────────────────── - - def build_digital_twin_isolation( - self, - spec: DigitalTwinIsolationSpec, - verbose: bool = True, - ) -> CohortManifest: - """Build a digital twin isolation manifest. - - For each CT scan in the dataset, generates one isolation case - per native nodule. Each case pairs the host's clean anatomy mask - with exactly one native nodule mask. - - Matching is at the CT-scan level: a nodule is only paired with - the CT it was originally annotated from. Patients with multiple - CT scans produce separate cases per CT (not grouped by patient). - - Returns a CohortManifest whose DataFrame uses the extended - ISOLATION_MANIFEST_COLS schema. - """ - from itrialspace.site.sampling import _diameter_to_bucket - - rng = np.random.default_rng(spec.seed) - dataset = spec.dataset - - # 1. Select nodule pool from the target dataset - q = self._index.query().datasets([dataset]) - - # Apply nodule-level filters - ns = spec.nodule_spec - if ns: - if ns.label is not None: - q = q.label(ns.label) - if ns.diameter_range: - lo, hi = ns.diameter_range - if lo is not None: - q = q.reinsertion_diameter(min=lo) - if hi is not None: - q = q.reinsertion_diameter(max=hi) - - pool = q.fetch() - - # Filter out annotations whose mask files are missing on disk - pool = self._filter_missing_masks(pool, dataset, verbose=verbose) - - if len(pool) == 0: - raise ValueError( - f"No eligible nodules found in dataset '{dataset}' with the given filters." - ) - - # 2. Group by patient (for user-facing selection), then by CT scan - grouped_by_patient = pool.groupby("patient_id") - all_patient_ids = sorted(grouped_by_patient.groups.keys()) - - total_eligible_patients = len(all_patient_ids) - total_eligible_nodules = len(pool) - - # 3. Select patients - if spec.all_patients: - selected_ids = all_patient_ids - else: - n = min(spec.max_patients, total_eligible_patients) - indices = rng.choice(total_eligible_patients, size=n, replace=False) - indices.sort() - selected_ids = [all_patient_ids[i] for i in indices] - - total_selected_patients = len(selected_ids) - - # Gather nodules for selected patients, then group by ct_path - selected_pool = pool[pool["patient_id"].isin(selected_ids)] - grouped_by_ct = selected_pool.groupby("ct_path") - total_eligible_cts = len(grouped_by_ct) - - if verbose: - print(f"Dataset: {dataset}") - print(f" Eligible patients: {total_eligible_patients}") - print(f" Selected patients: {total_selected_patients}") - print(f" CT scans (selected): {total_eligible_cts}") - print(f" Eligible nodules (total pool): {total_eligible_nodules}") - - # 4. Build isolation cases — group by CT scan, not patient - rows = [] - case_id = 0 - - for ct_path_key in sorted(grouped_by_ct.groups.keys()): - ct_nodules = grouped_by_ct.get_group(ct_path_key).reset_index(drop=True) - host_n_nodules = len(ct_nodules) - patient_id = ct_nodules.iloc[0]["patient_id"] - - # Optionally cap nodules per patient - if spec.max_nodules_per_patient is not None: - ct_nodules = ct_nodules.head(spec.max_nodules_per_patient) - - for iso_idx, (_, nod) in enumerate(ct_nodules.iterrows()): - ct_rel = str(nod.get("ct_path", "")) - ct_id = PathResolver.extract_ct_id(ct_rel) - ann_id = str(nod.get("annotation_id", "")) - donor_diam = float(nod.get("reinsertion_nodule_diam_mm", 0)) - size_bucket = _diameter_to_bucket(donor_diam) if donor_diam > 0 else "" - - raw_label = nod.get("label") - label_val = int(raw_label) if pd.notna(raw_label) else None - - population_type = "screening" if dataset in SCREENING_DATASETS else "diagnostic" - label_source = "histopathology" if dataset in HISTOPATH_DATASETS else "radiology" - - patient_age, patient_sex, smoking_status, pack_years = self._extract_demographics( - nod, dataset - ) - - host_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) - donor_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) - - # Safety: host and donor must reference the same CT scan - assert host_ct_abs == donor_ct_abs, ( - f"CT mismatch: host={host_ct_abs} != donor={donor_ct_abs} " - f"for annotation {ann_id}" - ) - - row = { - # Case identity - "case_id": case_id, - "nodule_idx": 0, - "is_primary_nodule": True, - "n_nodules_in_case": 1, - "companion_group_id": case_id, - "trial_name": spec.trial_name, - "trial_template": "", - "bootstrap_id": 0, - # Host CT (same CT scan as the nodule) - "host_patient_id": str(patient_id), - "host_dataset": dataset, - "host_ct_path": host_ct_abs, - "host_organ_seg_path": self._resolver.resolve_organ_seg_path(dataset, ct_id), - # Donor = same CT scan's nodule (native) - "donor_patient_id": str(patient_id), - "donor_annotation_id": ann_id, - "donor_dataset": dataset, - "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( - dataset, ann_id, ct_id=ct_id - ), - "donor_ct_path": donor_ct_abs, - "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( - dataset, ct_id - ), - # Insertion — use nodule's own reinsertion coords (profile_faithful) - "insertion_coord_x": float(nod.get("coordX", 0)), - "insertion_coord_y": float(nod.get("coordY", 0)), - "insertion_coord_z": float(nod.get("coordZ", 0)), - "insertion_lobe": str(nod.get("reinsertion_lobe", "")), - "insertion_lobe_cc_pct": float(nod.get("reinsertion_lobe_cc_pct", 0)), - "insertion_lobe_ml_pct": float(nod.get("reinsertion_lobe_ml_pct", 0)), - "insertion_lobe_ap_pct": float(nod.get("reinsertion_lobe_ap_pct", 0)), - "insertion_mode": "profile_faithful", - # Nodule characteristics - "nodule_diam_mm": donor_diam, - "effective_diam_mm": donor_diam, - "scale_factor": 1.0, - "warp_applied": "none", - "label": label_val, - # Anatomy - "nodule_lobe_name": str(nod.get("reinsertion_lobe", "")), - "nodule_lung_side": str(nod.get("reinsertion_lung_side", "")), - "nodule_lung_zone": str(nod.get("reinsertion_lung_zone", "")), - "nodule_central_peripheral": str(nod.get("central_peripheral", "")), - "pleural_distance_mm": nod.get("reinsertion_pleural_dist_mm"), - # Demographics - "patient_age": patient_age, - "patient_sex": patient_sex, - "smoking_status": smoking_status, - "pack_years": pack_years, - # Cohort metadata - "cohort_mode": "native", - "size_bucket": size_bucket, - "population_type": population_type, - "label_source": label_source, - # Digital twin isolation columns - "mode": "digital_twin_isolation", - "target_annotation_id": ann_id, - "target_nodule_mask_path": self._resolver.resolve_nodule_mask_path( - dataset, ann_id, ct_id=ct_id - ), - "target_diameter_mm": donor_diam, - "target_label": label_val, - "target_lobe": str(nod.get("reinsertion_lobe", "")), - "target_side": str(nod.get("reinsertion_lung_side", "")), - "target_zone": str(nod.get("reinsertion_lung_zone", "")), - "host_n_nodules": host_n_nodules, - "isolation_case_index": iso_idx, - } - rows.append(row) - case_id += 1 - - total_generated = len(rows) - - if verbose: - print(f" Generated isolation cases: {total_generated}") - print("\nSummary:") - print(f" Total eligible patients: {total_eligible_patients}") - print(f" Total selected patients: {total_selected_patients}") - print(f" Total CT scans: {total_eligible_cts}") - print(f" Total eligible nodules: {total_eligible_nodules}") - print(f" Total generated cases: {total_generated}") - - df = pd.DataFrame(rows) - - # Create a lightweight TrialSpec wrapper for CohortManifest compatibility - wrapper_spec = TrialSpec( - trial_name=spec.trial_name, - n_cases=total_generated, - cohort_mode="native", - seed=spec.seed, - source_datasets=[dataset], - base_dir=spec.base_dir, - ) - - return CohortManifest(df, wrapper_spec) - - # ── Digital twin complete ───────────────────────────────────────────────── - - def build_digital_twin_complete( - self, - spec: DigitalTwinCompleteSpec, - verbose: bool = True, - ) -> CohortManifest: - """Build a digital twin complete manifest. - - For each CT scan in the dataset, generates ONE case containing - ALL native nodules from that CT. Rows sharing a case_id are processed - sequentially by Stage 2 (insert_manifest), accumulating into one - combined conditioning mask per CT scan. - - Matching is at the CT-scan level: a nodule is only paired with - the CT it was originally annotated from. Patients with multiple - CT scans produce one case per CT (not one case per patient). - - Returns a CohortManifest whose DataFrame uses the extended - COMPLETE_MANIFEST_COLS schema. - """ - from itrialspace.site.sampling import _diameter_to_bucket - - rng = np.random.default_rng(spec.seed) - dataset = spec.dataset - - # 1. Select nodule pool from the target dataset - q = self._index.query().datasets([dataset]) - - # Apply nodule-level filters - ns = spec.nodule_spec - if ns: - if ns.label is not None: - q = q.label(ns.label) - if ns.diameter_range: - lo, hi = ns.diameter_range - if lo is not None: - q = q.reinsertion_diameter(min=lo) - if hi is not None: - q = q.reinsertion_diameter(max=hi) - - pool = q.fetch() - - # Filter out annotations whose mask files are missing on disk - pool = self._filter_missing_masks(pool, dataset, verbose=verbose) - - if len(pool) == 0: - raise ValueError( - f"No eligible nodules found in dataset '{dataset}' with the given filters." - ) - - # 2. Group by patient (for user-facing selection), then by CT scan - grouped_by_patient = pool.groupby("patient_id") - all_patient_ids = sorted(grouped_by_patient.groups.keys()) - - total_eligible_patients = len(all_patient_ids) - total_eligible_nodules = len(pool) - - # 3. Select patients - if spec.all_patients: - selected_ids = all_patient_ids - else: - n = min(spec.max_patients, total_eligible_patients) - indices = rng.choice(total_eligible_patients, size=n, replace=False) - indices.sort() - selected_ids = [all_patient_ids[i] for i in indices] - - total_selected_patients = len(selected_ids) - - # Gather nodules for selected patients, then group by ct_path - selected_pool = pool[pool["patient_id"].isin(selected_ids)] - grouped_by_ct = selected_pool.groupby("ct_path") - total_eligible_cts = len(grouped_by_ct) - - if verbose: - print(f"Dataset: {dataset}") - print(f" Eligible patients: {total_eligible_patients}") - print(f" Selected patients: {total_selected_patients}") - print(f" CT scans (selected): {total_eligible_cts}") - print(f" Eligible nodules (total pool): {total_eligible_nodules}") - - # 4. Build complete cases — one case_id per CT scan, one row per nodule - rows = [] - case_id = 0 - total_nodules = 0 - - for ct_path_key in sorted(grouped_by_ct.groups.keys()): - ct_nodules = grouped_by_ct.get_group(ct_path_key).reset_index(drop=True) - n_nodules = len(ct_nodules) - total_nodules += n_nodules - patient_id = ct_nodules.iloc[0]["patient_id"] - - # Collect per-CT summary lists for the case-level columns - ann_ids_list = [] - diams_list = [] - labels_list = [] - lobes_list = [] - sides_list = [] - zones_list = [] - - for _, nod in ct_nodules.iterrows(): - ann_ids_list.append(str(nod.get("annotation_id", ""))) - diams_list.append(str(round(float(nod.get("reinsertion_nodule_diam_mm", 0)), 2))) - raw_label = nod.get("label") - labels_list.append(str(int(raw_label)) if pd.notna(raw_label) else "") - lobes_list.append(str(nod.get("reinsertion_lobe", ""))) - sides_list.append(str(nod.get("reinsertion_lung_side", ""))) - zones_list.append(str(nod.get("reinsertion_lung_zone", ""))) - - # Semicolon-delimited summary strings - ann_ids_str = ";".join(ann_ids_list) - diams_str = ";".join(diams_list) - labels_str = ";".join(labels_list) - lobes_str = ";".join(lobes_list) - sides_str = ";".join(sides_list) - zones_str = ";".join(zones_list) - - for nod_idx, (_, nod) in enumerate(ct_nodules.iterrows()): - ct_rel = str(nod.get("ct_path", "")) - ct_id = PathResolver.extract_ct_id(ct_rel) - ann_id = str(nod.get("annotation_id", "")) - donor_diam = float(nod.get("reinsertion_nodule_diam_mm", 0)) - size_bucket = _diameter_to_bucket(donor_diam) if donor_diam > 0 else "" - - raw_label = nod.get("label") - label_val = int(raw_label) if pd.notna(raw_label) else None - - population_type = "screening" if dataset in SCREENING_DATASETS else "diagnostic" - label_source = "histopathology" if dataset in HISTOPATH_DATASETS else "radiology" - - patient_age, patient_sex, smoking_status, pack_years = self._extract_demographics( - nod, dataset - ) - - host_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) - donor_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) - - # Safety: host and donor must reference the same CT scan - assert host_ct_abs == donor_ct_abs, ( - f"CT mismatch: host={host_ct_abs} != donor={donor_ct_abs} " - f"for annotation {ann_id}" - ) - - row = { - # Case identity — same case_id for all nodules in this CT - "case_id": case_id, - "nodule_idx": nod_idx, - "is_primary_nodule": nod_idx == 0, - "n_nodules_in_case": n_nodules, - "companion_group_id": case_id, - "trial_name": spec.trial_name, - "trial_template": "", - "bootstrap_id": 0, - # Host CT (same CT scan as the nodule) - "host_patient_id": str(patient_id), - "host_dataset": dataset, - "host_ct_path": host_ct_abs, - "host_organ_seg_path": self._resolver.resolve_organ_seg_path(dataset, ct_id), - # Donor = same CT scan's nodule (native) - "donor_patient_id": str(patient_id), - "donor_annotation_id": ann_id, - "donor_dataset": dataset, - "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( - dataset, ann_id, ct_id=ct_id - ), - "donor_ct_path": donor_ct_abs, - "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( - dataset, ct_id - ), - # Insertion — profile_faithful at native coordinates - "insertion_coord_x": float(nod.get("coordX", 0)), - "insertion_coord_y": float(nod.get("coordY", 0)), - "insertion_coord_z": float(nod.get("coordZ", 0)), - "insertion_lobe": str(nod.get("reinsertion_lobe", "")), - "insertion_lobe_cc_pct": float(nod.get("reinsertion_lobe_cc_pct", 0)), - "insertion_lobe_ml_pct": float(nod.get("reinsertion_lobe_ml_pct", 0)), - "insertion_lobe_ap_pct": float(nod.get("reinsertion_lobe_ap_pct", 0)), - "insertion_mode": "profile_faithful", - # Nodule characteristics - "nodule_diam_mm": donor_diam, - "effective_diam_mm": donor_diam, - "scale_factor": 1.0, - "warp_applied": "none", - "label": label_val, - # Anatomy - "nodule_lobe_name": str(nod.get("reinsertion_lobe", "")), - "nodule_lung_side": str(nod.get("reinsertion_lung_side", "")), - "nodule_lung_zone": str(nod.get("reinsertion_lung_zone", "")), - "nodule_central_peripheral": str(nod.get("central_peripheral", "")), - "pleural_distance_mm": nod.get("reinsertion_pleural_dist_mm"), - # Demographics - "patient_age": patient_age, - "patient_sex": patient_sex, - "smoking_status": smoking_status, - "pack_years": pack_years, - # Cohort metadata - "cohort_mode": "native", - "size_bucket": size_bucket, - "population_type": population_type, - "label_source": label_source, - # Digital twin complete columns - "mode": "digital_twin_complete", - "host_n_nodules": n_nodules, - "annotation_ids": ann_ids_str, - "diameters_mm": diams_str, - "labels": labels_str, - "lobes": lobes_str, - "sides": sides_str, - "zones": zones_str, - } - rows.append(row) - - case_id += 1 - - total_generated_cases = case_id - total_rows = len(rows) - - if verbose: - print(f" Generated cases: {total_generated_cases}") - print(f" Total manifest rows: {total_rows}") - print("\nSummary:") - print(f" Total eligible patients: {total_eligible_patients}") - print(f" Total selected patients: {total_selected_patients}") - print(f" Total CT scans: {total_eligible_cts}") - print(f" Total nodules: {total_nodules}") - print(f" Total generated cases: {total_generated_cases}") - - df = pd.DataFrame(rows) - - # Create a lightweight TrialSpec wrapper for CohortManifest compatibility - wrapper_spec = TrialSpec( - trial_name=spec.trial_name, - n_cases=total_generated_cases, - cohort_mode="native", - seed=spec.seed, - source_datasets=[dataset], - base_dir=spec.base_dir, - ) - - return CohortManifest(df, wrapper_spec) - - # ── Digital twin cross ──────────────────────────────────────────────────── - - def build_digital_twin_cross( - self, - spec: DigitalTwinCrossSpec, - verbose: bool = True, - ) -> CohortManifest: - """Build a digital twin cross manifest. - - Pairs host anatomy from one patient/dataset with donor nodule(s) - from a *different* patient/dataset. Supports three pairing - policies and two donor transfer modes. - - Returns a CohortManifest whose DataFrame uses the extended - CROSS_MANIFEST_COLS schema. - """ - - rng = np.random.default_rng(spec.seed) - - # ── 1. Build host pool ─────────────────────────────────────────── - host_q = self._index.query().datasets([spec.host_dataset]) - if spec.exclude_training_datasets: - host_q = host_q.exclude_datasets(spec.exclude_training_datasets) - host_pool = host_q.fetch() - # Deduplicate to one row per host patient - host_pool = host_pool.drop_duplicates( - subset=["patient_id", "ct_path"], keep="first" - ).reset_index(drop=True) - - total_eligible_hosts = len(host_pool) - if total_eligible_hosts == 0: - raise ValueError(f"No eligible host patients in dataset '{spec.host_dataset}'.") - - # Select hosts - if spec.all_host_patients: - selected_hosts = host_pool - else: - n = min(spec.max_host_patients, total_eligible_hosts) - indices = rng.choice(total_eligible_hosts, size=n, replace=False) - indices.sort() - selected_hosts = host_pool.iloc[indices].reset_index(drop=True) - - # ── 2. Build donor pool ────────────────────────────────────────── - donor_q = self._index.query().datasets([spec.donor_dataset]) - if spec.exclude_training_datasets: - donor_q = donor_q.exclude_datasets(spec.exclude_training_datasets) - - ns = spec.nodule_spec - if ns: - if ns.label is not None: - donor_q = donor_q.label(ns.label) - if ns.diameter_range: - lo, hi = ns.diameter_range - if lo is not None: - donor_q = donor_q.reinsertion_diameter(min=lo) - if hi is not None: - donor_q = donor_q.reinsertion_diameter(max=hi) - - donor_pool = donor_q.fetch() - - if len(donor_pool) == 0: - raise ValueError( - f"No eligible donor nodules in dataset '{spec.donor_dataset}' " - f"with the given filters." - ) - - # Group donors by patient - donor_grouped = donor_pool.groupby("patient_id") - all_donor_patient_ids = sorted(donor_grouped.groups.keys()) - total_eligible_donor_patients = len(all_donor_patient_ids) - total_eligible_donor_nodules = len(donor_pool) - - # Select donor patients - if spec.all_donor_patients: - selected_donor_ids = all_donor_patient_ids - elif spec.max_donor_patients is not None: - n = min(spec.max_donor_patients, total_eligible_donor_patients) - indices = rng.choice(total_eligible_donor_patients, size=n, replace=False) - indices.sort() - selected_donor_ids = [all_donor_patient_ids[i] for i in indices] - else: - # max_donor_nodules: take donors that cover that many nodules - selected_donor_ids = all_donor_patient_ids # will limit nodules below - - # Collect selected donor nodules - donor_nodules = [] - for pid in selected_donor_ids: - patient_nods = donor_grouped.get_group(pid).reset_index(drop=True) - for _, nod in patient_nods.iterrows(): - donor_nodules.append(nod) - - # Apply max_donor_nodules cap - if spec.max_donor_nodules is not None and len(donor_nodules) > spec.max_donor_nodules: - rng.shuffle(donor_nodules) - donor_nodules = donor_nodules[: spec.max_donor_nodules] - - total_selected_hosts = len(selected_hosts) - total_selected_donor_nodules = len(donor_nodules) - - if verbose: - print(f"Host dataset: {spec.host_dataset}") - print(f"Donor dataset: {spec.donor_dataset}") - print(f" Eligible host patients: {total_eligible_hosts}") - print(f" Selected host patients: {total_selected_hosts}") - print(f" Eligible donor patients: {total_eligible_donor_patients}") - print(f" Eligible donor nodules: {total_eligible_donor_nodules}") - print(f" Selected donor nodules: {total_selected_donor_nodules}") - - # ── 3. Build cross cases ───────────────────────────────────────── - rows = [] - case_id = 0 - - if spec.pairing_policy == "one_to_one": - # Each donor nodule paired with one host (round-robin across hosts) - for i, donor_nod in enumerate(donor_nodules): - host_idx = i % total_selected_hosts - host_row = selected_hosts.iloc[host_idx] - new_rows = self._build_cross_case_rows( - case_id=case_id, - spec=spec, - host_row=host_row, - donor_nodules_for_case=[donor_nod], - rng=rng, - ) - rows.extend(new_rows) - case_id += 1 - - elif spec.pairing_policy == "one_to_many_hosts": - # Same donor nodule paired with N hosts - n_hosts = min(spec.n_hosts_per_donor, total_selected_hosts) - for donor_nod in donor_nodules: - # Select N distinct hosts for this donor - host_indices = rng.choice(total_selected_hosts, size=n_hosts, replace=False) - for h_idx in host_indices: - host_row = selected_hosts.iloc[h_idx] - new_rows = self._build_cross_case_rows( - case_id=case_id, - spec=spec, - host_row=host_row, - donor_nodules_for_case=[donor_nod], - rng=rng, - ) - rows.extend(new_rows) - case_id += 1 - - elif spec.pairing_policy == "donor_patient_complete": - # All donor nodules from one donor patient → one host - # Group donor_nodules back by patient - from collections import defaultdict - - by_patient: dict[str, list] = defaultdict(list) - for nod in donor_nodules: - by_patient[str(nod.get("patient_id", ""))].append(nod) - - for i, (donor_pid, nods) in enumerate(by_patient.items()): - host_idx = i % total_selected_hosts - host_row = selected_hosts.iloc[host_idx] - new_rows = self._build_cross_case_rows( - case_id=case_id, - spec=spec, - host_row=host_row, - donor_nodules_for_case=nods, - rng=rng, - ) - rows.extend(new_rows) - case_id += 1 - - total_generated_cases = case_id - total_rows = len(rows) - - if verbose: - print(f"\n Generated cross cases: {total_generated_cases}") - print(f" Total manifest rows: {total_rows}") - print("\nSummary:") - print(f" Total eligible host patients: {total_eligible_hosts}") - print(f" Total selected host patients: {total_selected_hosts}") - print(f" Total eligible donor patients: {total_eligible_donor_patients}") - print(f" Total eligible donor nodules: {total_eligible_donor_nodules}") - print(f" Total selected donor nodules: {total_selected_donor_nodules}") - print(f" Total generated cross cases: {total_generated_cases}") - - df = pd.DataFrame(rows) - - wrapper_spec = TrialSpec( - trial_name=spec.trial_name, - n_cases=total_generated_cases, - cohort_mode="cross", - seed=spec.seed, - host_datasets=[spec.host_dataset], - donor_datasets=[spec.donor_dataset], - base_dir=spec.base_dir, - ) - - return CohortManifest(df, wrapper_spec) - - def _build_cross_case_rows( - self, - case_id: int, - spec: DigitalTwinCrossSpec, - host_row: pd.Series, - donor_nodules_for_case: list[pd.Series], - rng: np.random.Generator, - ) -> list[dict]: - """Assemble manifest rows for a single cross case. - - For donor_transfer_mode="single", donor_nodules_for_case has 1 element. - For "complete" or "donor_patient_complete" pairing, it may have many. - """ - from itrialspace.site.sampling import _diameter_to_bucket - - host_ds = spec.host_dataset - host_pid = str(host_row.get("patient_id", "")) - host_ct_rel = str(host_row.get("ct_path", "")) - host_ct_id = PathResolver.extract_ct_id(host_ct_rel) - - host_age, host_sex, host_smoking, host_pack_years = self._extract_demographics( - host_row, host_ds - ) - - rows = [] - n_nodules = len(donor_nodules_for_case) - - for nod_idx, donor_nod in enumerate(donor_nodules_for_case): - donor_ds = spec.donor_dataset - donor_pid = str(donor_nod.get("patient_id", "")) - donor_ann_id = str(donor_nod.get("annotation_id", "")) - donor_ct_rel = str(donor_nod.get("ct_path", "")) - donor_ct_id = PathResolver.extract_ct_id(donor_ct_rel) - donor_diam = float(donor_nod.get("reinsertion_nodule_diam_mm", 0)) - size_bucket = _diameter_to_bucket(donor_diam) if donor_diam > 0 else "" - - raw_label = donor_nod.get("label") - label_val = int(raw_label) if pd.notna(raw_label) else None - - population_type = "screening" if donor_ds in SCREENING_DATASETS else "diagnostic" - label_source = "histopathology" if donor_ds in HISTOPATH_DATASETS else "radiology" - - # Insertion planning — use donor's reinsertion profile - # profile_faithful_transfer: preserve donor's anatomical coordinates - # host_constrained_transfer: use prescribed mode to resample in host - if spec.placement_strategy == "profile_faithful_transfer": - plan = self._planner.plan( - nodule_row=donor_nod, - mode="profile_faithful", - target_diam_mm=None, - insertion_spec=None, - rng=rng, - ) - else: - # host_constrained_transfer: use prescribed mode with donor's lobe info - from itrialspace.site.spec import InsertionSpec - - insertion_spec = InsertionSpec( - target_lobe=str(donor_nod.get("reinsertion_lobe", "")), - ) - plan = self._planner.plan( - nodule_row=donor_nod, - mode="prescribed", - target_diam_mm=None, - insertion_spec=insertion_spec, - rng=rng, - ) - - row = { - # Case identity - "case_id": case_id, - "nodule_idx": nod_idx, - "is_primary_nodule": nod_idx == 0, - "n_nodules_in_case": n_nodules, - "companion_group_id": case_id, - "trial_name": spec.trial_name, - "trial_template": "", - "bootstrap_id": 0, - # Host CT — from host patient - "host_patient_id": host_pid, - "host_dataset": host_ds, - "host_ct_path": self._resolver.resolve_ct_path(host_ds, host_ct_rel), - "host_organ_seg_path": self._resolver.resolve_organ_seg_path(host_ds, host_ct_id), - # Donor — from different patient/dataset - "donor_patient_id": donor_pid, - "donor_annotation_id": donor_ann_id, - "donor_dataset": donor_ds, - "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( - donor_ds, donor_ann_id, ct_id=donor_ct_id - ), - "donor_ct_path": self._resolver.resolve_ct_path(donor_ds, donor_ct_rel), - "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( - donor_ds, donor_ct_id - ), - # Insertion — from planner - "insertion_coord_x": plan.insertion_coord_x, - "insertion_coord_y": plan.insertion_coord_y, - "insertion_coord_z": plan.insertion_coord_z, - "insertion_lobe": plan.insertion_lobe, - "insertion_lobe_cc_pct": plan.insertion_lobe_cc_pct, - "insertion_lobe_ml_pct": plan.insertion_lobe_ml_pct, - "insertion_lobe_ap_pct": plan.insertion_lobe_ap_pct, - "insertion_mode": plan.insertion_mode, - # Nodule characteristics - "nodule_diam_mm": donor_diam, - "effective_diam_mm": ( - plan.effective_diam_mm if plan.effective_diam_mm > 0 else donor_diam - ), - "scale_factor": plan.scale_factor, - "warp_applied": plan.warp_applied, - "label": label_val, - # Anatomy (donor's native anatomy) - "nodule_lobe_name": str(donor_nod.get("reinsertion_lobe", "")), - "nodule_lung_side": str(donor_nod.get("reinsertion_lung_side", "")), - "nodule_lung_zone": str(donor_nod.get("reinsertion_lung_zone", "")), - "nodule_central_peripheral": str(donor_nod.get("central_peripheral", "")), - "pleural_distance_mm": donor_nod.get("reinsertion_pleural_dist_mm"), - # Demographics (from host) - "patient_age": host_age, - "patient_sex": host_sex, - "smoking_status": host_smoking, - "pack_years": host_pack_years, - # Cohort metadata - "cohort_mode": "cross", - "size_bucket": size_bucket, - "population_type": population_type, - "label_source": label_source, - # Digital twin cross columns - "mode": "digital_twin_cross", - "donor_transfer_mode": spec.donor_transfer_mode, - "pairing_policy": spec.pairing_policy, - "placement_strategy": spec.placement_strategy, - "cross_case_group_id": case_id, - } - rows.append(row) - - return rows diff --git a/itrialspace/src/itrialspace/site/config/paths.yaml b/itrialspace/src/itrialspace/site/config/paths.yaml deleted file mode 100644 index 2403d5cf4b3aa23e4dc43291f759f0527d87ce28..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/config/paths.yaml +++ /dev/null @@ -1,61 +0,0 @@ -# iTrialSpace path layout — unified data directory. -# -# Copy to `configs/paths.yaml` and adjust if your layout differs. ${ITRIALSPACE_DATA_DIR} -# is expanded by itrialspace.config.settings (default: ~/.itrialspace/data). -# -# ${ITRIALSPACE_DATA_DIR}/ -# ├── raw_ct/{DATASET}/ CT scans (resampled NIfTI) -# ├── masks/{DATASET}/ -# │ ├── nodule_seg/ Individual nodule masks -# │ ├── combined_seg/ Combined patient masks -# │ ├── organ_seg/ VISTA3D organ segmentations (raw, deprecated) -# │ └── refined_seg/ Refined organ + body segmentations (used by default) -# ├── profiles/ Nodule profile CSVs -# └── meta/ Original dataset metadata CSVs -# -# ct_path values in profile CSVs are relative to raw_ct/, e.g. -# "DLCS24/DLCS_0001.nii.gz" → ${ITRIALSPACE_DATA_DIR}/raw_ct/DLCS24/DLCS_0001.nii.gz - -# ── Global base directory ────────────────────────────────────────────────── -base_dir: ${ITRIALSPACE_DATA_DIR} - -# ── Per-dataset configuration ────────────────────────────────────────────── -# Only override patterns/flags when they differ from the defaults: -# organ_seg_pattern: "{ct_id}_seg.nii.gz" -# nodule_seg_pattern: "{annotation_id}.nii.gz" -# combined_mask_pattern: "{ct_id}_mask.nii.gz" - -datasets: - - DLCS24: - profile_csv: DLCS24_nodule_profiles.csv - meta_csv: DLCS24_BMdataset_FEB192026_FIT_v1.csv - - LUNA25: - profile_csv: LUNA25_nodule_profiles.csv - meta_csv: LUNA25_dataset_FEB192026_FIT_v1.csv - - LUNA16: - profile_csv: LUNA16_nodule_profiles.csv - meta_csv: LUNA16_dataset_FEB192026_FIT_v1.csv - - LUNGx: - profile_csv: LUNGx_nodule_profiles.csv - meta_csv: LUNGx_dataset_FEB192026_FIT_v1.csv - - LNDbv4: - profile_csv: LNDbv4_nodule_profiles.csv - meta_csv: LNDBv4_dataset_FEB192026_FIT_v1.csv - - NSCLCR: - profile_csv: NSCLCR_nodule_profiles.csv - meta_csv: NSCLCR_dataset_FEB192026_FIT_v1.csv - nodule_seg_pattern: "{annotation_id}.nii.gz" - combined_mask_pattern: "{ct_id}.nii.gz" - - IMDCT: - profile_csv: IMDCT_nodule_profiles.csv - meta_csv: IMDCT_dataset_FEB192026_FIT_v1.csv - nodule_seg_use_ct_id: true - nodule_seg_pattern: "{ct_id}_seg.nii.gz" - combined_mask_pattern: "{ct_id}_seg.nii.gz" diff --git a/itrialspace/src/itrialspace/site/config/trials.yaml b/itrialspace/src/itrialspace/site/config/trials.yaml deleted file mode 100644 index f1059ea91828b3a631423a6407986df9ae46f1d7..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/config/trials.yaml +++ /dev/null @@ -1,157 +0,0 @@ -# Published lung cancer screening trial parameters. -# Used by TrialKnowledgeBase to instantiate TrialSpec objects. -# -# Sources: -# NLST: Aberle et al. NEJM 2011; 365:395-409 -# NELSON: de Koning et al. NEJM 2020; 382:503-513 -# UKLS: Field et al. Lancet Respir Med 2016; 4:699-709 -# DANTE: Infante et al. AJRCCM 2009; 180:445-453 -# MILD: Pastorino et al. ERJ 2012; 39:1354-1362 - -trials: - - NLST: - full_name: "National Lung Screening Trial" - publication: "Aberle et al. NEJM 2011" - population: screening - n_participants: 26722 - demographics: - age_range: [55, 74] - age_mean: 61.4 - age_std: 5.0 - sex_ratio_male: 0.59 - smoking_status: ["Current", "Former"] - pack_years_min: 30 - nodule_prevalence: - any_nodule: 0.245 - malignancy_rate: 0.04 - size_distribution: - bucket_weights: - "<5mm": 0.42 - "5-10mm": 0.38 - "10-15mm": 0.11 - "15-20mm": 0.05 - "20-30mm": 0.03 - ">30mm": 0.01 - malignancy_rate_by_size: - "<5mm": 0.01 - "5-10mm": 0.024 - "10-15mm": 0.094 - "15-20mm": 0.178 - "20-30mm": 0.222 - ">30mm": 0.362 - lobe_distribution: - right_lung_upper_lobe: 0.30 - right_lung_middle_lobe: 0.08 - right_lung_lower_lobe: 0.18 - left_lung_upper_lobe: 0.28 - left_lung_lower_lobe: 0.16 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] - - NELSON: - full_name: "Nederlands-Leuvens Longkanker Screenings Onderzoek" - publication: "de Koning et al. NEJM 2020" - population: screening - n_participants: 7557 - demographics: - age_range: [50, 75] - age_mean: 58.0 - age_std: 5.5 - sex_ratio_male: 0.84 - smoking_status: ["Current", "Former"] - pack_years_min: 15 - nodule_prevalence: - any_nodule: 0.50 - malignancy_rate: 0.022 - size_distribution: - bucket_weights: - "<5mm": 0.55 - "5-10mm": 0.30 - "10-15mm": 0.09 - "15-20mm": 0.04 - ">20mm": 0.02 - malignancy_rate_by_size: - "<5mm": 0.005 - "5-10mm": 0.014 - "10-15mm": 0.063 - "15-20mm": 0.156 - ">20mm": 0.308 - lobe_distribution: - right_lung_upper_lobe: 0.30 - right_lung_middle_lobe: 0.08 - right_lung_lower_lobe: 0.18 - left_lung_upper_lobe: 0.28 - left_lung_lower_lobe: 0.16 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] - - UKLS: - full_name: "UK Lung Cancer Screening Trial" - publication: "Field et al. Lancet Respir Med 2016" - population: screening - n_participants: 1994 - demographics: - age_range: [50, 75] - sex_ratio_male: 0.52 - smoking_status: ["Current", "Former"] - pack_years_min: 20 - nodule_prevalence: - any_nodule: 0.34 - malignancy_rate: 0.017 - size_distribution: - bucket_weights: - "<5mm": 0.48 - "5-10mm": 0.35 - "10-15mm": 0.10 - "15-20mm": 0.04 - ">20mm": 0.03 - lobe_distribution: - right_lung_upper_lobe: 0.30 - right_lung_middle_lobe: 0.08 - right_lung_lower_lobe: 0.18 - left_lung_upper_lobe: 0.28 - left_lung_lower_lobe: 0.16 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] - - DANTE: - full_name: "Detection And screening of early lung Neoplasm with LDCT" - publication: "Infante et al. AJRCCM 2009" - population: screening - n_participants: 1276 - demographics: - age_range: [60, 75] - sex_ratio_male: 1.0 - smoking_status: ["Current", "Former"] - pack_years_min: 20 - nodule_prevalence: - any_nodule: 0.31 - malignancy_rate: 0.028 - size_distribution: - bucket_weights: - "<5mm": 0.40 - "5-10mm": 0.37 - "10-15mm": 0.13 - "15-20mm": 0.06 - ">20mm": 0.04 - applicable_source_datasets: ["DLCS24", "LUNA25"] - - MILD: - full_name: "Multicentric Italian Lung Detection Trial" - publication: "Pastorino et al. ERJ 2012" - population: screening - n_participants: 2376 - demographics: - age_range: [49, 75] - sex_ratio_male: 0.66 - smoking_status: ["Current", "Former"] - pack_years_min: 20 - nodule_prevalence: - any_nodule: 0.28 - malignancy_rate: 0.012 - size_distribution: - bucket_weights: - "<5mm": 0.52 - "5-10mm": 0.33 - "10-15mm": 0.09 - "15-20mm": 0.04 - ">20mm": 0.02 - applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] diff --git a/itrialspace/src/itrialspace/site/insertion_planner.py b/itrialspace/src/itrialspace/site/insertion_planner.py deleted file mode 100644 index 5f89c04274da92036f9580081a596123067860ac..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/insertion_planner.py +++ /dev/null @@ -1,264 +0,0 @@ -""" -Insertion planner — determines insertion coordinates and scaling -for each case in the synthetic cohort. - -Three modes: -- profile_faithful: use reinsertion_* columns directly from the nodule profile -- prescribed: user specifies target anatomy; planner samples from observed distributions -- randomised: uniform sample within target lobe's observed percentile ranges -""" - -from __future__ import annotations - -from dataclasses import dataclass -from typing import TYPE_CHECKING, Optional - -import numpy as np -import pandas as pd - -if TYPE_CHECKING: - from itrialspace.site.spec import InsertionSpec - - -@dataclass -class InsertionPlan: - """Result of planning a single nodule insertion.""" - - insertion_coord_x: float = 0.0 - insertion_coord_y: float = 0.0 - insertion_coord_z: float = 0.0 - insertion_lobe: str = "unknown" - insertion_lobe_cc_pct: float = 0.0 - insertion_lobe_ml_pct: float = 0.0 - insertion_lobe_ap_pct: float = 0.0 - insertion_mode: str = "profile_faithful" - scale_factor: float = 1.0 - scale_factor_xyz: tuple[float, float, float] = (1.0, 1.0, 1.0) - warp_applied: str = "none" # "none" | "isotropic" | "anisotropic" - effective_diam_mm: float = 0.0 - feasible: bool = True - infeasibility_reason: str = "" - - -class InsertionPlanner: - """Plans insertion coordinates and scaling for synthetic nodule placement.""" - - def __init__(self, index_df: pd.DataFrame): - """ - Args: - index_df: The NoduleIndex DataFrame (used to compute lobe - statistics for prescribed/randomised modes). - """ - self._df = index_df - self._lobe_stats = self._compute_lobe_ranges() - - def plan( - self, - nodule_row: pd.Series, - mode: str, - target_diam_mm: Optional[float] = None, - insertion_spec: Optional["InsertionSpec"] = None, - rng: Optional[np.random.Generator] = None, - ) -> InsertionPlan: - """Dispatch to mode-specific planner. - - Args: - nodule_row: Row from NoduleIndex DataFrame (the donor nodule). - mode: "profile_faithful", "prescribed", or "randomised". - target_diam_mm: Desired diameter (triggers scaling if different from donor). - insertion_spec: InsertionSpec for prescribed/randomised modes. - rng: Random generator (required for prescribed/randomised). - - Returns: - InsertionPlan with coordinates, scaling, and feasibility. - """ - if mode == "profile_faithful": - plan = self._plan_profile_faithful(nodule_row) - elif mode == "prescribed": - if rng is None: - raise ValueError("rng required for prescribed mode") - plan = self._plan_prescribed(nodule_row, insertion_spec, rng) - elif mode == "randomised": - if rng is None: - raise ValueError("rng required for randomised mode") - plan = self._plan_randomised(nodule_row, insertion_spec, rng) - else: - raise ValueError(f"Unknown insertion mode: {mode}") - - # Apply scaling if target diameter specified - if target_diam_mm is not None: - donor_diam = float(nodule_row.get("reinsertion_nodule_diam_mm", 0)) - if donor_diam > 0: - sf, warp = self._compute_scale(donor_diam, target_diam_mm, insertion_spec) - plan.scale_factor = sf - plan.warp_applied = warp - plan.effective_diam_mm = donor_diam * sf - else: - plan.effective_diam_mm = target_diam_mm - else: - plan.effective_diam_mm = float(nodule_row.get("reinsertion_nodule_diam_mm", 0)) - - plan.insertion_mode = mode - return plan - - # ── Mode implementations ────────────────────────────────────────────────── - - def _plan_profile_faithful(self, row: pd.Series) -> InsertionPlan: - """Use reinsertion_* columns directly.""" - return InsertionPlan( - insertion_coord_x=float(row.get("coordX", 0)), - insertion_coord_y=float(row.get("coordY", 0)), - insertion_coord_z=float(row.get("coordZ", 0)), - insertion_lobe=str(row.get("reinsertion_lobe", "unknown")), - insertion_lobe_cc_pct=float(row.get("reinsertion_lobe_cc_pct", 0)), - insertion_lobe_ml_pct=float(row.get("reinsertion_lobe_ml_pct", 0)), - insertion_lobe_ap_pct=float(row.get("reinsertion_lobe_ap_pct", 0)), - ) - - def _plan_prescribed( - self, - row: pd.Series, - spec: Optional["InsertionSpec"], - rng: np.random.Generator, - ) -> InsertionPlan: - """Sample position within prescribed lobe/zone from observed distributions.""" - from itrialspace.site.spec import InsertionSpec - - spec = spec or InsertionSpec() - target_lobe = spec.target_lobe or str(row.get("reinsertion_lobe", "unknown")) - - stats = self._lobe_stats.get(target_lobe) - if stats is None: - return InsertionPlan( - insertion_lobe=target_lobe, - feasible=False, - infeasibility_reason=f"No statistics for lobe '{target_lobe}'", - ) - - cc = rng.uniform(stats["cc_p10"], stats["cc_p90"]) - ml = rng.uniform(stats["ml_p10"], stats["ml_p90"]) - ap = rng.uniform(stats["ap_p10"], stats["ap_p90"]) - - return InsertionPlan( - insertion_lobe=target_lobe, - insertion_lobe_cc_pct=cc, - insertion_lobe_ml_pct=ml, - insertion_lobe_ap_pct=ap, - ) - - def _plan_randomised( - self, - row: pd.Series, - spec: Optional["InsertionSpec"], - rng: np.random.Generator, - ) -> InsertionPlan: - """Uniform sample within target lobe's observed ranges.""" - from itrialspace.site.spec import InsertionSpec - - spec = spec or InsertionSpec() - target_lobe = spec.target_lobe or str(row.get("reinsertion_lobe", "unknown")) - - stats = self._lobe_stats.get(target_lobe) - if stats is None: - return InsertionPlan( - insertion_lobe=target_lobe, - feasible=False, - infeasibility_reason=f"No statistics for lobe '{target_lobe}'", - ) - - cc = rng.uniform(stats["cc_min"], stats["cc_max"]) - ml = rng.uniform(stats["ml_min"], stats["ml_max"]) - ap = rng.uniform(stats["ap_min"], stats["ap_max"]) - - return InsertionPlan( - insertion_lobe=target_lobe, - insertion_lobe_cc_pct=cc, - insertion_lobe_ml_pct=ml, - insertion_lobe_ap_pct=ap, - ) - - # ── Scaling ─────────────────────────────────────────────────────────────── - - @staticmethod - def _compute_scale( - donor_diam: float, - target_diam: float, - spec: Optional["InsertionSpec"], - ) -> tuple[float, str]: - """Compute scale factor and warp type. - - Priority: - 1. Constrained match (within tolerance) → no warp - 2. Isotropic scale → uniform resize - 3. Anisotropic warp → per-axis stretch (opt-in) - - Returns: - (scale_factor, warp_type) where warp_type is "none"|"isotropic"|"anisotropic" - """ - from itrialspace.site.spec import InsertionSpec - - spec = spec or InsertionSpec() - if donor_diam <= 0: - return (1.0, "none") - - ratio = target_diam / donor_diam - - # Within tolerance → no scaling needed - if abs(ratio - 1.0) <= spec.scale_tolerance: - return (1.0, "none") - - # Isotropic scale - if spec.allow_isotropic_scale and ratio <= spec.max_scale_factor: - return (ratio, "isotropic") - - # Anisotropic warp - if spec.allow_anisotropic_warp and ratio <= spec.max_scale_factor: - return (ratio, "anisotropic") - - # Scale factor exceeds maximum — clamp - clamped = min(ratio, spec.max_scale_factor) - warp = "isotropic" if spec.allow_isotropic_scale else "anisotropic" - return (clamped, warp) - - # ── Lobe statistics ─────────────────────────────────────────────────────── - - def _compute_lobe_ranges(self) -> dict[str, dict]: - """Compute per-lobe position statistics from the index. - - Uses reinsertion_* columns (100% complete) to build - min/max/percentile ranges for each lobe. - """ - from itrialspace.core.schema import LOBE_NAMES - - stats: dict[str, dict] = {} - for lobe in LOBE_NAMES: - mask = self._df["reinsertion_lobe"] == lobe - sub = self._df.loc[mask] - if len(sub) < 5: - continue - - cc = sub["reinsertion_lobe_cc_pct"].dropna() - ml = sub["reinsertion_lobe_ml_pct"].dropna() - ap = sub["reinsertion_lobe_ap_pct"].dropna() - - if len(cc) < 5: - continue - - stats[lobe] = { - "n": len(sub), - "cc_min": float(cc.min()), - "cc_max": float(cc.max()), - "cc_p10": float(cc.quantile(0.10)), - "cc_p90": float(cc.quantile(0.90)), - "cc_median": float(cc.median()), - "ml_min": float(ml.min()), - "ml_max": float(ml.max()), - "ml_p10": float(ml.quantile(0.10)), - "ml_p90": float(ml.quantile(0.90)), - "ap_min": float(ap.min()), - "ap_max": float(ap.max()), - "ap_p10": float(ap.quantile(0.10)), - "ap_p90": float(ap.quantile(0.90)), - } - - return stats diff --git a/itrialspace/src/itrialspace/site/knowledge_base.py b/itrialspace/src/itrialspace/site/knowledge_base.py deleted file mode 100644 index 432ad481c029f4b2c25540fa92139b288f98cbbd..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/knowledge_base.py +++ /dev/null @@ -1,177 +0,0 @@ -""" -Clinical trial knowledge base — loads published trial parameters -from trials.yaml and converts them into TrialSpec objects. -""" - -from __future__ import annotations - -from pathlib import Path -from typing import Optional - -import pandas as pd - -try: - import yaml -except ImportError: - yaml = None # type: ignore[assignment] - -from itrialspace.site.spec import ( - DemographicSpec, - NoduleSpec, - SizeDistribution, - TrialSpec, -) - -_DEFAULT_YAML = Path(__file__).parent / "config" / "trials.yaml" - - -class TrialKnowledgeBase: - """Loads published trial parameters and produces TrialSpec objects.""" - - def __init__(self, yaml_path: Optional[str] = None): - if yaml is None: - raise ImportError("pyyaml is required: pip install pyyaml") - path = Path(yaml_path) if yaml_path else _DEFAULT_YAML - with open(path) as f: - data = yaml.safe_load(f) - self._trials: dict[str, dict] = data.get("trials", {}) - - @property - def available_trials(self) -> list[str]: - return list(self._trials.keys()) - - def get_template(self, trial_name: str) -> dict: - if trial_name not in self._trials: - raise KeyError(f"Unknown trial '{trial_name}'. " f"Available: {self.available_trials}") - return self._trials[trial_name] - - def to_trial_spec( - self, - trial_name: str, - n_cases: int = 500, - cohort_mode: str = "synthetic", - insertion_mode: str = "profile_faithful", - overrides: Optional[dict] = None, - seed: int = 42, - ) -> TrialSpec: - """Convert a published trial template into a TrialSpec. - - Args: - trial_name: Template name (e.g. "NLST", "NELSON"). - n_cases: Number of cases in the cohort. - cohort_mode: "native", "matched", or "synthetic". - insertion_mode: "profile_faithful", "prescribed", or "randomised". - overrides: Dict to patch any TrialSpec field after construction. - seed: Random seed for reproducibility. - - Returns: - Fully populated TrialSpec. - """ - tmpl = self.get_template(trial_name) - - # Demographics - demo = None - if "demographics" in tmpl: - d = tmpl["demographics"] - age_range = tuple(d["age_range"]) if "age_range" in d else None - demo = DemographicSpec( - age_range=age_range, - age_mean=d.get("age_mean"), - age_std=d.get("age_std"), - sex_ratio_male=d.get("sex_ratio_male"), - smoking_status=d.get("smoking_status"), - pack_years_min=d.get("pack_years_min"), - ) - - # Size distribution - size_dist = None - if "size_distribution" in tmpl: - sd = tmpl["size_distribution"] - size_dist = SizeDistribution( - bucket_weights=sd.get("bucket_weights"), - ) - - # Nodule spec - nodule_spec = NoduleSpec(size_distribution=size_dist) - - # Prevalence - mal_prev = None - if "nodule_prevalence" in tmpl: - mal_prev = tmpl["nodule_prevalence"].get("malignancy_rate") - - # Source datasets - source_ds = tmpl.get("applicable_source_datasets") - - spec = TrialSpec( - trial_name=f"{trial_name}_cohort", - trial_template=trial_name, - description=f"Cohort based on {tmpl.get('full_name', trial_name)} " - f"({tmpl.get('publication', 'N/A')})", - seed=seed, - n_cases=n_cases, - cohort_mode=cohort_mode, - demographics=demo, - nodule_spec=nodule_spec, - malignancy_prevalence=mal_prev, - source_datasets=source_ds, - insertion_mode=insertion_mode, - ) - - # Apply overrides - if overrides: - for k, v in overrides.items(): - if hasattr(spec, k): - setattr(spec, k, v) - - return spec - - def describe(self, trial_name: str) -> str: - """Human-readable summary of a trial template.""" - tmpl = self.get_template(trial_name) - lines = [ - f"=== {tmpl.get('full_name', trial_name)} ===", - f"Publication: {tmpl.get('publication', 'N/A')}", - f"Population: {tmpl.get('population', 'N/A')}", - f"N participants: {tmpl.get('n_participants', 'N/A')}", - ] - if "demographics" in tmpl: - d = tmpl["demographics"] - lines.append(f"Age range: {d.get('age_range', 'N/A')}") - lines.append(f"Male ratio: {d.get('sex_ratio_male', 'N/A')}") - lines.append(f"Min pack-years: {d.get('pack_years_min', 'N/A')}") - if "nodule_prevalence" in tmpl: - np_ = tmpl["nodule_prevalence"] - lines.append(f"Any nodule prevalence: {np_.get('any_nodule', 'N/A')}") - lines.append(f"Malignancy rate: {np_.get('malignancy_rate', 'N/A')}") - if "size_distribution" in tmpl: - sd = tmpl["size_distribution"] - if "bucket_weights" in sd: - lines.append("Size distribution:") - for bucket, w in sd["bucket_weights"].items(): - lines.append(f" {bucket}: {w:.0%}") - lines.append(f"Source datasets: {tmpl.get('applicable_source_datasets', 'N/A')}") - return "\n".join(lines) - - def compare(self, trial_names: Optional[list[str]] = None) -> pd.DataFrame: - """Side-by-side comparison table of trial templates.""" - if trial_names is None: - trial_names = self.available_trials - - rows = [] - for name in trial_names: - tmpl = self.get_template(name) - demo = tmpl.get("demographics", {}) - prev = tmpl.get("nodule_prevalence", {}) - row = { - "trial": name, - "population": tmpl.get("population"), - "n_participants": tmpl.get("n_participants"), - "age_range": str(demo.get("age_range", "")), - "male_ratio": demo.get("sex_ratio_male"), - "pack_years_min": demo.get("pack_years_min"), - "nodule_prevalence": prev.get("any_nodule"), - "malignancy_rate": prev.get("malignancy_rate"), - } - rows.append(row) - - return pd.DataFrame(rows).set_index("trial") diff --git a/itrialspace/src/itrialspace/site/manifest.py b/itrialspace/src/itrialspace/site/manifest.py deleted file mode 100644 index 9df91edceddc844dafa3048cf5989ac95f226d57..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/manifest.py +++ /dev/null @@ -1,345 +0,0 @@ -""" -CohortManifest — the final output of iTrialSpace. - -A structured manifest describing every case in a synthetic trial -cohort. Wraps a DataFrame with export, audit, and path verification. -""" - -from __future__ import annotations - -import json -import os - -import pandas as pd - -from itrialspace.site.spec import TrialSpec - -# ── Manifest column schema ──────────────────────────────────────────────────── - -MANIFEST_COLS = [ - # Case identity - "case_id", - "nodule_idx", - "is_primary_nodule", - "n_nodules_in_case", - "companion_group_id", - "trial_name", - "trial_template", - "bootstrap_id", - # Host CT - "host_patient_id", - "host_dataset", - "host_ct_path", - "host_organ_seg_path", - # Donor nodule - "donor_patient_id", - "donor_annotation_id", - "donor_dataset", - "donor_nodule_mask_path", - "donor_ct_path", - "donor_refined_seg_path", - # Insertion parameters - "insertion_coord_x", - "insertion_coord_y", - "insertion_coord_z", - "insertion_lobe", - "insertion_lobe_cc_pct", - "insertion_lobe_ml_pct", - "insertion_lobe_ap_pct", - "insertion_mode", - # Nodule characteristics - "nodule_diam_mm", - "effective_diam_mm", - "scale_factor", - "warp_applied", - "label", - # Anatomy - "nodule_lobe_name", - "nodule_lung_side", - "nodule_lung_zone", - "nodule_central_peripheral", - "pleural_distance_mm", - # Demographics - "patient_age", - "patient_sex", - "smoking_status", - "pack_years", - # Cohort metadata - "cohort_mode", - "size_bucket", - "population_type", - "label_source", -] - -# Additional columns for digital twin isolation manifests. -# These are appended to MANIFEST_COLS when the mode is digital_twin_isolation. -ISOLATION_MANIFEST_COLS = MANIFEST_COLS + [ - "mode", - "target_annotation_id", - "target_nodule_mask_path", - "target_diameter_mm", - "target_label", - "target_lobe", - "target_side", - "target_zone", - "host_n_nodules", - "isolation_case_index", -] - -# Additional columns for digital twin complete manifests. -# One row per nodule, all nodules for the same patient share a case_id. -COMPLETE_MANIFEST_COLS = MANIFEST_COLS + [ - "mode", - "host_n_nodules", - "annotation_ids", - "diameters_mm", - "labels", - "lobes", - "sides", - "zones", -] - -# Additional columns for digital twin cross manifests. -# Explicit host/donor provenance with placement and pairing metadata. -CROSS_MANIFEST_COLS = MANIFEST_COLS + [ - "mode", - "donor_transfer_mode", - "pairing_policy", - "placement_strategy", - "cross_case_group_id", -] - - -class CohortManifest: - """Structured manifest for a synthetic imaging trial cohort.""" - - def __init__(self, df: pd.DataFrame, spec: TrialSpec): - self._df = df - self._spec = spec - - @property - def df(self) -> pd.DataFrame: - return self._df - - @property - def spec(self) -> TrialSpec: - return self._spec - - def __len__(self) -> int: - return len(self._df) - - def __repr__(self) -> str: - n_mal = (self._df["label"] == 1).sum() - n_ben = (self._df["label"] == 0).sum() - # Show total rows vs unique cases when companions present - if "is_primary_nodule" in self._df.columns: - n_primary = int(self._df["is_primary_nodule"].sum()) - if n_primary < len(self): - return ( - f"CohortManifest('{self._spec.trial_name}' | " - f"{n_primary} cases ({len(self)} total rows) | " - f"{n_mal} malignant, {n_ben} benign)" - ) - return ( - f"CohortManifest('{self._spec.trial_name}' | " - f"{len(self)} cases | {n_mal} malignant, {n_ben} benign)" - ) - - # ── Export ───────────────────────────────────────────────────────────────── - - def to_csv(self, path: str) -> None: - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - self._df.to_csv(path, index=False) - - def to_json(self, path: str) -> None: - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - records = self._df.to_dict(orient="records") - with open(path, "w") as f: - json.dump( - { - "trial_name": self._spec.trial_name, - "trial_template": self._spec.trial_template, - "n_cases": len(self), - "cohort_mode": self._spec.cohort_mode, - "seed": self._spec.seed, - "cases": records, - }, - f, - indent=2, - default=str, - ) - - def to_dataframe(self) -> pd.DataFrame: - return self._df.copy() - - # ── Summary ─────────────────────────────────────────────────────────────── - - def summary(self) -> dict: - """Summary statistics of the manifest.""" - df = self._df - s: dict = { - "trial_name": self._spec.trial_name, - "n_cases": len(df), - "cohort_mode": self._spec.cohort_mode, - } - - if "label" in df.columns: - labels = df["label"].dropna() - s["n_malignant"] = int((labels == 1).sum()) - s["n_benign"] = int((labels == 0).sum()) - s["n_unlabelled"] = int(df["label"].isna().sum()) - if len(labels) > 0: - s["malignancy_rate"] = round(float((labels == 1).mean()), 4) - - if "size_bucket" in df.columns: - s["size_distribution"] = df["size_bucket"].value_counts().to_dict() - - if "insertion_lobe" in df.columns: - s["lobe_distribution"] = df["insertion_lobe"].value_counts().to_dict() - - if "donor_dataset" in df.columns: - s["donor_datasets"] = df["donor_dataset"].value_counts().to_dict() - - if "host_dataset" in df.columns: - s["host_datasets"] = df["host_dataset"].value_counts().to_dict() - - if "warp_applied" in df.columns: - s["warp_distribution"] = df["warp_applied"].value_counts().to_dict() - - # Multi-nodule statistics - if "is_primary_nodule" in df.columns: - n_primary = int(df["is_primary_nodule"].sum()) - n_companion = len(df) - n_primary - if n_companion > 0: - s["n_primary_cases"] = n_primary - s["n_companion_insertions"] = n_companion - s["total_manifest_rows"] = len(df) - # Count cases with >1 nodule - if "n_nodules_in_case" in df.columns: - primary_rows = df[df["is_primary_nodule"] == True] - s["multi_nodule_cases"] = int((primary_rows["n_nodules_in_case"] > 1).sum()) - - return s - - def audit(self) -> pd.DataFrame: - """Compare actual manifest statistics to TrialSpec targets. - - Returns: - DataFrame with columns: metric, target, actual, deviation. - """ - rows = [] - spec = self._spec - df = self._df - - # Prevalence - if spec.malignancy_prevalence is not None and "label" in df.columns: - labels = df["label"].dropna() - actual_prev = float((labels == 1).mean()) if len(labels) > 0 else 0.0 - rows.append( - { - "metric": "malignancy_prevalence", - "target": spec.malignancy_prevalence, - "actual": round(actual_prev, 4), - "deviation": round(actual_prev - spec.malignancy_prevalence, 4), - } - ) - - # N cases - rows.append( - { - "metric": "n_cases", - "target": spec.n_cases, - "actual": len(df), - "deviation": len(df) - spec.n_cases, - } - ) - - # Size distribution - if ( - spec.nodule_spec - and spec.nodule_spec.size_distribution - and spec.nodule_spec.size_distribution.bucket_weights - and "size_bucket" in df.columns - ): - actual_dist = df["size_bucket"].value_counts(normalize=True) - for bucket, target_w in spec.nodule_spec.size_distribution.bucket_weights.items(): - actual_w = actual_dist.get(bucket, 0.0) - rows.append( - { - "metric": f"size_{bucket}", - "target": round(target_w, 3), - "actual": round(float(actual_w), 3), - "deviation": round(float(actual_w) - target_w, 3), - } - ) - - # Companion nodule audit - if "is_primary_nodule" in df.columns: - n_companion = int((df["is_primary_nodule"] == False).sum()) - if n_companion > 0: - rows.append( - { - "metric": "companion_nodules_added", - "target": "N/A", - "actual": n_companion, - "deviation": 0, - } - ) - - return pd.DataFrame(rows) - - # ── Path verification ───────────────────────────────────────────────────── - - def verify_paths(self) -> pd.DataFrame: - """Check which files actually exist on disk. - - Returns: - DataFrame of missing files with columns: case_id, path_type, path. - """ - path_cols = [ - "host_ct_path", - "host_organ_seg_path", - "donor_nodule_mask_path", - "donor_ct_path", - ] - missing = [] - for _, row in self._df.iterrows(): - for col in path_cols: - if col in row and pd.notna(row[col]): - path = str(row[col]) - if not os.path.exists(path): - missing.append( - { - "case_id": row.get("case_id", ""), - "path_type": col, - "path": path, - } - ) - return pd.DataFrame(missing) - - # ── Subsetting ──────────────────────────────────────────────────────────── - - def malignant_cases(self) -> CohortManifest: - return CohortManifest( - self._df[self._df["label"] == 1].reset_index(drop=True), - self._spec, - ) - - def benign_cases(self) -> CohortManifest: - return CohortManifest( - self._df[self._df["label"] == 0].reset_index(drop=True), - self._spec, - ) - - def filter_lobe(self, lobe: str) -> CohortManifest: - return CohortManifest( - self._df[self._df["insertion_lobe"] == lobe].reset_index(drop=True), - self._spec, - ) - - def filter_size(self, min_mm: float, max_mm: float) -> CohortManifest: - mask = (self._df["effective_diam_mm"] >= min_mm) & (self._df["effective_diam_mm"] <= max_mm) - return CohortManifest( - self._df[mask].reset_index(drop=True), - self._spec, - ) diff --git a/itrialspace/src/itrialspace/site/path_resolver.py b/itrialspace/src/itrialspace/site/path_resolver.py deleted file mode 100644 index 56f1c854299bb1cc641ea6de921903aebbca86a3..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/path_resolver.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -Path resolution — turns relative CSV paths and annotation IDs -into absolute server paths for CT scans, nodule masks, organ -segmentations, and refined segmentations. - -Configuration is loaded from config/paths.yaml. The unified -iTrialSpace layout uses a single base_dir with standardised -subdirectories: - - base_dir/ - ├── raw_ct/{DATASET}/ CT scans - ├── masks/{DATASET}/ - │ ├── nodule_seg/ Individual nodule masks - │ ├── combined_seg/ Combined patient masks - │ ├── organ_seg/ VISTA3D organ segmentations (raw, deprecated) - │ └── refined_seg/ Refined organ + body segmentations (default) - ├── profiles/ Nodule profile CSVs - └── meta/ Dataset metadata CSVs -""" - -from __future__ import annotations - -import os -from pathlib import Path -from typing import Optional - -import pandas as pd - -from itrialspace.config import settings - -_DEFAULT_PATHS_YAML = Path(__file__).parent / "config" / "paths.yaml" - - -class PathResolver: - """Config-driven path resolver for iTrialSpace datasets. - - Loads per-dataset path layouts from a YAML config file. - All paths resolve relative to a single base_dir. - """ - - def __init__( - self, - config_path: Optional[str] = None, - base_dir: Optional[str] = None, - ): - """ - Args: - config_path: Path to paths.yaml. Defaults to bundled config. - base_dir: Override the global base_dir from config. - """ - # Resolve the config file: explicit arg → top-level configs/ → package default. - if config_path: - path = Path(config_path) - else: - path = settings.find_config("paths.yaml", package_default=_DEFAULT_PATHS_YAML) - - # load_yaml expands ${ITRIALSPACE_DATA_DIR} and other ${VAR} placeholders. - cfg = settings.load_yaml(path) - - self._base_dir = base_dir or cfg.get("base_dir") or str(settings.data_dir()) - self._datasets: dict[str, dict] = cfg.get("datasets", {}) - - @property - def base_dir(self) -> str: - return self._base_dir - - @property - def available_datasets(self) -> list[str]: - return list(self._datasets.keys()) - - def _get_ds(self, dataset: str) -> dict: - if dataset not in self._datasets: - raise KeyError( - f"Unknown dataset '{dataset}'. " - f"Available: {self.available_datasets}. " - f"Add it to config/paths.yaml." - ) - return self._datasets[dataset] - - # ── Individual resolvers ────────────────────────────────────────────────── - - def resolve_ct_path(self, dataset: str, ct_path_relative: str) -> str: - """Resolve ct_path column value to an absolute path. - - ct_path_relative is e.g. "DLCS24/DLCS_0001.nii.gz", - resolved as base_dir/raw_ct/{ct_path_relative}. - """ - return os.path.join(self._base_dir, "raw_ct", ct_path_relative) - - def resolve_nodule_mask_path( - self, - dataset: str, - annotation_id: str, - ct_id: Optional[str] = None, - ) -> str: - """Individual nodule mask. - - Some datasets (e.g. IMDCT) have one nodule per CT and store masks - keyed by ct_id rather than annotation_id. Set ``nodule_seg_use_ct_id: true`` - in the dataset config to activate this. - """ - ds = self._get_ds(dataset) - pattern = ds.get("nodule_seg_pattern", "{annotation_id}.nii.gz") - if ds.get("nodule_seg_use_ct_id", False) and ct_id is not None: - filename = pattern.format(ct_id=ct_id, annotation_id=annotation_id) - else: - filename = pattern.format(annotation_id=annotation_id) - return os.path.join(self._base_dir, "masks", dataset, "nodule_seg", filename) - - def resolve_organ_seg_path(self, dataset: str, ct_id: str) -> str: - """Organ + body segmentation (refined_seg preferred over organ_seg).""" - ds = self._get_ds(dataset) - pattern = ds.get("organ_seg_pattern", "{ct_id}_seg.nii.gz") - filename = pattern.format(ct_id=ct_id) - return os.path.join(self._base_dir, "masks", dataset, "refined_seg", filename) - - def resolve_combined_mask_path(self, dataset: str, ct_id: str) -> str: - """Combined (all nodules in one file) segmentation mask.""" - ds = self._get_ds(dataset) - pattern = ds.get("combined_mask_pattern", "{ct_id}_mask.nii.gz") - filename = pattern.format(ct_id=ct_id) - return os.path.join(self._base_dir, "masks", dataset, "combined_seg", filename) - - def resolve_refined_seg_path(self, dataset: str, ct_id: str) -> str: - """Refined segmentation.""" - return os.path.join( - self._base_dir, - "masks", - dataset, - "refined_seg", - f"{ct_id}_seg.nii.gz", - ) - - def resolve_profile_csv_path(self, dataset: str) -> str: - """Nodule profile CSV for a dataset.""" - ds = self._get_ds(dataset) - csv_name = ds.get("profile_csv", f"{dataset}_nodule_profiles.csv") - return os.path.join(self._base_dir, "profiles", csv_name) - - def resolve_meta_csv_path(self, dataset: str) -> str: - """Dataset metadata CSV.""" - ds = self._get_ds(dataset) - csv_name = ds.get("meta_csv", "") - if not csv_name: - return "" - return os.path.join(self._base_dir, "meta", csv_name) - - # ── Batch resolver ──────────────────────────────────────────────────────── - - @staticmethod - def extract_ct_id(ct_path: str) -> str: - """Extract ct_id from a ct_path for organ seg / mask lookup. - - E.g. "DLCS24/DLCS_0001.nii.gz" → "DLCS_0001" - "LUNA25/1.2.840...nii.gz" → "1.2.840..." - """ - basename = os.path.basename(ct_path) - if basename.endswith(".nii.gz"): - return basename[:-7] - if basename.endswith(".nii"): - return basename[:-4] - return basename - - def resolve_all_paths(self, row: pd.Series) -> dict[str, str]: - """Resolve all paths from a NoduleIndex DataFrame row. - - Returns dict with keys: - ct_path, nodule_mask_path, organ_seg_path, - combined_mask_path, refined_seg_path - """ - dataset = row["dataset"] - ct_rel = row["ct_path"] - annotation_id = row["annotation_id"] - ct_id = self.extract_ct_id(ct_rel) - - return { - "ct_path": self.resolve_ct_path(dataset, ct_rel), - "nodule_mask_path": self.resolve_nodule_mask_path(dataset, annotation_id, ct_id=ct_id), - "organ_seg_path": self.resolve_organ_seg_path(dataset, ct_id), - "combined_mask_path": self.resolve_combined_mask_path(dataset, ct_id), - "refined_seg_path": self.resolve_refined_seg_path(dataset, ct_id), - } diff --git a/itrialspace/src/itrialspace/site/sampling.py b/itrialspace/src/itrialspace/site/sampling.py deleted file mode 100644 index cb1f314db39bb008464770b57a3aac082263688e..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/sampling.py +++ /dev/null @@ -1,142 +0,0 @@ -""" -Distribution sampling utilities — stateless helper functions for -sampling nodule sizes, labels, and lobe assignments from trial -specifications. -""" - -from __future__ import annotations - -import numpy as np - -from itrialspace.site.spec import SIZE_BUCKET_ALIASES, SIZE_BUCKET_RANGES - - -class DistributionSampler: - """Stateless sampling helpers for trial cohort generation.""" - - @staticmethod - def sample_size_from_buckets( - bucket_weights: dict[str, float], - n: int, - rng: np.random.Generator, - ) -> np.ndarray: - """Sample n diameters from weighted size buckets. - - Within each bucket, diameters are uniformly distributed - over the bucket's range. - - Returns: - Array of float diameters in mm, shape (n,). - """ - buckets = list(bucket_weights.keys()) - weights = np.array([bucket_weights[b] for b in buckets], dtype=float) - weights /= weights.sum() - - bucket_indices = rng.choice(len(buckets), size=n, p=weights) - diameters = np.empty(n, dtype=float) - - for i, idx in enumerate(bucket_indices): - b = buckets[idx] - rng_lohi = SIZE_BUCKET_RANGES.get(b) or SIZE_BUCKET_ALIASES.get(b) - if rng_lohi is None: - raise KeyError( - f"Unknown size bucket {b!r}; valid: " - f"{list(SIZE_BUCKET_RANGES) + list(SIZE_BUCKET_ALIASES)}" - ) - lo, hi = rng_lohi - diameters[i] = rng.uniform(lo, hi) - - return diameters - - @staticmethod - def sample_size_lognormal( - n: int, - mean_log_mm: float, - std_log_mm: float, - min_mm: float, - max_mm: float, - rng: np.random.Generator, - ) -> np.ndarray: - """Sample n diameters from a truncated log-normal distribution.""" - samples = [] - while len(samples) < n: - batch = rng.lognormal(mean_log_mm, std_log_mm, size=n * 2) - valid = batch[(batch >= min_mm) & (batch <= max_mm)] - samples.extend(valid.tolist()) - return np.array(samples[:n]) - - @staticmethod - def sample_labels( - n: int, - malignancy_rate: float, - rng: np.random.Generator, - ) -> np.ndarray: - """Sample n binary labels at given malignancy rate. - - Returns: - Array of int (0 or 1), shape (n,). - """ - return rng.binomial(1, malignancy_rate, size=n).astype(int) - - @staticmethod - def sample_labels_by_size( - sizes: np.ndarray, - rate_by_bucket: dict[str, float], - rng: np.random.Generator, - ) -> np.ndarray: - """Assign labels conditioned on nodule size. - - Uses per-bucket malignancy rates from clinical trial data. - More realistic than a flat prevalence. - """ - labels = np.zeros(len(sizes), dtype=int) - for i, d in enumerate(sizes): - bucket = _diameter_to_bucket(d) - rate = rate_by_bucket.get(bucket, 0.0) - labels[i] = rng.binomial(1, rate) - return labels - - @staticmethod - def sample_lobe_distribution( - lobe_weights: dict[str, float], - n: int, - rng: np.random.Generator, - ) -> np.ndarray: - """Sample n lobe assignments from weighted distribution. - - Returns: - Array of str lobe names, shape (n,). - """ - lobes = list(lobe_weights.keys()) - weights = np.array([lobe_weights[l] for l in lobes], dtype=float) - weights /= weights.sum() - indices = rng.choice(len(lobes), size=n, p=weights) - return np.array([lobes[i] for i in indices]) - - @staticmethod - def assign_no_nodule_cases( - n: int, - no_nodule_fraction: float, - rng: np.random.Generator, - ) -> np.ndarray: - """Return boolean mask where True = no nodule (clean case). - - Returns: - Array of bool, shape (n,). - """ - return rng.random(n) < no_nodule_fraction - - -def _diameter_to_bucket(d: float) -> str: - """Map a diameter in mm to its size bucket string.""" - if d < 5: - return "<5mm" - if d < 10: - return "5-10mm" - if d < 15: - return "10-15mm" - if d < 20: - return "15-20mm" - if d < 30: - return "20-30mm" - return ">30mm" diff --git a/itrialspace/src/itrialspace/site/spec.py b/itrialspace/src/itrialspace/site/spec.py deleted file mode 100644 index a0866acb59a065622fac2fe8bc4ed05dc41d1b54..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/spec.py +++ /dev/null @@ -1,382 +0,0 @@ -""" -Trial specification dataclasses — pure data, no logic. - -These define what a synthetic imaging trial looks like: -demographics, nodule characteristics, prevalence, insertion mode, etc. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Optional - -from itrialspace.config import settings - - -def _default_base_dir() -> str: - """Resolve the data root at instantiation time (env-portable).""" - return str(settings.data_dir()) - - -# Datasets that have been permanently removed and must be rejected at all entry points. -_REMOVED_DATASETS = {"NLST3D"} - - -def validate_dataset_names(names: list[str] | None) -> None: - """Raise ValueError if any removed dataset is specified.""" - if names is None: - return - bad = _REMOVED_DATASETS.intersection(names) - if bad: - raise ValueError( - f"Dataset(s) {bad} removed due to quality issues and cannot be used. " - f"Remove them from your dataset list." - ) - - -# ── Size distribution ──────────────────────────────────────────────────────── - -SIZE_BUCKETS = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] - -SIZE_BUCKET_RANGES: dict[str, tuple[float, float]] = { - "<5mm": (1.0, 5.0), - "5-10mm": (5.0, 10.0), - "10-15mm": (10.0, 15.0), - "15-20mm": (15.0, 20.0), - "20-30mm": (20.0, 30.0), - ">30mm": (30.0, 60.0), -} - -# Open-ended aggregate buckets used by some published trial templates (UKLS, DANTE, -# NELSON, MILD) in their reported size distributions. These are NOT part of the -# canonical SIZE_BUCKETS; the sampler resolves them via SIZE_BUCKET_RANGES first, -# then these aliases. -SIZE_BUCKET_ALIASES: dict[str, tuple[float, float]] = { - ">20mm": (20.0, 60.0), # i.e. >=20mm, up to the max nodule diameter -} - - -@dataclass -class SizeDistribution: - """How to sample nodule diameters. - - Either discrete bucket weights or continuous log-normal parameters. - Exactly one mode should be specified. - """ - - # Discrete: keys from SIZE_BUCKETS, weights summing to ~1.0 - bucket_weights: Optional[dict[str, float]] = None - - # Continuous: truncated log-normal - mean_log_mm: Optional[float] = None - std_log_mm: Optional[float] = None - min_mm: float = 3.0 - max_mm: float = 60.0 - - -# ── Demographics ───────────────────────────────────────────────────────────── - - -@dataclass -class DemographicSpec: - """Demographics constraints (best-effort; only DLCS24/LUNA25 have these).""" - - age_range: Optional[tuple[int, int]] = None - age_mean: Optional[float] = None - age_std: Optional[float] = None - sex_ratio_male: Optional[float] = None # 0.0–1.0 - smoking_status: Optional[list[str]] = None # ["Current", "Former", ...] - pack_years_min: Optional[float] = None - - -# ── Nodule specification ───────────────────────────────────────────────────── - -HISTOPATH_DATASETS = ["DLCS24", "LUNA25", "NSCLCR", "IMDCT", "LUNGx"] -RADIOLOGY_DATASETS = ["LUNA16", "LNDbv4"] -SCREENING_DATASETS = ["DLCS24", "LUNA16", "LUNA25", "LNDbv4"] -DIAGNOSTIC_DATASETS = ["NSCLCR", "IMDCT", "LUNGx"] - -# Valid values for label_source and population_type filters -LABEL_SOURCE_VALUES = ["histopathology", "radiology", "all"] -POPULATION_TYPE_VALUES = ["screening", "diagnostic", "all"] - -# Mapping from label_source / population_type → dataset lists -LABEL_SOURCE_MAP: dict[str, list[str]] = { - "histopathology": HISTOPATH_DATASETS, - "radiology": RADIOLOGY_DATASETS, -} -POPULATION_TYPE_MAP: dict[str, list[str]] = { - "screening": SCREENING_DATASETS, - "diagnostic": DIAGNOSTIC_DATASETS, -} - -# Valid values for multi-nodule controls -N_NODULES_FILTER_VALUES = ["any", "single_only", "multi_only"] -COMPANION_STRATEGY_VALUES = ["none", "all_companions", "ipsilateral", "same_lobe"] - - -@dataclass -class NoduleSpec: - """Constraints on which nodules to include in the cohort.""" - - label: Optional[int] = None # 0, 1, or None=any - diameter_range: Optional[tuple[float, float]] = None # (min_mm, max_mm) - size_distribution: Optional[SizeDistribution] = None - lobe: Optional[list[str]] = None - zone: Optional[list[str]] = None - side: Optional[str] = None - central_peripheral: Optional[str] = None - pleural_distance_range: Optional[tuple[float, float]] = None - exclude_all_malignant_datasets: bool = False # skip NSCLCR - - # ── Label source filter ──────────────────────────────────── - # Controls which datasets are eligible based on how labels were obtained. - # "histopathology" → DLCS24, LUNA25, NSCLCR, IMDCT, LUNGx - # "radiology" → LUNA16, LNDbv4 (radiologist suspicion level / RSL) - # "all" → no restriction (default) - # None → same as "all" - label_source: Optional[str] = None - - # ── Population type filter ───────────────────────────────── - # Controls whether to draw from screening or diagnostic populations. - # "screening" → DLCS24, LUNA16, LUNA25, LNDbv4 - # "diagnostic" → NSCLCR, IMDCT, LUNGx - # "all" → no restriction (default) - # None → same as "all" - population_type: Optional[str] = None - - # Deprecated: use label_source="histopathology" instead - require_histopath_label: bool = False - - # ── Multi-nodule donor pool filter ───────────────────────── - # Controls which nodules are eligible based on how many nodules - # the donor patient has. - # "any" → no filter (default, current behavior) - # "single_only" → only n_nodules_in_patient == 1 - # "multi_only" → only n_nodules_in_patient >= 2 - # None → same as "any" - n_nodules_filter: Optional[str] = None - - -# ── Insertion specification ────────────────────────────────────────────────── - - -@dataclass -class InsertionSpec: - """Controls for the insertion planner.""" - - target_lobe: Optional[str] = None - target_zone: Optional[str] = None - target_side: Optional[str] = None - scale_tolerance: float = 0.20 # max fractional mismatch before scaling - allow_isotropic_scale: bool = True - allow_anisotropic_warp: bool = False - max_scale_factor: float = 1.5 # never scale more than 50% - min_pleural_dist_mm: float = 2.0 # safety margin from pleura - - -# ── Top-level trial specification ──────────────────────────────────────────── - - -@dataclass -class TrialSpec: - """Complete specification of a synthetic imaging trial.""" - - # ── Identity ────────────────────────────────────────────── - trial_name: str = "untitled_trial" - trial_template: Optional[str] = None # e.g. "NLST" (from knowledge base) - description: str = "" - seed: int = 42 - - # ── Cohort size ─────────────────────────────────────────── - n_cases: int = 500 - cohort_mode: str = "synthetic" # "native" | "matched" | "synthetic" - - # ── Demographics ────────────────────────────────────────── - demographics: Optional[DemographicSpec] = None - - # ── Nodule specification ────────────────────────────────── - nodule_spec: Optional[NoduleSpec] = None - - # ── Prevalence ──────────────────────────────────────────── - malignancy_prevalence: Optional[float] = None # e.g. 0.04 for 4% - no_nodule_fraction: float = 0.0 # fraction of clean cases - - # ── Dataset constraints ─────────────────────────────────── - source_datasets: Optional[list[str]] = None - exclude_datasets: Optional[list[str]] = None - host_datasets: Optional[list[str]] = None # CTs for matched/synthetic - donor_datasets: Optional[list[str]] = None # nodules for matched/synthetic - - # ── Training exclusion ───────────────────────────────────── - # Datasets the model was trained on — excluded from BOTH donor and host pools. - # Use this to ensure test cohorts have zero data leakage from training. - # e.g. exclude_training_datasets=["LUNA16", "LNDbv4"] - exclude_training_datasets: Optional[list[str]] = None - - # ── Multi-nodule companion inclusion ────────────────────── - # When a donor nodule comes from a multi-nodule patient, controls - # whether sibling nodules are also added to the manifest for that case. - # "none" → one nodule per case (default, current behavior) - # "all_companions" → include all sibling nodules from donor patient - # "ipsilateral" → include only same-side companions - # "same_lobe" → include only same-lobe companions - companion_strategy: str = "none" - - # ── Insertion ───────────────────────────────────────────── - insertion_mode: str = "profile_faithful" - insertion_spec: Optional[InsertionSpec] = None - - # ── Stratification ──────────────────────────────────────── - stratify_by: Optional[list[str]] = None # e.g. ["lobe_name", "label"] - - # ── Bootstrapping ───────────────────────────────────────── - n_bootstrap: int = 1 - bootstrap_replace: bool = True - - # ── Path config ─────────────────────────────────────────── - base_dir: str = field(default_factory=_default_base_dir) - - def __post_init__(self): - for attr in ( - "source_datasets", - "exclude_datasets", - "host_datasets", - "donor_datasets", - "exclude_training_datasets", - ): - validate_dataset_names(getattr(self, attr, None)) - - -# ── Digital twin isolation specification ───────────────────────────────────── - - -@dataclass -class DigitalTwinIsolationSpec: - """Specification for a digital twin isolation study. - - This spec is fundamentally different from TrialSpec: instead of - specifying n_cases with donor-host pairing, it selects host patients - from a single dataset and generates one isolation case per native nodule. - - The host body/anatomy segmentation masks are already nodule-free. - Each native nodule has its own individual mask file. - """ - - trial_name: str = "digital_twin_isolation" - dataset: str = "" # Single source dataset - max_patients: Optional[int] = None # Max host patients - all_patients: bool = False # Use all eligible patients - max_nodules_per_patient: Optional[int] = ( - None # Cap isolation cases per CT scan (applied per-CT, not per-patient) - ) - nodule_spec: Optional[NoduleSpec] = None # Nodule filters - seed: int = 42 - exclude_training_datasets: Optional[list[str]] = None - base_dir: str = field(default_factory=_default_base_dir) - - def __post_init__(self): - validate_dataset_names(self.exclude_training_datasets) - - -# ── Digital twin complete specification ────────────────────────────────────── - - -@dataclass -class DigitalTwinCompleteSpec: - """Specification for a digital twin complete study. - - Complementary to DigitalTwinIsolationSpec: instead of one case per - nodule, this mode produces one case per patient containing ALL native - nodules. The host body/anatomy segmentation masks are already - nodule-free; each native nodule has its own individual mask file. - - Stage 2 will insert all nodule masks into the host anatomy with - label value 23, producing a single combined conditioning mask per case. - """ - - trial_name: str = "digital_twin_complete" - dataset: str = "" # Single source dataset - max_patients: Optional[int] = None # Max host patients - all_patients: bool = False # Use all eligible patients - nodule_spec: Optional[NoduleSpec] = None # Nodule filters - seed: int = 42 - exclude_training_datasets: Optional[list[str]] = None - base_dir: str = field(default_factory=_default_base_dir) - - def __post_init__(self): - validate_dataset_names(self.exclude_training_datasets) - - -# ── Digital twin cross specification ───────────────────────────────────────── - -# Valid values for donor_transfer_mode and pairing_policy -DONOR_TRANSFER_MODES = ["single", "complete"] -PAIRING_POLICIES = ["one_to_one", "one_to_many_hosts", "donor_patient_complete"] -PLACEMENT_STRATEGIES = ["profile_faithful_transfer", "host_constrained_transfer"] - - -@dataclass -class DigitalTwinCrossSpec: - """Specification for a digital twin cross study. - - Pairs host anatomy from one patient with donor nodule(s) from a - *different* patient — potentially from a different dataset. - - This enables controlled counterfactual experiments: - - Same donor nodule, different host anatomies - - Same host anatomy, different donor nodules - - Cross-dataset anatomy/nodule mixing - - The host body/anatomy segmentation masks are already nodule-free. - Each donor nodule has its own individual mask file. - """ - - trial_name: str = "digital_twin_cross" - - # Host pool configuration - host_dataset: str = "" # Dataset for host anatomies - max_host_patients: Optional[int] = None # Max host patients to select - all_host_patients: bool = False # Use all eligible host patients - - # Donor pool configuration - donor_dataset: str = "" # Dataset for donor nodules - max_donor_patients: Optional[int] = None # Max donor patients to select - all_donor_patients: bool = False # Use all eligible donor patients - max_donor_nodules: Optional[int] = None # Max donor nodules to use - - # Cross-patient pairing configuration - donor_transfer_mode: str = "single" # "single" | "complete" - pairing_policy: str = ( - "one_to_one" # "one_to_one" | "one_to_many_hosts" | "donor_patient_complete" - ) - n_hosts_per_donor: int = 3 # For one_to_many_hosts policy - - # Placement strategy - placement_strategy: str = ( - "profile_faithful_transfer" # "profile_faithful_transfer" | "host_constrained_transfer" - ) - - # Nodule filters - nodule_spec: Optional[NoduleSpec] = None - - seed: int = 42 - exclude_training_datasets: Optional[list[str]] = None - base_dir: str = field(default_factory=_default_base_dir) - - def __post_init__(self): - validate_dataset_names(self.exclude_training_datasets) - if self.donor_transfer_mode not in DONOR_TRANSFER_MODES: - raise ValueError( - f"donor_transfer_mode must be one of {DONOR_TRANSFER_MODES}, " - f"got '{self.donor_transfer_mode}'" - ) - if self.pairing_policy not in PAIRING_POLICIES: - raise ValueError( - f"pairing_policy must be one of {PAIRING_POLICIES}, " f"got '{self.pairing_policy}'" - ) - if self.placement_strategy not in PLACEMENT_STRATEGIES: - raise ValueError( - f"placement_strategy must be one of {PLACEMENT_STRATEGIES}, " - f"got '{self.placement_strategy}'" - ) diff --git a/itrialspace/src/itrialspace/site/trial_modes.py b/itrialspace/src/itrialspace/site/trial_modes.py deleted file mode 100644 index 271d3f427bb52b1583ace17615d0fdfcad92a801..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/trial_modes.py +++ /dev/null @@ -1,715 +0,0 @@ -""" -Pre-wired trial mode factories — convenience functions that produce -TrialSpec objects for the 13 scientific trial modes. - -Each function returns either a single TrialSpec or a list of TrialSpecs, -ready to be passed to CohortBuilder.build() (or, for digital twin modes, -to CohortBuilder.build_digital_twin_isolation() / build_digital_twin_complete() -/ build_digital_twin_cross()). -""" - -from __future__ import annotations - -from typing import Optional - -from itrialspace.core.schema import LOBE_NAMES -from itrialspace.site.spec import ( - SIZE_BUCKETS, - DemographicSpec, - DigitalTwinCompleteSpec, - DigitalTwinCrossSpec, - DigitalTwinIsolationSpec, - InsertionSpec, - NoduleSpec, - TrialSpec, -) - - -def _apply_nodule_filters( - spec: TrialSpec, - label_source: Optional[str], - population_type: Optional[str], - n_nodules_filter: Optional[str] = None, -) -> None: - """Apply label_source, population_type, and n_nodules_filter to a spec's NoduleSpec (in-place).""" - if label_source is None and population_type is None and n_nodules_filter is None: - return - if spec.nodule_spec is None: - spec.nodule_spec = NoduleSpec() - if label_source: - spec.nodule_spec.label_source = label_source - if population_type: - spec.nodule_spec.population_type = population_type - if n_nodules_filter: - spec.nodule_spec.n_nodules_filter = n_nodules_filter - - -def controlled_prevalence_study( - n_cases: int = 1000, - prevalence: float = 0.05, - template: Optional[str] = "NLST", - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - companion_strategy: str = "none", - n_nodules_filter: Optional[str] = None, - **overrides, -) -> TrialSpec: - """Mode 1: Fixed malignancy prevalence. - - Produces n_cases with exactly `prevalence` fraction malignant. - Uses a template trial for demographics and size distribution if provided. - - Args: - exclude_training_datasets: Datasets to exclude (e.g. model was trained on them). - label_source: "histopathology", "radiology", or "all". - population_type: "screening", "diagnostic", or "all". - companion_strategy: "none", "all_companions", "ipsilateral", or "same_lobe". - n_nodules_filter: "any", "single_only", or "multi_only". - """ - if template: - from itrialspace.site.knowledge_base import TrialKnowledgeBase - - kb = TrialKnowledgeBase() - spec = kb.to_trial_spec( - template, - n_cases=n_cases, - cohort_mode="synthetic", - seed=seed, - overrides={"malignancy_prevalence": prevalence, **overrides}, - ) - else: - spec = TrialSpec( - trial_name=f"prevalence_{prevalence:.0%}", - n_cases=n_cases, - malignancy_prevalence=prevalence, - cohort_mode="synthetic", - seed=seed, - ) - for k, v in overrides.items(): - if hasattr(spec, k): - setattr(spec, k, v) - - # Apply filters - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - spec.companion_strategy = companion_strategy - _apply_nodule_filters(spec, label_source, population_type, n_nodules_filter) - return spec - - -def size_detection_curve( - n_per_bucket: int = 100, - size_buckets: Optional[list[str]] = None, - label: int = 1, - template: Optional[str] = "NLST", - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - **overrides, -) -> list[TrialSpec]: - """Mode 2: One TrialSpec per size bucket. - - Returns list of specs (one per bucket), each with n_per_bucket cases - of a fixed label. Use for FROC size-detection curves. - """ - if size_buckets is None: - size_buckets = SIZE_BUCKETS - - from itrialspace.site.spec import SIZE_BUCKET_RANGES - - specs = [] - for i, bucket in enumerate(size_buckets): - lo, hi = SIZE_BUCKET_RANGES[bucket] - spec = TrialSpec( - trial_name=f"size_curve_{bucket}", - trial_template=template, - n_cases=n_per_bucket, - cohort_mode="synthetic", - malignancy_prevalence=1.0 if label == 1 else 0.0, - nodule_spec=NoduleSpec( - label=label, - diameter_range=(lo, hi), - ), - seed=seed + i, - ) - for k, v in overrides.items(): - if hasattr(spec, k): - setattr(spec, k, v) - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(spec, label_source, population_type) - specs.append(spec) - return specs - - -def location_sensitivity( - n_per_lobe: int = 100, - label: int = 1, - diameter_range: tuple[float, float] = (6.0, 15.0), - template: Optional[str] = "NLST", - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - **overrides, -) -> list[TrialSpec]: - """Mode 3: One TrialSpec per lobe. - - Same nodule size range, varies only location. - Measures detection sensitivity by anatomical position. - """ - specs = [] - for i, lobe in enumerate(LOBE_NAMES): - spec = TrialSpec( - trial_name=f"lobe_{lobe}", - trial_template=template, - n_cases=n_per_lobe, - cohort_mode="synthetic", - malignancy_prevalence=1.0 if label == 1 else 0.0, - nodule_spec=NoduleSpec( - label=label, - diameter_range=diameter_range, - lobe=[lobe], - ), - insertion_mode="prescribed", - insertion_spec=InsertionSpec(target_lobe=lobe), - seed=seed + i, - ) - for k, v in overrides.items(): - if hasattr(spec, k): - setattr(spec, k, v) - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(spec, label_source, population_type) - specs.append(spec) - return specs - - -def demographic_stratification( - n_per_stratum: int = 200, - strata: Optional[list[dict]] = None, - template: str = "NLST", - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - **overrides, -) -> list[TrialSpec]: - """Mode 4: Separate cohorts by demographic strata. - - Each stratum dict can contain: - sex (str), age_range (tuple), smoking_status (list), pack_years_min (float) - """ - if strata is None: - strata = [ - {"sex_ratio_male": 1.0, "age_range": (55, 65)}, - {"sex_ratio_male": 1.0, "age_range": (65, 75)}, - {"sex_ratio_male": 0.0, "age_range": (55, 65)}, - {"sex_ratio_male": 0.0, "age_range": (65, 75)}, - ] - - from itrialspace.site.knowledge_base import TrialKnowledgeBase - - kb = TrialKnowledgeBase() - - specs = [] - for i, stratum in enumerate(strata): - demo = DemographicSpec( - age_range=stratum.get("age_range"), - sex_ratio_male=stratum.get("sex_ratio_male"), - smoking_status=stratum.get("smoking_status"), - pack_years_min=stratum.get("pack_years_min"), - ) - spec = kb.to_trial_spec( - template, - n_cases=n_per_stratum, - cohort_mode="synthetic", - seed=seed + i, - overrides={"demographics": demo, **overrides}, - ) - spec.trial_name = f"demo_stratum_{i}" - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(spec, label_source, population_type) - specs.append(spec) - return specs - - -def counterfactual_cohort( - n_cases: int = 500, - template: str = "NLST", - vary_param: str = "malignancy_prevalence", - values: Optional[list] = None, - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, -) -> list[TrialSpec]: - """Mode 5: Same base cohort with one parameter varied. - - Useful for measuring the effect of a single variable on algorithm performance. - """ - if values is None: - values = [0.01, 0.02, 0.05, 0.10, 0.20] - - from itrialspace.site.knowledge_base import TrialKnowledgeBase - - kb = TrialKnowledgeBase() - - specs = [] - for i, val in enumerate(values): - spec = kb.to_trial_spec( - template, - n_cases=n_cases, - cohort_mode="synthetic", - seed=seed, # same seed for same base cohort - overrides={vary_param: val}, - ) - spec.trial_name = f"counterfactual_{vary_param}={val}" - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(spec, label_source, population_type) - specs.append(spec) - return specs - - -def cross_dataset_generalization( - n_cases: int = 300, - datasets: Optional[list[str]] = None, - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - **overrides, -) -> list[TrialSpec]: - """Mode 6: One spec per dataset as sole donor. - - Tests whether algorithm performance varies by data source. - """ - if datasets is None: - datasets = ["DLCS24", "LUNA25", "LNDbv4", "IMDCT", "LUNGx"] - - specs = [] - for i, ds in enumerate(datasets): - spec = TrialSpec( - trial_name=f"cross_ds_{ds}", - n_cases=n_cases, - cohort_mode="synthetic", - donor_datasets=[ds], - seed=seed + i, - ) - for k, v in overrides.items(): - if hasattr(spec, k): - setattr(spec, k, v) - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(spec, label_source, population_type) - specs.append(spec) - return specs - - -def bootstrap_confidence( - base_spec: TrialSpec, - n_bootstrap: int = 100, -) -> TrialSpec: - """Mode 7: Set n_bootstrap on a spec for confidence interval estimation. - - CohortBuilder.build_all() will produce n_bootstrap independent manifests. - """ - base_spec.n_bootstrap = n_bootstrap - return base_spec - - -def algorithm_comparison( - n_cases: int = 500, - template: str = "NLST", - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - companion_strategy: str = "none", - n_nodules_filter: Optional[str] = None, - **overrides, -) -> TrialSpec: - """Mode 8: Single standardised cohort for comparing algorithms. - - Fixed seed ensures identical manifest across runs. - Use the same manifest to evaluate multiple CADe/CADx models. - - Args: - companion_strategy: "none", "all_companions", "ipsilateral", or "same_lobe". - n_nodules_filter: "any", "single_only", or "multi_only". - """ - from itrialspace.site.knowledge_base import TrialKnowledgeBase - - kb = TrialKnowledgeBase() - spec = kb.to_trial_spec( - template, - n_cases=n_cases, - cohort_mode="synthetic", - seed=seed, - overrides=overrides, - ) - spec.trial_name = f"algo_comparison_{template}_{n_cases}" - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - spec.companion_strategy = companion_strategy - _apply_nodule_filters(spec, label_source, population_type, n_nodules_filter) - return spec - - -def screening_protocol_simulation( - template: str = "NLST", - n_rounds: int = 3, - n_cases_per_round: int = 500, - prevalence_decay: float = 0.7, - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - **overrides, -) -> list[TrialSpec]: - """Mode 9: Multi-round screening protocol simulation. - - Each round has decreasing malignancy prevalence (simulating - that cancers caught in round 1 are removed from later rounds). - """ - from itrialspace.site.knowledge_base import TrialKnowledgeBase - - kb = TrialKnowledgeBase() - - base_spec = kb.to_trial_spec( - template, - n_cases=n_cases_per_round, - cohort_mode="synthetic", - seed=seed, - ) - base_prev = base_spec.malignancy_prevalence or 0.04 - - specs = [] - for r in range(n_rounds): - round_prev = base_prev * (prevalence_decay**r) - spec = kb.to_trial_spec( - template, - n_cases=n_cases_per_round, - cohort_mode="synthetic", - seed=seed + r, - overrides={"malignancy_prevalence": round_prev, **overrides}, - ) - spec.trial_name = f"screening_round_{r+1}_prev={round_prev:.3f}" - if exclude_training_datasets: - spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(spec, label_source, population_type) - specs.append(spec) - return specs - - -def multi_nodule_realism_study( - n_cases: int = 500, - multi_nodule_fraction: float = 0.25, - companion_strategy: str = "all_companions", - template: Optional[str] = "NLST", - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, - label_source: Optional[str] = None, - population_type: Optional[str] = None, - **overrides, -) -> list[TrialSpec]: - """Mode 10: Multi-nodule realism study. - - Creates two sub-cohorts: - 1. Single-nodule cases (1 - multi_nodule_fraction) - 2. Multi-nodule cases with companions (multi_nodule_fraction) - - Allows measuring the impact of multi-nodule context on detection - performance. In NLST, ~25% of screened patients have multiple nodules. - - Args: - multi_nodule_fraction: Fraction of cases drawn from multi-nodule patients. - companion_strategy: How to include companion nodules ("all_companions", - "ipsilateral", "same_lobe"). - """ - n_multi = int(n_cases * multi_nodule_fraction) - n_single = n_cases - n_multi - - # Single-nodule sub-cohort - single_spec = TrialSpec( - trial_name="multi_nodule_study_single", - trial_template=template, - n_cases=n_single, - cohort_mode="synthetic", - nodule_spec=NoduleSpec(n_nodules_filter="single_only"), - companion_strategy="none", - seed=seed, - ) - for k, v in overrides.items(): - if hasattr(single_spec, k): - setattr(single_spec, k, v) - if exclude_training_datasets: - single_spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(single_spec, label_source, population_type) - - # Multi-nodule sub-cohort - multi_spec = TrialSpec( - trial_name="multi_nodule_study_multi", - trial_template=template, - n_cases=n_multi, - cohort_mode="synthetic", - nodule_spec=NoduleSpec(n_nodules_filter="multi_only"), - companion_strategy=companion_strategy, - seed=seed + 1, - ) - for k, v in overrides.items(): - if hasattr(multi_spec, k): - setattr(multi_spec, k, v) - if exclude_training_datasets: - multi_spec.exclude_training_datasets = exclude_training_datasets - _apply_nodule_filters(multi_spec, label_source, population_type) - - return [single_spec, multi_spec] - - -def digital_twin_isolation( - dataset: str, - max_patients: Optional[int] = None, - all_patients: bool = False, - max_nodules_per_patient: Optional[int] = None, - label: Optional[int] = None, - diameter_min: Optional[float] = None, - diameter_max: Optional[float] = None, - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, -) -> DigitalTwinIsolationSpec: - """Mode 11: Digital twin isolation study. - - For each host patient in the selected dataset, generate one trial case - per native nodule. Each case uses the host's own clean anatomy mask - paired with exactly one of its native nodule masks. - - Scientific purpose: - • Isolate lesion behaviour within fixed host anatomy - • Remove multi-nodule interference - • Enable lesion-level evaluation - • Allow later comparison with complete multi-nodule digital twin trials - - Args: - dataset: Source dataset name (e.g. "DLCS24", "LUNA16"). - max_patients: Process at most N eligible host patients. - Mutually exclusive with all_patients. - all_patients: Process every eligible host patient. - Mutually exclusive with max_patients. - max_nodules_per_patient: Cap the number of isolation cases per patient. - label: Filter nodules by label (0=benign, 1=malignant, None=any). - diameter_min: Minimum nodule diameter in mm (inclusive). - diameter_max: Maximum nodule diameter in mm (inclusive). - seed: Random seed for patient sampling when max_patients is set. - exclude_training_datasets: Datasets to exclude entirely. - - Returns: - DigitalTwinIsolationSpec carrying the full configuration. - - Raises: - ValueError: If both max_patients and all_patients are specified, or neither. - """ - if max_patients is not None and all_patients: - raise ValueError("--max-patients and --all-patients are mutually exclusive") - if max_patients is None and not all_patients: - raise ValueError("Specify either --max-patients N or --all-patients") - - nodule_spec = NoduleSpec( - label=label, - diameter_range=( - (diameter_min, diameter_max) - if (diameter_min is not None or diameter_max is not None) - else None - ), - ) - - return DigitalTwinIsolationSpec( - trial_name=f"digital_twin_isolation_{dataset}", - dataset=dataset, - max_patients=max_patients, - all_patients=all_patients, - max_nodules_per_patient=max_nodules_per_patient, - nodule_spec=nodule_spec, - seed=seed, - exclude_training_datasets=exclude_training_datasets, - ) - - -def digital_twin_complete( - dataset: str, - max_patients: Optional[int] = None, - all_patients: bool = False, - label: Optional[int] = None, - diameter_min: Optional[float] = None, - diameter_max: Optional[float] = None, - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, -) -> DigitalTwinCompleteSpec: - """Mode 12: Digital twin complete study. - - For each host patient in the selected dataset, generate one trial case - containing ALL native nodules. The host's clean anatomy mask is paired - with every native nodule mask belonging to that patient. - - This is the complement to digital_twin_isolation (Mode 11): - - Isolation → one nodule per case (N nodules → N cases) - - Complete → all nodules per case (N nodules → 1 case) - - Scientific purpose: - • Reconstruct the complete native nodule burden - • Compare with isolation trials to measure multi-nodule detection suppression - • Identify context-dependent CADx behaviour and lesion-specific failures - - Args: - dataset: Source dataset name (e.g. "DLCS24", "LUNA16"). - max_patients: Process at most N eligible host patients. - Mutually exclusive with all_patients. - all_patients: Process every eligible host patient. - Mutually exclusive with max_patients. - label: Filter nodules by label (0=benign, 1=malignant, None=any). - diameter_min: Minimum nodule diameter in mm (inclusive). - diameter_max: Maximum nodule diameter in mm (inclusive). - seed: Random seed for patient sampling when max_patients is set. - exclude_training_datasets: Datasets to exclude entirely. - - Returns: - DigitalTwinCompleteSpec carrying the full configuration. - - Raises: - ValueError: If both max_patients and all_patients are specified, or neither. - """ - if max_patients is not None and all_patients: - raise ValueError("--max-patients and --all-patients are mutually exclusive") - if max_patients is None and not all_patients: - raise ValueError("Specify either --max-patients N or --all-patients") - - nodule_spec = NoduleSpec( - label=label, - diameter_range=( - (diameter_min, diameter_max) - if (diameter_min is not None or diameter_max is not None) - else None - ), - ) - - return DigitalTwinCompleteSpec( - trial_name=f"digital_twin_complete_{dataset}", - dataset=dataset, - max_patients=max_patients, - all_patients=all_patients, - nodule_spec=nodule_spec, - seed=seed, - exclude_training_datasets=exclude_training_datasets, - ) - - -def digital_twin_cross( - host_dataset: str, - donor_dataset: str, - max_host_patients: Optional[int] = None, - all_host_patients: bool = False, - max_donor_patients: Optional[int] = None, - all_donor_patients: bool = False, - max_donor_nodules: Optional[int] = None, - donor_transfer_mode: str = "single", - pairing_policy: str = "one_to_one", - n_hosts_per_donor: int = 3, - placement_strategy: str = "profile_faithful_transfer", - label: Optional[int] = None, - diameter_min: Optional[float] = None, - diameter_max: Optional[float] = None, - seed: int = 42, - exclude_training_datasets: Optional[list[str]] = None, -) -> DigitalTwinCrossSpec: - """Mode 13: Digital twin cross study. - - Pairs host anatomy from one patient with donor nodule(s) from a - *different* patient, potentially from a different dataset. - - This enables controlled counterfactual experiments: - - Same donor nodule across multiple host anatomies - - Same host anatomy with different donor nodules - - Cross-dataset anatomy/nodule mixing - - Full donor burden transfer to new anatomy - - Supported pairing policies: - - one_to_one: each donor nodule paired with one host - - one_to_many_hosts: same donor paired with N hosts (crucial for anatomy-dependent analysis) - - donor_patient_complete: all nodules from one donor patient paired to one host - - Supported donor transfer modes: - - single: one donor nodule per case - - complete: all donor nodules from the donor patient per case - - Args: - host_dataset: Dataset for host anatomies (e.g. "DLCS24"). - donor_dataset: Dataset for donor nodules (e.g. "LUNA25"). - max_host_patients: Process at most N host patients. - Mutually exclusive with all_host_patients. - all_host_patients: Use all eligible host patients. - Mutually exclusive with max_host_patients. - max_donor_patients: Process at most N donor patients. - Mutually exclusive with all_donor_patients. - all_donor_patients: Use all eligible donor patients. - Mutually exclusive with max_donor_patients. - max_donor_nodules: Max total donor nodules used. - donor_transfer_mode: "single" or "complete". - pairing_policy: "one_to_one", "one_to_many_hosts", or "donor_patient_complete". - n_hosts_per_donor: Number of hosts per donor (one_to_many_hosts policy). - placement_strategy: "profile_faithful_transfer" or "host_constrained_transfer". - label: Filter donor nodules by label (0=benign, 1=malignant, None=any). - diameter_min: Min donor nodule diameter in mm (inclusive). - diameter_max: Max donor nodule diameter in mm (inclusive). - seed: Random seed for patient sampling. - exclude_training_datasets: Datasets to exclude entirely. - - Returns: - DigitalTwinCrossSpec carrying the full configuration. - - Raises: - ValueError: If mutual exclusion constraints are violated. - """ - if max_host_patients is not None and all_host_patients: - raise ValueError("--max-host-patients and --all-host-patients are mutually exclusive") - if max_host_patients is None and not all_host_patients: - raise ValueError("Specify either --max-host-patients N or --all-host-patients") - if max_donor_patients is not None and all_donor_patients: - raise ValueError("--max-donor-patients and --all-donor-patients are mutually exclusive") - if max_donor_patients is None and not all_donor_patients and max_donor_nodules is None: - raise ValueError( - "Specify either --max-donor-patients N, --all-donor-patients, or --max-donor-nodules N" - ) - - nodule_spec = NoduleSpec( - label=label, - diameter_range=( - (diameter_min, diameter_max) - if (diameter_min is not None or diameter_max is not None) - else None - ), - ) - - trial_name = f"digital_twin_cross_{host_dataset}_x_{donor_dataset}" - - return DigitalTwinCrossSpec( - trial_name=trial_name, - host_dataset=host_dataset, - donor_dataset=donor_dataset, - max_host_patients=max_host_patients, - all_host_patients=all_host_patients, - max_donor_patients=max_donor_patients, - all_donor_patients=all_donor_patients, - max_donor_nodules=max_donor_nodules, - donor_transfer_mode=donor_transfer_mode, - pairing_policy=pairing_policy, - n_hosts_per_donor=n_hosts_per_donor, - placement_strategy=placement_strategy, - nodule_spec=nodule_spec, - seed=seed, - exclude_training_datasets=exclude_training_datasets, - ) diff --git a/itrialspace/src/itrialspace/site/validation.py b/itrialspace/src/itrialspace/site/validation.py deleted file mode 100644 index 0c24bec97b9b4beb32b17cc1a23d53e9be5a74d3..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/site/validation.py +++ /dev/null @@ -1,264 +0,0 @@ -""" -Spec validation — checks a TrialSpec against the available NoduleIndex -for feasibility and correctness. -""" - -from __future__ import annotations - -import pandas as pd - -from itrialspace.core.schema import CP_VALUES, DATASET_NAMES, LOBE_NAMES, SIDE_NAMES, ZONE_NAMES -from itrialspace.site.spec import ( - COMPANION_STRATEGY_VALUES, - HISTOPATH_DATASETS, - LABEL_SOURCE_MAP, - LABEL_SOURCE_VALUES, - N_NODULES_FILTER_VALUES, - POPULATION_TYPE_MAP, - POPULATION_TYPE_VALUES, - TrialSpec, -) - - -class SpecValidator: - """Validates a TrialSpec against the available NoduleIndex.""" - - def __init__(self, index_df: pd.DataFrame): - self._df = index_df - - def validate(self, spec: TrialSpec) -> list[str]: - """Returns list of error messages. Empty = valid.""" - errors: list[str] = [] - - # Cohort mode - if spec.cohort_mode not in ("native", "matched", "synthetic"): - errors.append(f"Invalid cohort_mode: '{spec.cohort_mode}'") - - # Insertion mode - if spec.insertion_mode not in ("profile_faithful", "prescribed", "randomised"): - errors.append(f"Invalid insertion_mode: '{spec.insertion_mode}'") - - # Prevalence bounds - if spec.malignancy_prevalence is not None: - if not 0.0 <= spec.malignancy_prevalence <= 1.0: - errors.append( - f"malignancy_prevalence must be in [0,1], got {spec.malignancy_prevalence}" - ) - - if not 0.0 <= spec.no_nodule_fraction <= 1.0: - errors.append(f"no_nodule_fraction must be in [0,1], got {spec.no_nodule_fraction}") - - # Dataset names - for ds_list_name in ( - "source_datasets", - "exclude_datasets", - "host_datasets", - "donor_datasets", - "exclude_training_datasets", - ): - ds_list = getattr(spec, ds_list_name) - if ds_list: - for ds in ds_list: - if ds not in DATASET_NAMES: - errors.append(f"Unknown dataset '{ds}' in {ds_list_name}") - - # N cases - if spec.n_cases < 1: - errors.append(f"n_cases must be >= 1, got {spec.n_cases}") - - # Nodule spec validation - ns = spec.nodule_spec - if ns: - if ns.label is not None and ns.label not in (0, 1): - errors.append(f"NoduleSpec.label must be 0, 1, or None, got {ns.label}") - - if ns.lobe: - for l in ns.lobe: - if l not in LOBE_NAMES: - errors.append(f"Unknown lobe '{l}' in NoduleSpec") - - if ns.zone: - for z in ns.zone: - if z not in ZONE_NAMES: - errors.append(f"Unknown zone '{z}' in NoduleSpec") - - if ns.side and ns.side not in SIDE_NAMES: - errors.append(f"Unknown side '{ns.side}' in NoduleSpec") - - if ns.central_peripheral and ns.central_peripheral not in CP_VALUES: - errors.append(f"Unknown central_peripheral '{ns.central_peripheral}'") - - if ns.diameter_range: - lo, hi = ns.diameter_range - if lo >= hi: - errors.append(f"diameter_range min ({lo}) >= max ({hi})") - - if ns.size_distribution and ns.size_distribution.bucket_weights: - total = sum(ns.size_distribution.bucket_weights.values()) - if abs(total - 1.0) > 0.05: - errors.append(f"Size distribution weights sum to {total:.3f}, expected ~1.0") - - if ns.label_source and ns.label_source not in LABEL_SOURCE_VALUES: - errors.append( - f"NoduleSpec.label_source must be one of {LABEL_SOURCE_VALUES}, " - f"got '{ns.label_source}'" - ) - - if ns.population_type and ns.population_type not in POPULATION_TYPE_VALUES: - errors.append( - f"NoduleSpec.population_type must be one of {POPULATION_TYPE_VALUES}, " - f"got '{ns.population_type}'" - ) - - if ns.n_nodules_filter and ns.n_nodules_filter not in N_NODULES_FILTER_VALUES: - errors.append( - f"NoduleSpec.n_nodules_filter must be one of {N_NODULES_FILTER_VALUES}, " - f"got '{ns.n_nodules_filter}'" - ) - - # Companion strategy validation - if spec.companion_strategy not in COMPANION_STRATEGY_VALUES: - errors.append( - f"companion_strategy must be one of {COMPANION_STRATEGY_VALUES}, " - f"got '{spec.companion_strategy}'" - ) - - # Insertion spec validation - ispec = spec.insertion_spec - if ispec: - if ispec.target_lobe and ispec.target_lobe not in LOBE_NAMES: - errors.append(f"Unknown target_lobe '{ispec.target_lobe}'") - if ispec.target_zone and ispec.target_zone not in ZONE_NAMES: - errors.append(f"Unknown target_zone '{ispec.target_zone}'") - if ispec.max_scale_factor < 1.0: - errors.append(f"max_scale_factor must be >= 1.0, got {ispec.max_scale_factor}") - - return errors - - def feasibility_report(self, spec: TrialSpec) -> dict: - """Detailed feasibility analysis against available data. - - Returns dict with: - pool_size: total matching nodules - malignant_pool: count of malignant nodules in pool - benign_pool: count of benign nodules in pool - n_requested_malignant / n_requested_benign: derived from spec - feasible: bool - warnings: list of strings - """ - df = self._df.copy() - warnings: list[str] = [] - - # Apply dataset filters - if spec.source_datasets: - df = df[df["dataset"].isin(spec.source_datasets)] - if spec.exclude_datasets: - df = df[~df["dataset"].isin(spec.exclude_datasets)] - if spec.donor_datasets: - df = df[df["dataset"].isin(spec.donor_datasets)] - if spec.exclude_training_datasets: - df = df[~df["dataset"].isin(spec.exclude_training_datasets)] - - # Apply nodule spec filters - ns = spec.nodule_spec - if ns: - if ns.diameter_range: - lo, hi = ns.diameter_range - df = df[ - (df["reinsertion_nodule_diam_mm"] >= lo) - & (df["reinsertion_nodule_diam_mm"] <= hi) - ] - if ns.lobe: - df = df[df["reinsertion_lobe"].isin(ns.lobe)] - if ns.zone: - df = df[df["reinsertion_lung_zone"].isin(ns.zone)] - if ns.side: - df = df[df["reinsertion_lung_side"] == ns.side] - if ns.exclude_all_malignant_datasets: - df = df[~df["dataset"].isin(["NSCLCR"])] - - # Label source filter - if ns.label_source and ns.label_source != "all": - allowed = LABEL_SOURCE_MAP.get(ns.label_source) - if allowed: - df = df[df["dataset"].isin(allowed)] - elif ns.require_histopath_label: - df = df[df["dataset"].isin(HISTOPATH_DATASETS)] - - # Population type filter - if ns.population_type and ns.population_type != "all": - allowed = POPULATION_TYPE_MAP.get(ns.population_type) - if allowed: - df = df[df["dataset"].isin(allowed)] - - # Multi-nodule filter - if ns.n_nodules_filter == "single_only": - df = df[df["n_nodules_in_patient"] == 1] - elif ns.n_nodules_filter == "multi_only": - df = df[df["n_nodules_in_patient"] >= 2] - - pool_size = len(df) - mal_pool = int((df["label"] == 1).sum()) if "label" in df.columns else 0 - ben_pool = int((df["label"] == 0).sum()) if "label" in df.columns else 0 - - # Compute requested counts - n_nodule_cases = int(spec.n_cases * (1.0 - spec.no_nodule_fraction)) - n_mal = 0 - n_ben = 0 - if spec.malignancy_prevalence is not None: - n_mal = int(n_nodule_cases * spec.malignancy_prevalence) - n_ben = n_nodule_cases - n_mal - else: - n_ben = n_nodule_cases # no prevalence constraint - - # Multi-nodule pool statistics - n_multi = ( - int((df["n_nodules_in_patient"] >= 2).sum()) - if "n_nodules_in_patient" in df.columns - else 0 - ) - n_single = ( - int((df["n_nodules_in_patient"] == 1).sum()) - if "n_nodules_in_patient" in df.columns - else pool_size - ) - - feasible = True - if pool_size < n_nodule_cases: - warnings.append( - f"Pool size ({pool_size}) < requested cases ({n_nodule_cases}). " - f"Sampling with replacement may be needed." - ) - if spec.malignancy_prevalence is not None: - if mal_pool < n_mal: - warnings.append(f"Malignant pool ({mal_pool}) < requested malignant ({n_mal})") - feasible = False - if ben_pool < n_ben: - warnings.append(f"Benign pool ({ben_pool}) < requested benign ({n_ben})") - - # Companion strategy feasibility - if spec.companion_strategy != "none": - multi_patients = ( - df[df["n_nodules_in_patient"] >= 2]["patient_id"].nunique() - if "patient_id" in df.columns - else 0 - ) - if multi_patients < n_nodule_cases * 0.1: - warnings.append( - f"companion_strategy='{spec.companion_strategy}' requested but only " - f"{multi_patients} multi-nodule patients in pool" - ) - - return { - "pool_size": pool_size, - "malignant_pool": mal_pool, - "benign_pool": ben_pool, - "n_requested_malignant": n_mal, - "n_requested_benign": n_ben, - "n_nodule_cases": n_nodule_cases, - "datasets_in_pool": df["dataset"].unique().tolist() if len(df) > 0 else [], - "multi_nodule_pool": n_multi, - "single_nodule_pool": n_single, - "feasible": feasible, - "warnings": warnings, - } diff --git a/itrialspace/src/itrialspace/synthesis/__init__.py b/itrialspace/src/itrialspace/synthesis/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/synthesis/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 52c0a82c6504d80a5aa5e7c345799bc6dafddbb0..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/configs/config_maisi3d-rflow.json b/itrialspace/src/itrialspace/synthesis/configs/config_maisi3d-rflow.json deleted file mode 100644 index 1f2ee4619b464ba47e619191085214bcf042752e..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/configs/config_maisi3d-rflow.json +++ /dev/null @@ -1,150 +0,0 @@ -{ - "spatial_dims": 3, - "image_channels": 1, - "latent_channels": 4, - "include_body_region": false, - "mask_generation_latent_shape": [ - 4, - 64, - 64, - 64 - ], - "autoencoder_def": { - "_target_": "monai.apps.generation.maisi.networks.autoencoderkl_maisi.AutoencoderKlMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": "@image_channels", - "out_channels": "@image_channels", - "latent_channels": "@latent_channels", - "num_channels": [ - 64, - 128, - 256 - ], - "num_res_blocks": [2,2,2], - "norm_num_groups": 32, - "norm_eps": 1e-06, - "attention_levels": [ - false, - false, - false - ], - "with_encoder_nonlocal_attn": false, - "with_decoder_nonlocal_attn": false, - "use_checkpointing": false, - "use_convtranspose": false, - "norm_float16": true, - "num_splits": 4, - "dim_split": 1 - }, - "diffusion_unet_def": { - "_target_": "monai.apps.generation.maisi.networks.diffusion_model_unet_maisi.DiffusionModelUNetMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": "@latent_channels", - "out_channels": "@latent_channels", - "num_channels": [64, 128, 256, 512], - "attention_levels": [ - false, - false, - true, - true - ], - "num_head_channels": [ - 0, - 0, - 32, - 32 - ], - "num_res_blocks": 2, - "use_flash_attention": true, - "include_top_region_index_input": "@include_body_region", - "include_bottom_region_index_input": "@include_body_region", - "include_spacing_input": true, - "num_class_embeds": 128, - "resblock_updown": true, - "include_fc": true - }, - "controlnet_def": { - "_target_": "monai.apps.generation.maisi.networks.controlnet_maisi.ControlNetMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": "@latent_channels", - "num_channels": [64, 128, 256, 512], - "attention_levels": [ - false, - false, - true, - true - ], - "num_head_channels": [ - 0, - 0, - 32, - 32 - ], - "num_res_blocks": 2, - "use_flash_attention": true, - "conditioning_embedding_in_channels": 8, - "conditioning_embedding_num_channels": [8, 32, 64], - "num_class_embeds": 128, - "resblock_updown": true, - "include_fc": true - }, - "mask_generation_autoencoder_def": { - "_target_": "monai.apps.generation.maisi.networks.autoencoderkl_maisi.AutoencoderKlMaisi", - "spatial_dims": "@spatial_dims", - "in_channels": 8, - "out_channels": 125, - "latent_channels": "@latent_channels", - "num_channels": [ - 32, - 64, - 128 - ], - "num_res_blocks": [1, 2, 2], - "norm_num_groups": 32, - "norm_eps": 1e-06, - "attention_levels": [ - false, - false, - false - ], - "with_encoder_nonlocal_attn": false, - "with_decoder_nonlocal_attn": false, - "use_flash_attention": false, - "use_checkpointing": true, - "use_convtranspose": true, - "norm_float16": true, - "num_splits": 8, - "dim_split": 1 - }, - "mask_generation_diffusion_def": { - "_target_": "monai.networks.nets.diffusion_model_unet.DiffusionModelUNet", - "spatial_dims": "@spatial_dims", - "in_channels": "@latent_channels", - "out_channels": "@latent_channels", - "channels":[64, 128, 256, 512], - "attention_levels":[false, false, true, true], - "num_head_channels":[0, 0, 32, 32], - "num_res_blocks": 2, - "use_flash_attention": true, - "with_conditioning": true, - "upcast_attention": true, - "cross_attention_dim": 10 - }, - "mask_generation_scale_factor": 1.0055984258651733, - "noise_scheduler": { - "_target_": "monai.networks.schedulers.rectified_flow.RFlowScheduler", - "num_train_timesteps": 1000, - "use_discrete_timesteps": false, - "use_timestep_transform": true, - "sample_method": "uniform", - "scale":1.4 - }, - "mask_generation_noise_scheduler": { - "_target_": "monai.networks.schedulers.ddpm.DDPMScheduler", - "num_train_timesteps": 1000, - "beta_start": 0.0015, - "beta_end": 0.0195, - "schedule": "scaled_linear_beta", - "clip_sample": false - } -} diff --git a/itrialspace/src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json b/itrialspace/src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json deleted file mode 100644 index 95f5dee643dfb75659cc11b0c8c77feaf1a5ff54..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "controlnet_train": { - "batch_size": 2, - "cache_rate": 0.0, - "fold": 1, - "lr": 1e-5, - "n_epochs": 500, - "weighted_loss_label": [23], - "weighted_loss": 100 - }, - "controlnet_infer": { - "num_inference_steps": 30, - "autoencoder_sliding_window_infer_size": [80, 80, 64], - "autoencoder_sliding_window_infer_overlap": 0.25, - "modality": 1 - } -} diff --git a/itrialspace/src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json b/itrialspace/src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json deleted file mode 100644 index 812c7b7ec6984b96ec9a1378152cff68c01f1567..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "model_dir": "${NODMAISI_MODELS_DIR}/", - "output_dir": "${ITRIALSPACE_OUTPUT_DIR}/synthesis_demo/NoMAISI_DLCSD24_demo_512xy_256z_771p25m", - "tfevent_path": "${ITRIALSPACE_OUTPUT_DIR}/synthesis_demo/tfevent", - "trained_autoencoder_path": "${NODMAISI_MODELS_DIR}/autoencoder.pt", - "trained_diffusion_path": "${NODMAISI_MODELS_DIR}/diffusion_unet.pt", - "trained_controlnet_path": "${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt", - "exp_name": "NoMAISI_DLCSD24_demo_512xy_256z_771p25m", - "data_base_dir": [ - "${ITRIALSPACE_ROOT}/src/itrialspace/synthesis/data" - ], - "json_data_list": [ - "${ITRIALSPACE_ROOT}/src/itrialspace/synthesis/data/infr_NoMAISI_DLCSD24_demo_512xy_256z_771p25m_dataset.json" - ] -} \ No newline at end of file diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__init__.py b/itrialspace/src/itrialspace/synthesis/scripts/__init__.py deleted file mode 100644 index 8ab6ee9afaf6fa15a7502da0525f01279f04f578..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index ad4ab4c5a0fb9d235bb1dfc8b61129f09c92483a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/augmentation.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/augmentation.cpython-310.pyc deleted file mode 100644 index 281a112fb0484bd24c2dd2e4ecc5ebde0c53f61f..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/augmentation.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/compute_fid_2-5d_ct.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/compute_fid_2-5d_ct.cpython-310.pyc deleted file mode 100644 index 1ad9f76b0843c879a2138245df5809e30510f81a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/compute_fid_2-5d_ct.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_create_training_data.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_create_training_data.cpython-310.pyc deleted file mode 100644 index 991ed478e63b414193eda835503fd95a01804c1e..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_create_training_data.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_infer.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_infer.cpython-310.pyc deleted file mode 100644 index 257bbfc6bc22f3521a0b362019ef5ad5b224648a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_infer.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_setting.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_setting.cpython-310.pyc deleted file mode 100644 index 2c15011ff32e44db9e138aaff8a3ed26da43dbca..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_setting.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_train.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_train.cpython-310.pyc deleted file mode 100644 index 785083143920d0e6ab0c99b202e674a0c22da573..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_train.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/find_masks.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/find_masks.cpython-310.pyc deleted file mode 100644 index 115c1dcebeada61cce3ba903aa79e3db082cfb01..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/find_masks.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_controlnet.cpython-310.pyc deleted file mode 100644 index 42f80da35807310b7344346199516bc78abeaf51..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_controlnet.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_testV2_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_testV2_controlnet.cpython-310.pyc deleted file mode 100644 index 1a6e0957cb883a4c3c995a4709d7d740764a0534..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_testV2_controlnet.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_test_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_test_controlnet.cpython-310.pyc deleted file mode 100644 index 50f3e896a0bbc275efcda131016f5c85a22b309d..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_test_controlnet.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/inference.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/inference.cpython-310.pyc deleted file mode 100644 index 850ae937849d3771f54288630ccf38d476f722f9..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/inference.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/quality_check.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/quality_check.cpython-310.pyc deleted file mode 100644 index 09b8912c8cecf3d089bf19de348d31eed4b38232..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/quality_check.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/rectified_flow.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/rectified_flow.cpython-310.pyc deleted file mode 100644 index abc44bf5c1f4eac3090dad3ce95cf2694c7e43c1..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/rectified_flow.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/sample.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/sample.cpython-310.pyc deleted file mode 100644 index 6fabbbc06510520fc02060fccb40d32ede45b758..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/sample.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/scheduler.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/scheduler.cpython-310.pyc deleted file mode 100644 index ebb02e92296f32e09cd5d36be22abf88e0dbcd8f..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/scheduler.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/train_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/train_controlnet.cpython-310.pyc deleted file mode 100644 index b1ccac8c5556fcba53c7a50891412aa7abaa757a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/train_controlnet.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/transforms.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/transforms.cpython-310.pyc deleted file mode 100644 index 1058550bc7c668220c38644bc018efce5ed1e4ec..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/transforms.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils.cpython-310.pyc deleted file mode 100644 index 9e9e267b3e8a6b7bcc396c0a17f5d207a9ea12da..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils_plot.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils_plot.cpython-310.pyc deleted file mode 100644 index 956012164f7101551873b626ff84242bd95318e1..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils_plot.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/augmentation.py b/itrialspace/src/itrialspace/synthesis/scripts/augmentation.py deleted file mode 100644 index ceef69eaa41afa6d63299bdcf5322880f2910b91..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/augmentation.py +++ /dev/null @@ -1,399 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import numpy as np -import torch -import torch.nn.functional as F -from monai.transforms import Rand3DElastic, RandAffine, RandZoom -from monai.utils import ensure_tuple_rep - - -def erode3d(input_tensor, erosion=3): - # Define the structuring element - erosion = ensure_tuple_rep(erosion, 3) - structuring_element = torch.ones(1, 1, erosion[0], erosion[1], erosion[2]).to( - input_tensor.device - ) - - # Pad the input tensor to handle border pixels - input_padded = F.pad( - input_tensor.float().unsqueeze(0).unsqueeze(0), - ( - erosion[0] // 2, - erosion[0] // 2, - erosion[1] // 2, - erosion[1] // 2, - erosion[2] // 2, - erosion[2] // 2, - ), - mode="constant", - value=1.0, - ) - - # Apply erosion operation - output = F.conv3d(input_padded, structuring_element, padding=0) - - # Set output values based on the minimum value within the structuring element - output = torch.where(output == torch.sum(structuring_element), 1.0, 0.0) - - return output.squeeze(0).squeeze(0) - - -def dilate3d(input_tensor, erosion=3): - # Define the structuring element - erosion = ensure_tuple_rep(erosion, 3) - structuring_element = torch.ones(1, 1, erosion[0], erosion[1], erosion[2]).to( - input_tensor.device - ) - - # Pad the input tensor to handle border pixels - input_padded = F.pad( - input_tensor.float().unsqueeze(0).unsqueeze(0), - ( - erosion[0] // 2, - erosion[0] // 2, - erosion[1] // 2, - erosion[1] // 2, - erosion[2] // 2, - erosion[2] // 2, - ), - mode="constant", - value=1.0, - ) - - # Apply erosion operation - output = F.conv3d(input_padded, structuring_element, padding=0) - - # Set output values based on the minimum value within the structuring element - output = torch.where(output > 0, 1.0, 0.0) - - return output.squeeze(0).squeeze(0) - - -def augmentation_tumor_bone(pt_nda, output_size, random_seed=None): - volume = pt_nda.squeeze(0) - real_l_volume_ = torch.zeros_like(volume) - real_l_volume_[volume == 128] = 1 - real_l_volume_ = real_l_volume_.to(torch.uint8) - - elastic = RandAffine( - mode="nearest", - prob=1.0, - translate_range=(5, 5, 0), - rotate_range=(0, 0, 0.1), - scale_range=(0.15, 0.15, 0), - padding_mode="zeros", - ) - elastic.set_random_state(seed=random_seed) - - tumor_szie = torch.sum((real_l_volume_ > 0).float()) - ########################### - # remove pred in pseudo_label in real lesion region - volume[real_l_volume_ > 0] = 200 - ########################### - if tumor_szie > 0: - # get organ mask - organ_mask = ( - torch.logical_and(33 <= volume, volume <= 56).float() - + torch.logical_and(63 <= volume, volume <= 97).float() - + (volume == 127).float() - + (volume == 114).float() - + real_l_volume_ - ) - organ_mask = (organ_mask > 0).float() - cnt = 0 - while True: - threshold = 0.8 if cnt < 40 else 0.75 - real_l_volume = real_l_volume_ - # random distor mask - distored_mask = elastic( - (real_l_volume > 0).cuda(), spatial_size=tuple(output_size) - ).as_tensor() - real_l_volume = distored_mask * organ_mask - cnt += 1 - print(torch.sum(real_l_volume), "|", tumor_szie * threshold) - if torch.sum(real_l_volume) >= tumor_szie * threshold: - real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) - real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0).to(torch.uint8) - break - else: - real_l_volume = real_l_volume_ - - volume[real_l_volume == 1] = 128 - - pt_nda = volume.unsqueeze(0) - return pt_nda - - -def augmentation_tumor_liver(pt_nda, output_size, random_seed=None): - volume = pt_nda.squeeze(0) - real_l_volume_ = torch.zeros_like(volume) - real_l_volume_[volume == 1] = 1 - real_l_volume_[volume == 26] = 2 - real_l_volume_ = real_l_volume_.to(torch.uint8) - - elastic = Rand3DElastic( - mode="nearest", - prob=1.0, - sigma_range=(5, 8), - magnitude_range=(100, 200), - translate_range=(10, 10, 10), - rotate_range=(np.pi / 36, np.pi / 36, np.pi / 36), - scale_range=(0.2, 0.2, 0.2), - padding_mode="zeros", - ) - elastic.set_random_state(seed=random_seed) - - tumor_szie = torch.sum(real_l_volume_ == 2) - ########################### - # remove pred organ labels - volume[volume == 1] = 0 - volume[volume == 26] = 0 - # before move tumor maks, full the original location by organ labels - volume[real_l_volume_ == 1] = 1 - volume[real_l_volume_ == 2] = 1 - ########################### - while True: - real_l_volume = real_l_volume_ - # random distor mask - real_l_volume = elastic( - (real_l_volume == 2).cuda(), spatial_size=tuple(output_size) - ).as_tensor() - # get organ mask - organ_mask = (real_l_volume_ == 1).float() + (real_l_volume_ == 2).float() - - organ_mask = dilate3d(organ_mask.squeeze(0), erosion=5) - organ_mask = erode3d(organ_mask, erosion=5).unsqueeze(0) - real_l_volume = real_l_volume * organ_mask - print(torch.sum(real_l_volume), "|", tumor_szie * 0.80) - if torch.sum(real_l_volume) >= tumor_szie * 0.80: - real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) - real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0) - break - - volume[real_l_volume == 1] = 26 - - pt_nda = volume.unsqueeze(0) - return pt_nda - - -def augmentation_tumor_lung(pt_nda, output_size, random_seed=None): - volume = pt_nda.squeeze(0) - real_l_volume_ = torch.zeros_like(volume) - real_l_volume_[volume == 23] = 1 - real_l_volume_ = real_l_volume_.to(torch.uint8) - - elastic = Rand3DElastic( - mode="nearest", - prob=1.0, - sigma_range=(5, 8), - magnitude_range=(100, 200), - translate_range=(20, 20, 20), - rotate_range=(np.pi / 36, np.pi / 36, np.pi), - scale_range=(0.15, 0.15, 0.15), - padding_mode="zeros", - ) - elastic.set_random_state(seed=random_seed) - - tumor_szie = torch.sum(real_l_volume_) - # before move lung tumor maks, full the original location by lung labels - new_real_l_volume_ = dilate3d(real_l_volume_.squeeze(0), erosion=3) - new_real_l_volume_ = new_real_l_volume_.unsqueeze(0) - new_real_l_volume_[real_l_volume_ > 0] = 0 - new_real_l_volume_[volume < 28] = 0 - new_real_l_volume_[volume > 32] = 0 - tmp = volume[(volume * new_real_l_volume_).nonzero(as_tuple=True)].view(-1) - - mode = torch.mode(tmp, 0)[0].item() - print(mode) - assert 28 <= mode <= 32 - volume[real_l_volume_.bool()] = mode - ########################### - if tumor_szie > 0: - # aug - while True: - real_l_volume = real_l_volume_ - # random distor mask - real_l_volume = elastic(real_l_volume, spatial_size=tuple(output_size)).as_tensor() - # get lung mask v2 (133 order) - lung_mask = ( - (volume == 28).float() - + (volume == 29).float() - + (volume == 30).float() - + (volume == 31).float() - + (volume == 32).float() - ) - - lung_mask = dilate3d(lung_mask.squeeze(0), erosion=5) - lung_mask = erode3d(lung_mask, erosion=5).unsqueeze(0) - real_l_volume = real_l_volume * lung_mask - print(torch.sum(real_l_volume), "|", tumor_szie * 0.85) - if torch.sum(real_l_volume) >= tumor_szie * 0.85: - real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) - real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0).to(torch.uint8) - break - else: - real_l_volume = real_l_volume_ - - volume[real_l_volume == 1] = 23 - - pt_nda = volume.unsqueeze(0) - return pt_nda - - -def augmentation_tumor_pancreas(pt_nda, output_size, random_seed=None): - volume = pt_nda.squeeze(0) - real_l_volume_ = torch.zeros_like(volume) - real_l_volume_[volume == 4] = 1 - real_l_volume_[volume == 24] = 2 - real_l_volume_ = real_l_volume_.to(torch.uint8) - - elastic = Rand3DElastic( - mode="nearest", - prob=1.0, - sigma_range=(5, 8), - magnitude_range=(100, 200), - translate_range=(15, 15, 15), - rotate_range=(np.pi / 36, np.pi / 36, np.pi / 36), - scale_range=(0.1, 0.1, 0.1), - padding_mode="zeros", - ) - elastic.set_random_state(seed=random_seed) - - tumor_szie = torch.sum(real_l_volume_ == 2) - ########################### - # remove pred organ labels - volume[volume == 24] = 0 - volume[volume == 4] = 0 - # before move tumor maks, full the original location by organ labels - volume[real_l_volume_ == 1] = 4 - volume[real_l_volume_ == 2] = 4 - ########################### - while True: - real_l_volume = real_l_volume_ - # random distor mask - real_l_volume = elastic( - (real_l_volume == 2).cuda(), spatial_size=tuple(output_size) - ).as_tensor() - # get organ mask - organ_mask = (real_l_volume_ == 1).float() + (real_l_volume_ == 2).float() - - organ_mask = dilate3d(organ_mask.squeeze(0), erosion=5) - organ_mask = erode3d(organ_mask, erosion=5).unsqueeze(0) - real_l_volume = real_l_volume * organ_mask - print(torch.sum(real_l_volume), "|", tumor_szie * 0.80) - if torch.sum(real_l_volume) >= tumor_szie * 0.80: - real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) - real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0) - break - - volume[real_l_volume == 1] = 24 - - pt_nda = volume.unsqueeze(0) - return pt_nda - - -def augmentation_tumor_colon(pt_nda, output_size, random_seed=None): - volume = pt_nda.squeeze(0) - real_l_volume_ = torch.zeros_like(volume) - real_l_volume_[volume == 27] = 1 - real_l_volume_ = real_l_volume_.to(torch.uint8) - - elastic = Rand3DElastic( - mode="nearest", - prob=1.0, - sigma_range=(5, 8), - magnitude_range=(100, 200), - translate_range=(5, 5, 5), - rotate_range=(np.pi / 36, np.pi / 36, np.pi / 36), - scale_range=(0.1, 0.1, 0.1), - padding_mode="zeros", - ) - elastic.set_random_state(seed=random_seed) - - tumor_szie = torch.sum(real_l_volume_) - ########################### - # before move tumor maks, full the original location by organ labels - volume[real_l_volume_.bool()] = 62 - ########################### - if tumor_szie > 0: - # get organ mask - organ_mask = (volume == 62).float() - organ_mask = dilate3d(organ_mask.squeeze(0), erosion=5) - organ_mask = erode3d(organ_mask, erosion=5).unsqueeze(0) - # cnt = 0 - cnt = 0 - while True: - threshold = 0.8 - real_l_volume = real_l_volume_ - if cnt < 20: - # random distor mask - distored_mask = elastic( - (real_l_volume == 1).cuda(), spatial_size=tuple(output_size) - ).as_tensor() - real_l_volume = distored_mask * organ_mask - elif 20 <= cnt < 40: - threshold = 0.75 - else: - break - - real_l_volume = real_l_volume * organ_mask - print(torch.sum(real_l_volume), "|", tumor_szie * threshold) - cnt += 1 - if torch.sum(real_l_volume) >= tumor_szie * threshold: - real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) - real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0).to(torch.uint8) - break - else: - real_l_volume = real_l_volume_ - # break - volume[real_l_volume == 1] = 27 - - pt_nda = volume.unsqueeze(0) - return pt_nda - - -def augmentation_body(pt_nda, random_seed=None): - volume = pt_nda.squeeze(0) - - zoom = RandZoom(min_zoom=0.99, max_zoom=1.01, mode="nearest", align_corners=None, prob=1.0) - zoom.set_random_state(seed=random_seed) - - volume = zoom(volume) - - pt_nda = volume.unsqueeze(0) - return pt_nda - - -def augmentation(pt_nda, output_size, random_seed=None): - label_list = torch.unique(pt_nda) - label_list = list(label_list.cpu().numpy()) - - if 128 in label_list: - print("augmenting bone lesion/tumor") - pt_nda = augmentation_tumor_bone(pt_nda, output_size, random_seed) - elif 26 in label_list: - print("augmenting liver tumor") - pt_nda = augmentation_tumor_liver(pt_nda, output_size, random_seed) - elif 23 in label_list: - print("augmenting lung tumor") - pt_nda = augmentation_tumor_lung(pt_nda, output_size, random_seed) - elif 24 in label_list: - print("augmenting pancreas tumor") - pt_nda = augmentation_tumor_pancreas(pt_nda, output_size, random_seed) - elif 27 in label_list: - print("augmenting colon tumor") - pt_nda = augmentation_tumor_colon(pt_nda, output_size, random_seed) - else: - print("augmenting body") - pt_nda = augmentation_body(pt_nda, random_seed) - - return pt_nda diff --git a/itrialspace/src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py b/itrialspace/src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py deleted file mode 100644 index 3ec98fd3467085a1ee02e3ba000597dbe0500442..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py +++ /dev/null @@ -1,761 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at: -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. -# See the License for the specific language governing permissions -# and limitations under the License. - -""" -Compute 2.5D FID using distributed GPU processing. - -SHELL Usage Example: -------------------- - #!/bin/bash - - export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6 - NUM_GPUS=7 - - torchrun --nproc_per_node=${NUM_GPUS} compute_fid_2-5d_ct.py \ - --model_name "radimagenet_resnet50" \ - --real_dataset_root "path/to/datasetA" \ - --real_filelist "path/to/filelistA.txt" \ - --real_features_dir "datasetA" \ - --synth_dataset_root "path/to/datasetB" \ - --synth_filelist "path/to/filelistB.txt" \ - --synth_features_dir "datasetB" \ - --enable_center_slices_ratio 0.4 \ - --enable_padding True \ - --enable_center_cropping True \ - --enable_resampling_spacing "1.0x1.0x1.0" \ - --ignore_existing True \ - --num_images 100 \ - --output_root "./features/features-512x512x512" \ - --target_shape "512x512x512" - -This script loads two datasets (real vs. synthetic) in 3D medical format (NIfTI) -and extracts feature maps via a 2.5D approach. It then computes the Frechet -Inception Distance (FID) across three orthogonal planes. Data parallelism -is implemented using torch.distributed with an NCCL backend. - -Function Arguments (main): --------------------------- - real_dataset_root (str): - Root folder for the real dataset. - - real_filelist (str): - Text file listing 3D images for the real dataset. - - real_features_dir (str): - Subdirectory (under `output_root`) in which to store feature files - extracted from the real dataset. - - synth_dataset_root (str): - Root folder for the synthetic dataset. - - synth_filelist (str): - Text file listing 3D images for the synthetic dataset. - - synth_features_dir (str): - Subdirectory (under `output_root`) in which to store feature files - extracted from the synthetic dataset. - - enable_center_slices_ratio (float or None): - - If not None, only slices around the specified center ratio will be used - (analogous to "enable_center_slices=True" with that ratio). - - If None, no center-slice selection is performed - (analogous to "enable_center_slices=False"). - - enable_padding (bool): - Whether to pad images to `target_shape`. - - enable_center_cropping (bool): - Whether to center-crop images to `target_shape`. - - enable_resampling_spacing (str or None): - - If not None, resample images to the specified voxel spacing (e.g. "1.0x1.0x1.0") - (analogous to "enable_resampling=True" with that spacing). - - If None, resampling is skipped - (analogous to "enable_resampling=False"). - - ignore_existing (bool): - If True, ignore any existing .pt feature files and force re-extraction. - - model_name (str): - Model identifier. Typically "radimagenet_resnet50" or "squeezenet1_1". - - num_images (int): - Max number of images to process from each dataset (truncate if more are present). - - output_root (str): - Folder where extracted .pt feature files, logs, and results are saved. - - target_shape (str): - Target shape as "XxYxZ" for padding, cropping, or resampling operations. -""" - - -from __future__ import annotations - -import logging -import os -import re -import sys -from datetime import timedelta -from pathlib import Path - -import fire -import monai -import torch -import torch.distributed as dist -import torch.nn.functional as F -from monai.metrics.fid import FIDMetric -from monai.transforms import Compose - -# ------------------------------------------------------------------------------ -# Create logger -# ------------------------------------------------------------------------------ -logger = logging.getLogger("fid_2-5d_ct") -if not logger.handlers: - # Configure logger only if it has no handlers (avoid reconfiguring in multi-rank scenarios) - logging.basicConfig(stream=sys.stdout, level=logging.INFO) -logger.setLevel(logging.INFO) - - -def drop_empty_slice(slices, empty_threshold: float): - """ - Decide which 2D slices to keep by checking if their maximum intensity - is below a certain threshold. - - Args: - slices (tuple or list of Tensors): Each element is (B, C, H, W). - empty_threshold (float): If the slice's maximum value is below this threshold, - it is considered "empty". - - Returns: - list[bool]: A list of booleans indicating for each slice whether to keep it. - """ - outputs = [] - n_drop = 0 - for s in slices: - largest_unique = torch.max(torch.unique(s)) - if largest_unique < empty_threshold: - outputs.append(False) - n_drop += 1 - else: - outputs.append(True) - - logger.info(f"Empty slice drop rate {round((n_drop/len(slices))*100,1)}%") - return outputs - - -def subtract_mean(x: torch.Tensor) -> torch.Tensor: - """ - Subtract per-channel means (ImageNet-like: [0.406, 0.456, 0.485]) - from the input 4D or 5D tensor. Expects channels in the first dimension - after the batch dimension: (B, C, H, W) or (B, C, H, W, D). - """ - mean = [0.406, 0.456, 0.485] - x[:, 0, ...] -= mean[0] - x[:, 1, ...] -= mean[1] - x[:, 2, ...] -= mean[2] - return x - - -def spatial_average(x: torch.Tensor, keepdim: bool = True) -> torch.Tensor: - """ - Average out the spatial dimensions of a tensor, preserving or removing them - according to `keepdim`. This is used to produce a 1D feature vector - out of a feature map. - - Args: - x (torch.Tensor): Input tensor (B, C, H, W, ...) or (B, C, H, W). - keepdim (bool): Whether to keep dimension or not after averaging. - - Returns: - torch.Tensor: Tensor with reduced spatial dimensions. - """ - dim = len(x.shape) - # 2D -> no average - if dim == 2: - return x - # 3D -> average over last dim - if dim == 3: - return x.mean([2], keepdim=keepdim) - # 4D -> average over H,W - if dim == 4: - return x.mean([2, 3], keepdim=keepdim) - # 5D -> average over H,W,D - if dim == 5: - return x.mean([2, 3, 4], keepdim=keepdim) - return x - - -def medicalnet_intensity_normalisation(volume: torch.Tensor) -> torch.Tensor: - """ - Intensity normalization approach from MedicalNet: - (volume - mean) / (std + 1e-5) across spatial dims. - Expects (B, C, H, W) or (B, C, H, W, D). - """ - dim = len(volume.shape) - if dim == 4: - mean = volume.mean([2, 3], keepdim=True) - std = volume.std([2, 3], keepdim=True) - elif dim == 5: - mean = volume.mean([2, 3, 4], keepdim=True) - std = volume.std([2, 3, 4], keepdim=True) - else: - return volume - return (volume - mean) / (std + 1e-5) - - -def radimagenet_intensity_normalisation(volume: torch.Tensor, norm2d: bool = False) -> torch.Tensor: - """ - Intensity normalization for radimagenet_resnet. Optionally normalizes each 2D slice individually. - - Args: - volume (torch.Tensor): Input (B, C, H, W) or (B, C, H, W, D). - norm2d (bool): If True, normalizes each (H,W) slice to [0,1], then subtracts the ImageNet mean. - """ - logger.info(f"norm2d: {norm2d}") - dim = len(volume.shape) - # If norm2d is True, only meaningful for 4D data (B, C, H, W): - if dim == 4 and norm2d: - max2d, _ = torch.max(volume, dim=2, keepdim=True) - max2d, _ = torch.max(max2d, dim=3, keepdim=True) - min2d, _ = torch.min(volume, dim=2, keepdim=True) - min2d, _ = torch.min(min2d, dim=3, keepdim=True) - # Scale each slice to 0..1 - volume = (volume - min2d) / (max2d - min2d + 1e-10) - # Subtract channel mean - return subtract_mean(volume) - elif dim == 4: - # 4D but no per-slice normalization - max3d = torch.max(volume) - min3d = torch.min(volume) - volume = (volume - min3d) / (max3d - min3d + 1e-10) - return subtract_mean(volume) - # Fallback for e.g. 5D data is simply a min-max over entire volume - if dim == 5: - maxval = torch.max(volume) - minval = torch.min(volume) - volume = (volume - minval) / (maxval - minval + 1e-10) - return subtract_mean(volume) - return volume - - -def get_features_2p5d( - image: torch.Tensor, - feature_network: torch.nn.Module, - center_slices: bool = False, - center_slices_ratio: float = 1.0, - sample_every_k: int = 1, - xy_only: bool = True, - drop_empty: bool = False, - empty_threshold: float = -700, -) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]: - """ - Extract 2.5D features from a 3D image by slicing it along XY, YZ, ZX planes. - - Args: - image (torch.Tensor): Input 5D tensor in shape (B, C, H, W, D). - feature_network (torch.nn.Module): Model that processes 2D slices (C,H,W). - center_slices (bool): Whether to slice only the center portion of each axis. - center_slices_ratio (float): Ratio of slices to keep in the center if `center_slices` is True. - sample_every_k (int): Downsampling factor along each axis when slicing. - xy_only (bool): If True, return only the XY-plane features. - drop_empty (bool): Drop slices that are deemed "empty" below `empty_threshold`. - empty_threshold (float): Threshold to decide emptiness of slices. - - Returns: - tuple of torch.Tensor or None: (XY_features, YZ_features, ZX_features). - """ - logger.info(f"center_slices: {center_slices}, ratio: {center_slices_ratio}") - - # If there's only 1 channel, replicate to 3 channels - if image.shape[1] == 1: - image = image.repeat(1, 3, 1, 1, 1) - - # Convert from 'RGB'→(R,G,B) to (B,G,R) - image = image[:, [2, 1, 0], ...] - - B, C, H, W, D = image.size() - with torch.no_grad(): - # ---------------------- XY-plane slicing along D ---------------------- - if center_slices: - start_d = int((1.0 - center_slices_ratio) / 2.0 * D) - end_d = int((1.0 + center_slices_ratio) / 2.0 * D) - slices = torch.unbind(image[:, :, :, :, start_d:end_d:sample_every_k], dim=-1) - else: - slices = torch.unbind(image, dim=-1) - - if drop_empty: - mapping_index = drop_empty_slice(slices, empty_threshold) - else: - mapping_index = [True for _ in range(len(slices))] - - images_2d = torch.cat(slices, dim=0) - images_2d = radimagenet_intensity_normalisation(images_2d) - images_2d = images_2d[mapping_index] - - feature_image_xy = feature_network.forward(images_2d) - feature_image_xy = spatial_average(feature_image_xy, keepdim=False) - if xy_only: - return feature_image_xy, None, None - - # ---------------------- YZ-plane slicing along H ---------------------- - if center_slices: - start_h = int((1.0 - center_slices_ratio) / 2.0 * H) - end_h = int((1.0 + center_slices_ratio) / 2.0 * H) - slices = torch.unbind(image[:, :, start_h:end_h:sample_every_k, :, :], dim=2) - else: - slices = torch.unbind(image, dim=2) - - if drop_empty: - mapping_index = drop_empty_slice(slices, empty_threshold) - else: - mapping_index = [True for _ in range(len(slices))] - - images_2d = torch.cat(slices, dim=0) - images_2d = radimagenet_intensity_normalisation(images_2d) - images_2d = images_2d[mapping_index] - - feature_image_yz = feature_network.forward(images_2d) - feature_image_yz = spatial_average(feature_image_yz, keepdim=False) - - # ---------------------- ZX-plane slicing along W ---------------------- - if center_slices: - start_w = int((1.0 - center_slices_ratio) / 2.0 * W) - end_w = int((1.0 + center_slices_ratio) / 2.0 * W) - slices = torch.unbind(image[:, :, :, start_w:end_w:sample_every_k, :], dim=3) - else: - slices = torch.unbind(image, dim=3) - - if drop_empty: - mapping_index = drop_empty_slice(slices, empty_threshold) - else: - mapping_index = [True for _ in range(len(slices))] - - images_2d = torch.cat(slices, dim=0) - images_2d = radimagenet_intensity_normalisation(images_2d) - images_2d = images_2d[mapping_index] - - feature_image_zx = feature_network.forward(images_2d) - feature_image_zx = spatial_average(feature_image_zx, keepdim=False) - - return feature_image_xy, feature_image_yz, feature_image_zx - - -def pad_to_max_size( - tensor: torch.Tensor, max_size: int, padding_value: float = 0.0 -) -> torch.Tensor: - """ - Zero-pad a 2D feature map or other tensor along the first dimension to match a specified size. - - Args: - tensor (torch.Tensor): The feature tensor to pad. - max_size (int): Desired size along the first dimension. - padding_value (float): Value to fill during padding. - - Returns: - torch.Tensor: Padded tensor matching `max_size` along dim=0. - """ - pad_size = [0, 0] * (len(tensor.shape) - 1) + [0, max_size - tensor.shape[0]] - return F.pad(tensor, pad_size, "constant", padding_value) - - -def main( - real_dataset_root: str = "path/to/datasetA", - real_filelist: str = "path/to/filelistA.txt", - real_features_dir: str = "datasetA", - synth_dataset_root: str = "path/to/datasetB", - synth_filelist: str = "path/to/filelistB.txt", - synth_features_dir: str = "datasetB", - enable_center_slices_ratio: float = None, - enable_padding: bool = True, - enable_center_cropping: bool = True, - enable_resampling_spacing: str = None, - ignore_existing: bool = False, - model_name: str = "radimagenet_resnet50", - num_images: int = 100, - output_root: str = "./features/features-512x512x512", - target_shape: str = "512x512x512", -): - """ - Compute 2.5D FID using distributed GPU processing. - - This function loads two datasets (real vs. synthetic) in 3D medical format (NIfTI) - and extracts feature maps via a 2.5D approach, then computes the Frechet Inception - Distance (FID) across three orthogonal planes. Data parallelism is implemented - using torch.distributed with an NCCL backend. - - Args: - real_dataset_root (str): - Root folder for the real dataset. - real_filelist (str): - Path to a text file listing 3D images (e.g., NIfTI files) for the real dataset. - Each line in this file should contain a relative path (or filename) to a NIfTI file. - For example, your "real_filelist.txt" could look like: - case001.nii.gz - case002.nii.gz - case003.nii.gz - ... - These entries will be appended to `real_dataset_root`. - real_features_dir (str): - Name of the directory under `output_root` in which to store - extracted features for the real dataset. - - synth_dataset_root (str): - Root folder for the synthetic dataset. - synth_filelist (str): - Path to a text file listing 3D images (e.g., NIfTI files) for the synthetic dataset. - The format is the same as the real dataset file list, for example: - synth_case001.nii.gz - synth_case002.nii.gz - synth_case003.nii.gz - ... - These entries will be appended to `synth_dataset_root`. - synth_features_dir (str): - Name of the directory under `output_root` in which to store - extracted features for the synthetic dataset. - - enable_center_slices_ratio (float or None): - - If not None, only slices around the specified center ratio are used. - (similar to "enable_center_slices=True" with that ratio in an earlier script). - - If None, no center-slice selection is performed - (similar to "enable_center_slices=False"). - - enable_padding (bool): - Whether to pad images to `target_shape`. - - enable_center_cropping (bool): - Whether to center-crop images to `target_shape`. - - enable_resampling_spacing (str or None): - - If not None, resample images to this voxel spacing (e.g. "1.0x1.0x1.0") - (similar to "enable_resampling=True" with that spacing). - - If None, skip resampling (similar to "enable_resampling=False"). - - ignore_existing (bool): - If True, ignore any existing .pt feature files and force re-computation. - - model_name (str): - Model identifier. Typically "radimagenet_resnet50" or "squeezenet1_1". - - num_images (int): - Maximum number of images to load from each dataset (truncate if more are present). - - output_root (str): - Parent folder where extracted .pt files and logs will be saved. - - target_shape (str): - Target shape, e.g. "512x512x512", for padding, cropping, or resampling operations. - - Returns: - None - """ - # ------------------------------------------------------------------------- - # Initialize Process Group (Distributed) - # ------------------------------------------------------------------------- - dist.init_process_group(backend="nccl", init_method="env://", timeout=timedelta(seconds=7200)) - - local_rank = int(os.environ["LOCAL_RANK"]) - world_size = int(dist.get_world_size()) - device = torch.device("cuda", local_rank) - torch.cuda.set_device(device) - logger.info(f"[INFO] Running process on {device} of total {world_size} ranks.") - - # Convert potential string bools to actual bools (if using Fire or similar) - if not isinstance(enable_padding, bool): - enable_padding = enable_padding.lower() == "true" - if not isinstance(enable_center_cropping, bool): - enable_center_cropping = enable_center_cropping.lower() == "true" - if not isinstance(ignore_existing, bool): - ignore_existing = ignore_existing.lower() == "true" - - # Merge logic for center slices - enable_center_slices = enable_center_slices_ratio is not None - - # Merge logic for resampling - enable_resampling = enable_resampling_spacing is not None - - # Print out some flags on rank 0 - if local_rank == 0: - logger.info(f"Real dataset root: {real_dataset_root}") - logger.info(f"Synth dataset root: {synth_dataset_root}") - logger.info(f"enable_center_slices_ratio: {enable_center_slices_ratio}") - logger.info(f"enable_center_slices: {enable_center_slices}") - logger.info(f"enable_padding: {enable_padding}") - logger.info(f"enable_center_cropping: {enable_center_cropping}") - logger.info(f"enable_resampling_spacing: {enable_resampling_spacing}") - logger.info(f"enable_resampling: {enable_resampling}") - logger.info(f"ignore_existing: {ignore_existing}") - - # ------------------------------------------------------------------------- - # Load feature extraction model - # ------------------------------------------------------------------------- - if model_name == "radimagenet_resnet50": - feature_network = torch.hub.load( - "Warvito/radimagenet-models", - model="radimagenet_resnet50", - verbose=True, - trust_repo=True, - ) - suffix = "radimagenet_resnet50" - else: - import torchvision - - feature_network = torchvision.models.squeezenet1_1(pretrained=True) - suffix = "squeezenet1_1" - - feature_network.to(device) - feature_network.eval() - - # ------------------------------------------------------------------------- - # Parse shape/spacings - # ------------------------------------------------------------------------- - t_shape = [int(x) for x in target_shape.split("x")] - target_shape_tuple = tuple(t_shape) - - # If not None, parse the resampling spacing - if enable_resampling: - rs_spacing = [float(x) for x in enable_resampling_spacing.split("x")] - rs_spacing_tuple = tuple(rs_spacing) - if local_rank == 0: - logger.info(f"Resampling spacing: {rs_spacing_tuple}") - else: - rs_spacing_tuple = (1.0, 1.0, 1.0) - - # Use the ratio if provided, otherwise 1.0 - center_slices_ratio_final = enable_center_slices_ratio if enable_center_slices else 1.0 - if local_rank == 0: - logger.info(f"center_slices_ratio: {center_slices_ratio_final}") - - # ------------------------------------------------------------------------- - # Prepare Real Dataset - # ------------------------------------------------------------------------- - output_root_real = os.path.join(output_root, real_features_dir) - with open(real_filelist, "r") as rf: - real_lines = [l.strip() for l in rf.readlines()] - real_lines.sort() - real_lines = real_lines[:num_images] - - real_filenames = [{"image": os.path.join(real_dataset_root, f)} for f in real_lines] - real_filenames = monai.data.partition_dataset( - data=real_filenames, shuffle=False, num_partitions=world_size, even_divisible=False - )[local_rank] - - # ------------------------------------------------------------------------- - # Prepare Synthetic Dataset - # ------------------------------------------------------------------------- - output_root_synth = os.path.join(output_root, synth_features_dir) - with open(synth_filelist, "r") as sf: - synth_lines = [l.strip() for l in sf.readlines()] - synth_lines.sort() - synth_lines = synth_lines[:num_images] - - synth_filenames = [{"image": os.path.join(synth_dataset_root, f)} for f in synth_lines] - synth_filenames = monai.data.partition_dataset( - data=synth_filenames, shuffle=False, num_partitions=world_size, even_divisible=False - )[local_rank] - - # ------------------------------------------------------------------------- - # Build MONAI transforms - # ------------------------------------------------------------------------- - transform_list = [ - monai.transforms.LoadImaged(keys=["image"]), - monai.transforms.EnsureChannelFirstd(keys=["image"]), - monai.transforms.Orientationd(keys=["image"], axcodes="RAS"), - ] - - if enable_resampling: - transform_list.append( - monai.transforms.Spacingd(keys=["image"], pixdim=rs_spacing_tuple, mode=["bilinear"]) - ) - - if enable_padding: - transform_list.append( - monai.transforms.SpatialPadd( - keys=["image"], spatial_size=target_shape_tuple, mode="constant", value=-1000 - ) - ) - - if enable_center_cropping: - transform_list.append( - monai.transforms.CenterSpatialCropd(keys=["image"], roi_size=target_shape_tuple) - ) - - transform_list.append( - monai.transforms.ScaleIntensityRanged( - keys=["image"], a_min=-1000, a_max=1000, b_min=-1000, b_max=1000, clip=True - ) - ) - transforms = Compose(transform_list) - - # ------------------------------------------------------------------------- - # Create DataLoaders - # ------------------------------------------------------------------------- - real_ds = monai.data.Dataset(data=real_filenames, transform=transforms) - real_loader = monai.data.DataLoader(real_ds, num_workers=6, batch_size=1, shuffle=False) - - synth_ds = monai.data.Dataset(data=synth_filenames, transform=transforms) - synth_loader = monai.data.DataLoader(synth_ds, num_workers=6, batch_size=1, shuffle=False) - - # ------------------------------------------------------------------------- - # Extract features for Real Dataset - # ------------------------------------------------------------------------- - real_features_xy, real_features_yz, real_features_zx = [], [], [] - for idx, batch_data in enumerate(real_loader, start=1): - img = batch_data["image"].to(device) - fn = img.meta["filename_or_obj"][0] - logger.info(f"[Rank {local_rank}] Real data {idx}/{len(real_filenames)}: {fn}") - - out_fp = fn.replace(real_dataset_root, output_root_real).replace(".nii.gz", ".pt") - out_fp = Path(out_fp) - out_fp.parent.mkdir(parents=True, exist_ok=True) - - if (not ignore_existing) and os.path.isfile(out_fp): - feats = torch.load(out_fp, weights_only=True) - else: - img_t = img.as_tensor() - logger.info(f"image shape: {tuple(img_t.shape)}") - - feats = get_features_2p5d( - img_t, - feature_network, - center_slices=enable_center_slices, - center_slices_ratio=center_slices_ratio_final, - xy_only=False, - ) - logger.info(f"feats shapes: {feats[0].shape}, {feats[1].shape}, {feats[2].shape}") - torch.save(feats, out_fp) - - real_features_xy.append(feats[0]) - real_features_yz.append(feats[1]) - real_features_zx.append(feats[2]) - - real_features_xy = torch.vstack(real_features_xy) - real_features_yz = torch.vstack(real_features_yz) - real_features_zx = torch.vstack(real_features_zx) - logger.info( - f"Real feature shapes: {real_features_xy.shape}, " - f"{real_features_yz.shape}, {real_features_zx.shape}" - ) - - # ------------------------------------------------------------------------- - # Extract features for Synthetic Dataset - # ------------------------------------------------------------------------- - synth_features_xy, synth_features_yz, synth_features_zx = [], [], [] - for idx, batch_data in enumerate(synth_loader, start=1): - img = batch_data["image"].to(device) - fn = img.meta["filename_or_obj"][0] - logger.info(f"[Rank {local_rank}] Synth data {idx}/{len(synth_filenames)}: {fn}") - - out_fp = fn.replace(synth_dataset_root, output_root_synth).replace(".nii.gz", ".pt") - out_fp = Path(out_fp) - out_fp.parent.mkdir(parents=True, exist_ok=True) - - if (not ignore_existing) and os.path.isfile(out_fp): - feats = torch.load(out_fp, weights_only=True) - else: - img_t = img.as_tensor() - logger.info(f"image shape: {tuple(img_t.shape)}") - - feats = get_features_2p5d( - img_t, - feature_network, - center_slices=enable_center_slices, - center_slices_ratio=center_slices_ratio_final, - xy_only=False, - ) - logger.info(f"feats shapes: {feats[0].shape}, {feats[1].shape}, {feats[2].shape}") - torch.save(feats, out_fp) - - synth_features_xy.append(feats[0]) - synth_features_yz.append(feats[1]) - synth_features_zx.append(feats[2]) - - synth_features_xy = torch.vstack(synth_features_xy) - synth_features_yz = torch.vstack(synth_features_yz) - synth_features_zx = torch.vstack(synth_features_zx) - logger.info( - f"Synth feature shapes: {synth_features_xy.shape}, " - f"{synth_features_yz.shape}, {synth_features_zx.shape}" - ) - - # ------------------------------------------------------------------------- - # All-reduce / gather features across ranks - # ------------------------------------------------------------------------- - features = [ - real_features_xy, - real_features_yz, - real_features_zx, - synth_features_xy, - synth_features_yz, - synth_features_zx, - ] - - # 1) Gather local feature sizes across ranks - local_sizes = [] - for ft_idx in range(len(features)): - local_size = torch.tensor([features[ft_idx].shape[0]], dtype=torch.int64, device=device) - local_sizes.append(local_size) - - all_sizes = [] - for ft_idx in range(len(features)): - rank_sizes = [ - torch.tensor([0], dtype=torch.int64, device=device) for _ in range(world_size) - ] - dist.all_gather(rank_sizes, local_sizes[ft_idx]) - all_sizes.append(rank_sizes) - - # 2) Pad and gather all features - all_tensors_list = [] - for ft_idx, ft in enumerate(features): - max_size = max(all_sizes[ft_idx]).item() - ft_padded = pad_to_max_size(ft, max_size) - - gather_list = [torch.empty_like(ft_padded) for _ in range(world_size)] - dist.all_gather(gather_list, ft_padded) - - # Trim each gather back to the real size - for rk in range(world_size): - gather_list[rk] = gather_list[rk][: all_sizes[ft_idx][rk], :] - - all_tensors_list.append(gather_list) - - # On rank 0, compute FID - if local_rank == 0: - real_xy = torch.vstack(all_tensors_list[0]) - real_yz = torch.vstack(all_tensors_list[1]) - real_zx = torch.vstack(all_tensors_list[2]) - - synth_xy = torch.vstack(all_tensors_list[3]) - synth_yz = torch.vstack(all_tensors_list[4]) - synth_zx = torch.vstack(all_tensors_list[5]) - - logger.info(f"Final Real shapes: {real_xy.shape}, {real_yz.shape}, {real_zx.shape}") - logger.info(f"Final Synth shapes: {synth_xy.shape}, {synth_yz.shape}, {synth_zx.shape}") - - fid = FIDMetric() - logger.info(f"Computing FID for: {output_root_real} | {output_root_synth}") - fid_res_xy = fid(synth_xy, real_xy) - fid_res_yz = fid(synth_yz, real_yz) - fid_res_zx = fid(synth_zx, real_zx) - - logger.info(f"FID XY: {fid_res_xy}") - logger.info(f"FID YZ: {fid_res_yz}") - logger.info(f"FID ZX: {fid_res_zx}") - fid_avg = (fid_res_xy + fid_res_yz + fid_res_zx) / 3.0 - logger.info(f"FID Avg: {fid_avg}") - - dist.destroy_process_group() - - -if __name__ == "__main__": - fire.Fire(main) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_create_training_data.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_create_training_data.py deleted file mode 100644 index da515aef0c853e4cac886940ecf0251046259270..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_create_training_data.py +++ /dev/null @@ -1,242 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import argparse -import json -import logging -import os -from pathlib import Path - -import monai -import nibabel as nib -import numpy as np -import torch -import torch.distributed as dist -from monai.transforms import Compose -from monai.utils import set_determinism - -from .diff_model_setting import initialize_distributed, load_config, setup_logging -from .utils import define_instance - -# Set the random seed for reproducibility -set_determinism(seed=0) - - -def create_transforms(dim: tuple = None) -> Compose: - """ - Create a set of MONAI transforms for preprocessing. - - Args: - dim (tuple, optional): New dimensions for resizing. Defaults to None. - - Returns: - Compose: Composed MONAI transforms. - """ - if dim: - return Compose( - [ - monai.transforms.LoadImaged(keys="image"), - monai.transforms.EnsureChannelFirstd(keys="image"), - monai.transforms.Orientationd(keys="image", axcodes="RAS"), - monai.transforms.EnsureTyped(keys="image", dtype=torch.float32), - monai.transforms.ScaleIntensityRanged( - keys="image", a_min=-1000, a_max=1000, b_min=0, b_max=1, clip=True - ), - monai.transforms.Resized(keys="image", spatial_size=dim, mode="trilinear"), - ] - ) - else: - return Compose( - [ - monai.transforms.LoadImaged(keys="image"), - monai.transforms.EnsureChannelFirstd(keys="image"), - monai.transforms.Orientationd(keys="image", axcodes="RAS"), - ] - ) - - -def round_number(number: int, base_number: int = 128) -> int: - """ - Round the number to the nearest multiple of the base number, with a minimum value of the base number. - - Args: - number (int): Number to be rounded. - base_number (int): Number to be common divisor. - - Returns: - int: Rounded number. - """ - new_number = max(round(float(number) / float(base_number)), 1.0) * float(base_number) - return int(new_number) - - -def load_filenames(data_list_path: str) -> list: - """ - Load filenames from the JSON data list. - - Args: - data_list_path (str): Path to the JSON data list file. - - Returns: - list: List of filenames. - """ - with open(data_list_path, "r") as file: - json_data = json.load(file) - filenames_raw = json_data["training"] - return [_item["image"] for _item in filenames_raw] - - -def process_file( - filepath: str, - args: argparse.Namespace, - autoencoder: torch.nn.Module, - device: torch.device, - plain_transforms: Compose, - new_transforms: Compose, - logger: logging.Logger, -) -> None: - """ - Process a single file to create training data. - - Args: - filepath (str): Path to the file to be processed. - args (argparse.Namespace): Configuration arguments. - autoencoder (torch.nn.Module): Autoencoder model. - device (torch.device): Device to process the file on. - plain_transforms (Compose): Plain transforms. - new_transforms (Compose): New transforms. - logger (logging.Logger): Logger for logging information. - """ - out_filename_base = filepath.replace(".gz", "").replace(".nii", "") - out_filename_base = os.path.join(args.embedding_base_dir, out_filename_base) - out_filename = out_filename_base + "_emb.nii.gz" - - if os.path.isfile(out_filename): - return - - test_data = {"image": os.path.join(args.data_base_dir, filepath)} - transformed_data = plain_transforms(test_data) - nda = transformed_data["image"] - - dim = [int(nda.meta["dim"][_i]) for _i in range(1, 4)] - spacing = [float(nda.meta["pixdim"][_i]) for _i in range(1, 4)] - - logger.info(f"old dim: {dim}, old spacing: {spacing}") - - new_data = new_transforms(test_data) - nda_image = new_data["image"] - - new_affine = nda_image.meta["affine"].numpy() - nda_image = nda_image.numpy().squeeze() - - logger.info(f"new dim: {nda_image.shape}, new affine: {new_affine}") - - try: - out_path = Path(out_filename) - out_path.parent.mkdir(parents=True, exist_ok=True) - logger.info(f"out_filename: {out_filename}") - - with torch.amp.autocast("cuda"): - pt_nda = torch.from_numpy(nda_image).float().to(device).unsqueeze(0).unsqueeze(0) - z = autoencoder.encode_stage_2_inputs(pt_nda) - logger.info(f"z: {z.size()}, {z.dtype}") - - out_nda = z.squeeze().cpu().detach().numpy().transpose(1, 2, 3, 0) - out_img = nib.Nifti1Image(np.float32(out_nda), affine=new_affine) - nib.save(out_img, out_filename) - except Exception as e: - logger.error(f"Error processing {filepath}: {e}") - - -@torch.inference_mode() -def diff_model_create_training_data( - env_config_path: str, model_config_path: str, model_def_path: str, num_gpus: int -) -> None: - """ - Create training data for the diffusion model. - - Args: - env_config_path (str): Path to the environment configuration file. - model_config_path (str): Path to the model configuration file. - model_def_path (str): Path to the model definition file. - """ - args = load_config(env_config_path, model_config_path, model_def_path) - local_rank, world_size, device = initialize_distributed(num_gpus=num_gpus) - logger = setup_logging("creating training data") - logger.info(f"Using device {device}") - - autoencoder = define_instance(args, "autoencoder_def").to(device) - try: - checkpoint_autoencoder = torch.load(args.trained_autoencoder_path, weights_only=True) - autoencoder.load_state_dict(checkpoint_autoencoder) - except Exception: - logger.error("The trained_autoencoder_path does not exist!") - - Path(args.embedding_base_dir).mkdir(parents=True, exist_ok=True) - - filenames_raw = load_filenames(args.json_data_list) - logger.info(f"filenames_raw: {filenames_raw}") - - plain_transforms = create_transforms(dim=None) - - for _iter in range(len(filenames_raw)): - if _iter % world_size != local_rank: - continue - - filepath = filenames_raw[_iter] - new_dim = tuple( - round_number( - int( - plain_transforms({"image": os.path.join(args.data_base_dir, filepath)})[ - "image" - ].meta["dim"][_i] - ) - ) - for _i in range(1, 4) - ) - new_transforms = create_transforms(new_dim) - - process_file(filepath, args, autoencoder, device, plain_transforms, new_transforms, logger) - - if dist.is_initialized(): - dist.destroy_process_group() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Diffusion Model Training Data Creation") - parser.add_argument( - "--env_config", - type=str, - default="./configs/environment_maisi_diff_model_train.json", - help="Path to environment configuration file", - ) - parser.add_argument( - "--model_config", - type=str, - default="./configs/config_maisi_diff_model_train.json", - help="Path to model training/inference configuration", - ) - parser.add_argument( - "--model_def", - type=str, - default="./configs/config_maisi.json", - help="Path to model definition file", - ) - parser.add_argument( - "--num_gpus", type=int, default=1, help="Number of GPUs to use for distributed training" - ) - - args = parser.parse_args() - diff_model_create_training_data( - args.env_config, args.model_config, args.model_def, args.num_gpus - ) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_infer.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_infer.py deleted file mode 100644 index eaacaa5398a82906f2e342d68d8bd8dca2d4fd0e..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_infer.py +++ /dev/null @@ -1,376 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import argparse -import logging -import os -import random -from datetime import datetime - -import nibabel as nib -import numpy as np -import torch -import torch.distributed as dist -from monai.inferers import sliding_window_inference -from monai.inferers.inferer import SlidingWindowInferer -from monai.networks.schedulers import RFlowScheduler -from monai.utils import set_determinism -from tqdm import tqdm - -from .diff_model_setting import initialize_distributed, load_config, setup_logging -from .sample import ReconModel, check_input -from .utils import define_instance, dynamic_infer - - -def set_random_seed(seed: int) -> int: - """ - Set random seed for reproducibility. - - Args: - seed (int): Random seed. - - Returns: - int: Set random seed. - """ - random_seed = random.randint(0, 99999) if seed is None else seed - set_determinism(random_seed) - return random_seed - - -def load_models(args: argparse.Namespace, device: torch.device, logger: logging.Logger) -> tuple: - """ - Load the autoencoder and UNet models. - - Args: - args (argparse.Namespace): Configuration arguments. - device (torch.device): Device to load models on. - logger (logging.Logger): Logger for logging information. - - Returns: - tuple: Loaded autoencoder, UNet model, and scale factor. - """ - autoencoder = define_instance(args, "autoencoder_def").to(device) - try: - checkpoint_autoencoder = torch.load(args.trained_autoencoder_path, weights_only=True) - autoencoder.load_state_dict(checkpoint_autoencoder) - except Exception: - logger.error("The trained_autoencoder_path does not exist!") - - unet = define_instance(args, "diffusion_unet_def").to(device) - checkpoint = torch.load( - f"{args.model_dir}/{args.model_filename}", map_location=device, weights_only=False - ) - unet.load_state_dict(checkpoint["unet_state_dict"], strict=True) - logger.info(f"checkpoints {args.model_dir}/{args.model_filename} loaded.") - - scale_factor = checkpoint["scale_factor"] - logger.info(f"scale_factor -> {scale_factor}.") - - return autoencoder, unet, scale_factor - - -def prepare_tensors(args: argparse.Namespace, device: torch.device) -> tuple: - """ - Prepare necessary tensors for inference. - - Args: - args (argparse.Namespace): Configuration arguments. - device (torch.device): Device to load tensors on. - - Returns: - tuple: Prepared top_region_index_tensor, bottom_region_index_tensor, and spacing_tensor. - """ - top_region_index_tensor = ( - np.array(args.diffusion_unet_inference["top_region_index"]).astype(float) * 1e2 - ) - bottom_region_index_tensor = ( - np.array(args.diffusion_unet_inference["bottom_region_index"]).astype(float) * 1e2 - ) - spacing_tensor = np.array(args.diffusion_unet_inference["spacing"]).astype(float) * 1e2 - - top_region_index_tensor = ( - torch.from_numpy(top_region_index_tensor[np.newaxis, :]).half().to(device) - ) - bottom_region_index_tensor = ( - torch.from_numpy(bottom_region_index_tensor[np.newaxis, :]).half().to(device) - ) - spacing_tensor = torch.from_numpy(spacing_tensor[np.newaxis, :]).half().to(device) - modality_tensor = args.diffusion_unet_inference["modality"] * torch.ones( - (len(spacing_tensor)), dtype=torch.long - ).to(device) - - return top_region_index_tensor, bottom_region_index_tensor, spacing_tensor, modality_tensor - - -def run_inference( - args: argparse.Namespace, - device: torch.device, - autoencoder: torch.nn.Module, - unet: torch.nn.Module, - scale_factor: float, - top_region_index_tensor: torch.Tensor, - bottom_region_index_tensor: torch.Tensor, - spacing_tensor: torch.Tensor, - modality_tensor: torch.Tensor, - output_size: tuple, - divisor: int, - logger: logging.Logger, -) -> np.ndarray: - """ - Run the inference to generate synthetic images. - - Args: - args (argparse.Namespace): Configuration arguments. - device (torch.device): Device to run inference on. - autoencoder (torch.nn.Module): Autoencoder model. - unet (torch.nn.Module): UNet model. - scale_factor (float): Scale factor for the model. - top_region_index_tensor (torch.Tensor): Top region index tensor. - bottom_region_index_tensor (torch.Tensor): Bottom region index tensor. - spacing_tensor (torch.Tensor): Spacing tensor. - modality_tensor (torch.Tensor): Modality tensor. - output_size (tuple): Output size of the synthetic image. - divisor (int): Divisor for downsample level. - logger (logging.Logger): Logger for logging information. - - Returns: - np.ndarray: Generated synthetic image data. - """ - include_body_region = unet.include_top_region_index_input - include_modality = unet.num_class_embeds is not None - - noise = torch.randn( - ( - 1, - args.latent_channels, - output_size[0] // divisor, - output_size[1] // divisor, - output_size[2] // divisor, - ), - device=device, - ) - logger.info(f"noise: {noise.device}, {noise.dtype}, {type(noise)}") - - image = noise - noise_scheduler = define_instance(args, "noise_scheduler") - if isinstance(noise_scheduler, RFlowScheduler): - noise_scheduler.set_timesteps( - num_inference_steps=args.diffusion_unet_inference["num_inference_steps"], - input_img_size_numel=torch.prod(torch.tensor(noise.shape[2:])), - ) - else: - noise_scheduler.set_timesteps( - num_inference_steps=args.diffusion_unet_inference["num_inference_steps"] - ) - - recon_model = ReconModel(autoencoder=autoencoder, scale_factor=scale_factor).to(device) - autoencoder.eval() - unet.eval() - - all_timesteps = noise_scheduler.timesteps - all_next_timesteps = torch.cat( - (all_timesteps[1:], torch.tensor([0], dtype=all_timesteps.dtype)) - ) - progress_bar = tqdm( - zip(all_timesteps, all_next_timesteps), - total=min(len(all_timesteps), len(all_next_timesteps)), - ) - with torch.amp.autocast("cuda", enabled=True): - for t, next_t in progress_bar: - # Create a dictionary to store the inputs - unet_inputs = { - "x": image, - "timesteps": torch.Tensor((t,)).to(device), - "spacing_tensor": spacing_tensor, - } - - # Add extra arguments if include_body_region is True - if include_body_region: - unet_inputs.update( - { - "top_region_index_tensor": top_region_index_tensor, - "bottom_region_index_tensor": bottom_region_index_tensor, - } - ) - - if include_modality: - unet_inputs.update( - { - "class_labels": modality_tensor, - } - ) - model_output = unet(**unet_inputs) - if not isinstance(noise_scheduler, RFlowScheduler): - image, _ = noise_scheduler.step(model_output, t, image) # type: ignore - else: - image, _ = noise_scheduler.step(model_output, t, image, next_t) # type: ignore - - inferer = SlidingWindowInferer( - roi_size=[80, 80, 80], - sw_batch_size=1, - progress=True, - mode="gaussian", - overlap=0.4, - sw_device=device, - device=device, - ) - synthetic_images = dynamic_infer(inferer, recon_model, image) - data = synthetic_images.squeeze().cpu().detach().numpy() - a_min, a_max, b_min, b_max = -1000, 1000, 0, 1 - data = (data - b_min) / (b_max - b_min) * (a_max - a_min) + a_min - data = np.clip(data, a_min, a_max) - return np.int16(data) - - -def save_image( - data: np.ndarray, - output_size: tuple, - out_spacing: tuple, - output_path: str, - logger: logging.Logger, -) -> None: - """ - Save the generated synthetic image to a file. - - Args: - data (np.ndarray): Synthetic image data. - output_size (tuple): Output size of the image. - out_spacing (tuple): Spacing of the output image. - output_path (str): Path to save the output image. - logger (logging.Logger): Logger for logging information. - """ - out_affine = np.eye(4) - for i in range(3): - out_affine[i, i] = out_spacing[i] - - new_image = nib.Nifti1Image(data, affine=out_affine) - os.makedirs(os.path.dirname(output_path), exist_ok=True) - nib.save(new_image, output_path) - logger.info(f"Saved {output_path}.") - - -@torch.inference_mode() -def diff_model_infer( - env_config_path: str, model_config_path: str, model_def_path: str, num_gpus: int -) -> None: - """ - Main function to run the diffusion model inference. - - Args: - env_config_path (str): Path to the environment configuration file. - model_config_path (str): Path to the model configuration file. - model_def_path (str): Path to the model definition file. - """ - args = load_config(env_config_path, model_config_path, model_def_path) - local_rank, world_size, device = initialize_distributed(num_gpus) - logger = setup_logging("inference") - random_seed = set_random_seed( - args.diffusion_unet_inference["random_seed"] + local_rank - if args.diffusion_unet_inference["random_seed"] - else None - ) - logger.info(f"Using {device} of {world_size} with random seed: {random_seed}") - - output_size = tuple(args.diffusion_unet_inference["dim"]) - out_spacing = tuple(args.diffusion_unet_inference["spacing"]) - output_prefix = args.output_prefix - ckpt_filepath = f"{args.model_dir}/{args.model_filename}" - - if local_rank == 0: - logger.info(f"[config] ckpt_filepath -> {ckpt_filepath}.") - logger.info(f"[config] random_seed -> {random_seed}.") - logger.info(f"[config] output_prefix -> {output_prefix}.") - logger.info(f"[config] output_size -> {output_size}.") - logger.info(f"[config] out_spacing -> {out_spacing}.") - - check_input(None, None, None, output_size, out_spacing, None) - - autoencoder, unet, scale_factor = load_models(args, device, logger) - num_downsample_level = max( - 1, - ( - len(args.diffusion_unet_def["num_channels"]) - if isinstance(args.diffusion_unet_def["num_channels"], list) - else len(args.diffusion_unet_def["attention_levels"]) - ), - ) - divisor = 2 ** (num_downsample_level - 2) - logger.info(f"num_downsample_level -> {num_downsample_level}, divisor -> {divisor}.") - - top_region_index_tensor, bottom_region_index_tensor, spacing_tensor, modality_tensor = ( - prepare_tensors(args, device) - ) - data = run_inference( - args, - device, - autoencoder, - unet, - scale_factor, - top_region_index_tensor, - bottom_region_index_tensor, - spacing_tensor, - modality_tensor, - output_size, - divisor, - logger, - ) - - timestamp = datetime.now().strftime("%Y%m%d%H%M%S") - output_path = "{0}/{1}_seed{2}_size{3:d}x{4:d}x{5:d}_spacing{6:.2f}x{7:.2f}x{8:.2f}_{9}_rank{10}.nii.gz".format( - args.output_dir, - output_prefix, - random_seed, - output_size[0], - output_size[1], - output_size[2], - out_spacing[0], - out_spacing[1], - out_spacing[2], - timestamp, - local_rank, - ) - save_image(data, output_size, out_spacing, output_path, logger) - - if dist.is_initialized(): - dist.destroy_process_group() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Diffusion Model Inference") - parser.add_argument( - "--env_config", - type=str, - default="./configs/environment_maisi_diff_model_train.json", - help="Path to environment configuration file", - ) - parser.add_argument( - "--model_config", - type=str, - default="./configs/config_maisi_diff_model_train.json", - help="Path to model training/inference configuration", - ) - parser.add_argument( - "--model_def", - type=str, - default="./configs/config_maisi.json", - help="Path to model definition file", - ) - parser.add_argument( - "--num_gpus", - type=int, - default=1, - help="Number of GPUs to use for distributed inference", - ) - - args = parser.parse_args() - diff_model_infer(args.env_config, args.model_config, args.model_def, args.num_gpus) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_setting.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_setting.py deleted file mode 100644 index 722207cf51e2ecf5b7f5729368d30a5cd883bac0..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_setting.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import argparse -import json -import logging - -import torch -import torch.distributed as dist -from monai.utils import RankFilter - - -def setup_logging(logger_name: str = "") -> logging.Logger: - """ - Setup the logging configuration. - - Args: - logger_name (str): logger name. - - Returns: - logging.Logger: Configured logger. - """ - logger = logging.getLogger(logger_name) - if dist.is_initialized(): - logger.addFilter(RankFilter()) - logging.basicConfig( - level=logging.INFO, - format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - return logger - - -def load_config( - env_config_path: str, model_config_path: str, model_def_path: str -) -> argparse.Namespace: - """ - Load configuration from JSON files. - - Args: - env_config_path (str): Path to the environment configuration file. - model_config_path (str): Path to the model configuration file. - model_def_path (str): Path to the model definition file. - - Returns: - argparse.Namespace: Loaded configuration. - """ - args = argparse.Namespace() - - with open(env_config_path, "r") as f: - env_config = json.load(f) - for k, v in env_config.items(): - setattr(args, k, v) - - with open(model_config_path, "r") as f: - model_config = json.load(f) - for k, v in model_config.items(): - setattr(args, k, v) - - with open(model_def_path, "r") as f: - model_def = json.load(f) - for k, v in model_def.items(): - setattr(args, k, v) - - return args - - -def initialize_distributed(num_gpus: int) -> tuple: - """ - Initialize distributed training. - - Returns: - tuple: local_rank, world_size, and device. - """ - if torch.cuda.is_available() and num_gpus > 1: - dist.init_process_group(backend="nccl", init_method="env://") - local_rank = dist.get_rank() - world_size = dist.get_world_size() - else: - local_rank = 0 - world_size = 1 - device = torch.device("cuda", local_rank) - torch.cuda.set_device(device) - return local_rank, world_size, device diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_train.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_train.py deleted file mode 100644 index 1376c2c65e320c9cd639043cec7069bba047c0bd..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_train.py +++ /dev/null @@ -1,536 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import argparse -import json -import logging -import os -from datetime import datetime -from pathlib import Path - -import monai -import torch -import torch.distributed as dist -from monai.data import DataLoader, partition_dataset -from monai.networks.schedulers import RFlowScheduler -from monai.networks.schedulers.ddpm import DDPMPredictionType -from monai.transforms import Compose -from monai.utils import first -from torch.amp import GradScaler, autocast -from torch.nn.parallel import DistributedDataParallel - -from .diff_model_setting import initialize_distributed, load_config, setup_logging -from .utils import define_instance - - -def load_filenames(data_list_path: str) -> list: - """ - Load filenames from the JSON data list. - - Args: - data_list_path (str): Path to the JSON data list file. - - Returns: - list: List of filenames. - """ - with open(data_list_path, "r") as file: - json_data = json.load(file) - filenames_train = json_data["training"] - return [_item["image"].replace(".nii.gz", "_emb.nii.gz") for _item in filenames_train] - - -def prepare_data( - train_files: list, - device: torch.device, - cache_rate: float, - num_workers: int = 2, - batch_size: int = 1, - include_body_region: bool = False, -) -> DataLoader: - """ - Prepare training data. - - Args: - train_files (list): List of training files. - device (torch.device): Device to use for training. - cache_rate (float): Cache rate for dataset. - num_workers (int): Number of workers for data loading. - batch_size (int): Mini-batch size. - include_body_region (bool): Whether to include body region in data - - Returns: - DataLoader: Data loader for training. - """ - - def _load_data_from_file(file_path, key): - with open(file_path) as f: - return torch.FloatTensor(json.load(f)[key]) - - train_transforms_list = [ - monai.transforms.LoadImaged(keys=["image"]), - monai.transforms.EnsureChannelFirstd(keys=["image"]), - monai.transforms.Lambdad(keys="spacing", func=lambda x: _load_data_from_file(x, "spacing")), - monai.transforms.Lambdad(keys="spacing", func=lambda x: x * 1e2), - ] - if include_body_region: - train_transforms_list += [ - monai.transforms.Lambdad( - keys="top_region_index", func=lambda x: _load_data_from_file(x, "top_region_index") - ), - monai.transforms.Lambdad( - keys="bottom_region_index", - func=lambda x: _load_data_from_file(x, "bottom_region_index"), - ), - monai.transforms.Lambdad(keys="top_region_index", func=lambda x: x * 1e2), - monai.transforms.Lambdad(keys="bottom_region_index", func=lambda x: x * 1e2), - ] - train_transforms = Compose(train_transforms_list) - - train_ds = monai.data.CacheDataset( - data=train_files, transform=train_transforms, cache_rate=cache_rate, num_workers=num_workers - ) - - return DataLoader(train_ds, num_workers=6, batch_size=batch_size, shuffle=True) - - -def load_unet( - args: argparse.Namespace, device: torch.device, logger: logging.Logger -) -> torch.nn.Module: - """ - Load the UNet model. - - Args: - args (argparse.Namespace): Configuration arguments. - device (torch.device): Device to load the model on. - logger (logging.Logger): Logger for logging information. - - Returns: - torch.nn.Module: Loaded UNet model. - """ - unet = define_instance(args, "diffusion_unet_def").to(device) - unet = torch.nn.SyncBatchNorm.convert_sync_batchnorm(unet) - - if dist.is_initialized(): - unet = DistributedDataParallel(unet, device_ids=[device], find_unused_parameters=True) - - if args.existing_ckpt_filepath is None: - logger.info("Training from scratch.") - else: - checkpoint_unet = torch.load( - f"{args.existing_ckpt_filepath}", map_location=device, weights_only=False - ) - if dist.is_initialized(): - unet.module.load_state_dict(checkpoint_unet["unet_state_dict"], strict=True) - else: - unet.load_state_dict(checkpoint_unet["unet_state_dict"], strict=True) - logger.info(f"Pretrained checkpoint {args.existing_ckpt_filepath} loaded.") - - return unet - - -def calculate_scale_factor( - train_loader: DataLoader, device: torch.device, logger: logging.Logger -) -> torch.Tensor: - """ - Calculate the scaling factor for the dataset. - - Args: - train_loader (DataLoader): Data loader for training. - device (torch.device): Device to use for calculation. - logger (logging.Logger): Logger for logging information. - - Returns: - torch.Tensor: Calculated scaling factor. - """ - check_data = first(train_loader) - z = check_data["image"].to(device) - scale_factor = 1 / torch.std(z) - logger.info(f"Scaling factor set to {scale_factor}.") - - if dist.is_initialized(): - dist.barrier() - dist.all_reduce(scale_factor, op=torch.distributed.ReduceOp.AVG) - logger.info(f"scale_factor -> {scale_factor}.") - return scale_factor - - -def create_optimizer(model: torch.nn.Module, lr: float) -> torch.optim.Optimizer: - """ - Create optimizer for training. - - Args: - model (torch.nn.Module): Model to optimize. - lr (float): Learning rate. - - Returns: - torch.optim.Optimizer: Created optimizer. - """ - return torch.optim.Adam(params=model.parameters(), lr=lr) - - -def create_lr_scheduler( - optimizer: torch.optim.Optimizer, total_steps: int -) -> torch.optim.lr_scheduler.PolynomialLR: - """ - Create learning rate scheduler. - - Args: - optimizer (torch.optim.Optimizer): Optimizer to schedule. - total_steps (int): Total number of training steps. - - Returns: - torch.optim.lr_scheduler.PolynomialLR: Created learning rate scheduler. - """ - return torch.optim.lr_scheduler.PolynomialLR(optimizer, total_iters=total_steps, power=2.0) - - -def train_one_epoch( - epoch: int, - unet: torch.nn.Module, - train_loader: DataLoader, - optimizer: torch.optim.Optimizer, - lr_scheduler: torch.optim.lr_scheduler.PolynomialLR, - loss_pt: torch.nn.L1Loss, - scaler: GradScaler, - scale_factor: torch.Tensor, - noise_scheduler: torch.nn.Module, - num_images_per_batch: int, - num_train_timesteps: int, - device: torch.device, - logger: logging.Logger, - local_rank: int, - amp: bool = True, -) -> torch.Tensor: - """ - Train the model for one epoch. - - Args: - epoch (int): Current epoch number. - unet (torch.nn.Module): UNet model. - train_loader (DataLoader): Data loader for training. - optimizer (torch.optim.Optimizer): Optimizer. - lr_scheduler (torch.optim.lr_scheduler.PolynomialLR): Learning rate scheduler. - loss_pt (torch.nn.L1Loss): Loss function. - scaler (GradScaler): Gradient scaler for mixed precision training. - scale_factor (torch.Tensor): Scaling factor. - noise_scheduler (torch.nn.Module): Noise scheduler. - num_images_per_batch (int): Number of images per batch. - num_train_timesteps (int): Number of training timesteps. - device (torch.device): Device to use for training. - logger (logging.Logger): Logger for logging information. - local_rank (int): Local rank for distributed training. - amp (bool): Use automatic mixed precision training. - - Returns: - torch.Tensor: Training loss for the epoch. - """ - include_body_region = unet.include_top_region_index_input - include_modality = unet.num_class_embeds is not None - - if local_rank == 0: - current_lr = optimizer.param_groups[0]["lr"] - logger.info(f"Epoch {epoch + 1}, lr {current_lr}.") - - _iter = 0 - loss_torch = torch.zeros(2, dtype=torch.float, device=device) - - unet.train() - for train_data in train_loader: - current_lr = optimizer.param_groups[0]["lr"] - - _iter += 1 - images = train_data["image"].to(device) - images = images * scale_factor - - if include_body_region: - top_region_index_tensor = train_data["top_region_index"].to(device) - bottom_region_index_tensor = train_data["bottom_region_index"].to(device) - # We trained with only CT in this version - if include_modality: - modality_tensor = torch.ones((len(images),), dtype=torch.long).to(device) - spacing_tensor = train_data["spacing"].to(device) - - optimizer.zero_grad(set_to_none=True) - - with autocast("cuda", enabled=amp): - noise = torch.randn_like(images) - - if isinstance(noise_scheduler, RFlowScheduler): - timesteps = noise_scheduler.sample_timesteps(images) - else: - timesteps = torch.randint( - 0, num_train_timesteps, (images.shape[0],), device=images.device - ).long() - - noisy_latent = noise_scheduler.add_noise( - original_samples=images, noise=noise, timesteps=timesteps - ) - - # Create a dictionary to store the inputs - unet_inputs = { - "x": noisy_latent, - "timesteps": timesteps, - "spacing_tensor": spacing_tensor, - } - # Add extra arguments if include_body_region is True - if include_body_region: - unet_inputs.update( - { - "top_region_index_tensor": top_region_index_tensor, - "bottom_region_index_tensor": bottom_region_index_tensor, - } - ) - if include_modality: - unet_inputs.update( - { - "class_labels": modality_tensor, - } - ) - model_output = unet(**unet_inputs) - - if noise_scheduler.prediction_type == DDPMPredictionType.EPSILON: - # predict noise - model_gt = noise - elif noise_scheduler.prediction_type == DDPMPredictionType.SAMPLE: - # predict sample - model_gt = images - elif noise_scheduler.prediction_type == DDPMPredictionType.V_PREDICTION: - # predict velocity - model_gt = images - noise - else: - raise ValueError( - "noise scheduler prediction type has to be chosen from ", - f"[{DDPMPredictionType.EPSILON},{DDPMPredictionType.SAMPLE},{DDPMPredictionType.V_PREDICTION}]", - ) - - loss = loss_pt(model_output.float(), model_gt.float()) - - if amp: - scaler.scale(loss).backward() - scaler.step(optimizer) - scaler.update() - else: - loss.backward() - optimizer.step() - - lr_scheduler.step() - - loss_torch[0] += loss.item() - loss_torch[1] += 1.0 - - if local_rank == 0: - logger.info( - "[{0}] epoch {1}, iter {2}/{3}, loss: {4:.4f}, lr: {5:.12f}.".format( - str(datetime.now())[:19], - epoch + 1, - _iter, - len(train_loader), - loss.item(), - current_lr, - ) - ) - - if dist.is_initialized(): - dist.all_reduce(loss_torch, op=torch.distributed.ReduceOp.SUM) - - return loss_torch - - -def save_checkpoint( - epoch: int, - unet: torch.nn.Module, - loss_torch_epoch: float, - num_train_timesteps: int, - scale_factor: torch.Tensor, - ckpt_folder: str, - args: argparse.Namespace, -) -> None: - """ - Save checkpoint. - - Args: - epoch (int): Current epoch number. - unet (torch.nn.Module): UNet model. - loss_torch_epoch (float): Training loss for the epoch. - num_train_timesteps (int): Number of training timesteps. - scale_factor (torch.Tensor): Scaling factor. - ckpt_folder (str): Checkpoint folder path. - args (argparse.Namespace): Configuration arguments. - """ - unet_state_dict = unet.module.state_dict() if dist.is_initialized() else unet.state_dict() - torch.save( - { - "epoch": epoch + 1, - "loss": loss_torch_epoch, - "num_train_timesteps": num_train_timesteps, - "scale_factor": scale_factor, - "unet_state_dict": unet_state_dict, - }, - f"{ckpt_folder}/{args.model_filename}", - ) - - -def diff_model_train( - env_config_path: str, - model_config_path: str, - model_def_path: str, - num_gpus: int, - amp: bool = True, -) -> None: - """ - Main function to train a diffusion model. - - Args: - env_config_path (str): Path to the environment configuration file. - model_config_path (str): Path to the model configuration file. - model_def_path (str): Path to the model definition file. - num_gpus (int): Number of GPUs to use for training. - amp (bool): Use automatic mixed precision training. - """ - args = load_config(env_config_path, model_config_path, model_def_path) - local_rank, world_size, device = initialize_distributed(num_gpus) - logger = setup_logging("training") - - logger.info(f"Using {device} of {world_size}") - - if local_rank == 0: - logger.info(f"[config] ckpt_folder -> {args.model_dir}.") - logger.info(f"[config] data_root -> {args.embedding_base_dir}.") - logger.info(f"[config] data_list -> {args.json_data_list}.") - logger.info(f"[config] lr -> {args.diffusion_unet_train['lr']}.") - logger.info(f"[config] num_epochs -> {args.diffusion_unet_train['n_epochs']}.") - logger.info( - f"[config] num_train_timesteps -> {args.noise_scheduler['num_train_timesteps']}." - ) - - Path(args.model_dir).mkdir(parents=True, exist_ok=True) - - unet = load_unet(args, device, logger) - noise_scheduler = define_instance(args, "noise_scheduler") - include_body_region = unet.include_top_region_index_input - - filenames_train = load_filenames(args.json_data_list) - if local_rank == 0: - logger.info(f"num_files_train: {len(filenames_train)}") - - train_files = [] - for _i in range(len(filenames_train)): - str_img = os.path.join(args.embedding_base_dir, filenames_train[_i]) - if not os.path.exists(str_img): - continue - - str_info = os.path.join(args.embedding_base_dir, filenames_train[_i]) + ".json" - train_files_i = {"image": str_img, "spacing": str_info} - if include_body_region: - train_files_i["top_region_index"] = str_info - train_files_i["bottom_region_index"] = str_info - train_files.append(train_files_i) - if dist.is_initialized(): - train_files = partition_dataset( - data=train_files, - shuffle=True, - num_partitions=dist.get_world_size(), - even_divisible=True, - )[local_rank] - - train_loader = prepare_data( - train_files, - device, - args.diffusion_unet_train["cache_rate"], - batch_size=args.diffusion_unet_train["batch_size"], - include_body_region=include_body_region, - ) - - scale_factor = calculate_scale_factor(train_loader, device, logger) - optimizer = create_optimizer(unet, args.diffusion_unet_train["lr"]) - - total_steps = ( - args.diffusion_unet_train["n_epochs"] * len(train_loader.dataset) - ) / args.diffusion_unet_train["batch_size"] - lr_scheduler = create_lr_scheduler(optimizer, total_steps) - loss_pt = torch.nn.L1Loss() - scaler = GradScaler("cuda") - - torch.set_float32_matmul_precision("highest") - logger.info("torch.set_float32_matmul_precision -> highest.") - - for epoch in range(args.diffusion_unet_train["n_epochs"]): - loss_torch = train_one_epoch( - epoch, - unet, - train_loader, - optimizer, - lr_scheduler, - loss_pt, - scaler, - scale_factor, - noise_scheduler, - args.diffusion_unet_train["batch_size"], - args.noise_scheduler["num_train_timesteps"], - device, - logger, - local_rank, - amp=amp, - ) - - loss_torch = loss_torch.tolist() - if torch.cuda.device_count() == 1 or local_rank == 0: - loss_torch_epoch = loss_torch[0] / loss_torch[1] - logger.info(f"epoch {epoch + 1} average loss: {loss_torch_epoch:.4f}.") - - save_checkpoint( - epoch, - unet, - loss_torch_epoch, - args.noise_scheduler["num_train_timesteps"], - scale_factor, - args.model_dir, - args, - ) - - if dist.is_initialized(): - dist.destroy_process_group() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Diffusion Model Training") - parser.add_argument( - "--env_config", - type=str, - default="./configs/environment_maisi_diff_model.json", - help="Path to environment configuration file", - ) - parser.add_argument( - "--model_config", - type=str, - default="./configs/config_maisi_diff_model.json", - help="Path to model training/inference configuration", - ) - parser.add_argument( - "--model_def", - type=str, - default="./configs/config_maisi.json", - help="Path to model definition file", - ) - parser.add_argument( - "--num_gpus", type=int, default=1, help="Number of GPUs to use for training" - ) - parser.add_argument( - "--no_amp", - dest="amp", - action="store_false", - help="Disable automatic mixed precision training", - ) - - args = parser.parse_args() - diff_model_train(args.env_config, args.model_config, args.model_def, args.num_gpus, args.amp) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/find_masks.py b/itrialspace/src/itrialspace/synthesis/scripts/find_masks.py deleted file mode 100644 index 42106f5f2a8794c556d116ea4c2407372095ecd4..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/find_masks.py +++ /dev/null @@ -1,170 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import json -import os -from typing import Sequence - -from monai.apps.utils import extractall -from monai.utils import ensure_tuple_rep - - -def convert_body_region(body_region: str | Sequence[str]) -> Sequence[int]: - """ - Convert body region string to body region index. - Args: - body_region: list of input body region string. If single str, will be converted to list of str. - Return: - body_region_indices, list of input body region index. - """ - if type(body_region) is str: - body_region = [body_region] - - # body region mapping for maisi - region_mapping_maisi = { - "head": 0, - "chest": 1, - "thorax": 1, - "chest/thorax": 1, - "abdomen": 2, - "pelvis": 3, - "lower": 3, - "pelvis/lower": 3, - } - - # perform mapping - body_region_indices = [] - for region in body_region: - normalized_region = region.lower() # norm str to lower case - if normalized_region not in region_mapping_maisi: - raise ValueError(f"Invalid region: {normalized_region}") - body_region_indices.append(region_mapping_maisi[normalized_region]) - - return body_region_indices - - -def find_masks( - body_region: str | Sequence[str], - anatomy_list: int | Sequence[int], - spacing: Sequence[float] | float = 1.0, - output_size: Sequence[int] = [512, 512, 512], - check_spacing_and_output_size: bool = False, - database_filepath: str = "./configs/database.json", - mask_foldername: str = "./datasets/masks/", -): - """ - Find candidate masks that fullfills all the requirements. - They shoud contain all the body region in `body_region`, all the anatomies in `anatomy_list`. - If there is no tumor specified in `anatomy_list`, we also expect the candidate masks to be tumor free. - If check_spacing_and_output_size is True, the candidate masks need to have the expected `spacing` and `output_size`. - Args: - body_region: list of input body region string. If single str, will be converted to list of str. - The found candidate mask will include these body regions. - anatomy_list: list of input anatomy. The found candidate mask will include these anatomies. - spacing: list of three floats, voxel spacing. If providing a single number, will use it for all the three dimensions. - output_size: list of three int, expected candidate mask spatial size. - check_spacing_and_output_size: whether we expect candidate mask to have spatial size of `output_size` and voxel size of `spacing`. - database_filepath: path for the json file that stores the information of all the candidate masks. - mask_foldername: directory that saves all the candidate masks. - Return: - candidate_masks, list of dict, each dict contains information of one candidate mask that fullfills all the requirements. - """ - # check and preprocess input - body_region = convert_body_region(body_region) - - if isinstance(anatomy_list, int): - anatomy_list = [anatomy_list] - - spacing = ensure_tuple_rep(spacing, 3) - - if not os.path.exists(mask_foldername): - zip_file_path = mask_foldername + ".zip" - - if not os.path.isfile(zip_file_path): - raise ValueError( - f"Please download {zip_file_path} following the instruction in ./datasets/README.md." - ) - - print(f"Extracting {zip_file_path} to {os.path.dirname(zip_file_path)}") - extractall( - filepath=zip_file_path, output_dir=os.path.dirname(zip_file_path), file_type="zip" - ) - print(f"Unzipped {zip_file_path} to {mask_foldername}.") - - if not os.path.isfile(database_filepath): - raise ValueError( - f"Please download {database_filepath} following the instruction in ./datasets/README.md." - ) - with open(database_filepath, "r") as f: - db = json.load(f) - - # select candidate_masks - candidate_masks = [] - for _item in db: - if not set(anatomy_list).issubset(_item["label_list"]): - continue - - # whether to keep this mask, default to be True. - keep_mask = True - - # extract region indice (top_index and bottom_index) for candidate mask - include_body_region = "top_region_index" in _item.keys() - if include_body_region: - top_index = [ - index for index, element in enumerate(_item["top_region_index"]) if element != 0 - ] - top_index = top_index[0] - bottom_index = [ - index for index, element in enumerate(_item["bottom_region_index"]) if element != 0 - ] - bottom_index = bottom_index[0] - - # if candiate mask does not contain all the body_region, skip it - for _idx in body_region: - if _idx > bottom_index or _idx < top_index: - keep_mask = False - - for tumor_label in [23, 24, 26, 27, 128]: - # we skip those mask with tumors if users do not provide tumor label in anatomy_list - if tumor_label not in anatomy_list and tumor_label in _item["label_list"]: - keep_mask = False - - if check_spacing_and_output_size: - # if the output_size and spacing are different with user's input, skip it - for axis in range(3): - if ( - _item["dim"][axis] != output_size[axis] - or _item["spacing"][axis] != spacing[axis] - ): - keep_mask = False - - if keep_mask: - # if decide to keep this mask, we pack the information of this mask and add to final output. - candidate = { - "pseudo_label": os.path.join(mask_foldername, _item["pseudo_label_filename"]), - "spacing": _item["spacing"], - "dim": _item["dim"], - } - if include_body_region: - candidate["top_region_index"] = _item["top_region_index"] - candidate["bottom_region_index"] = _item["bottom_region_index"] - - # Conditionally add the label to the candidate dictionary - if "label_filename" in _item: - candidate["label"] = os.path.join(mask_foldername, _item["label_filename"]) - - candidate_masks.append(candidate) - - if len(candidate_masks) == 0 and not check_spacing_and_output_size: - raise ValueError("Cannot find body region with given anatomy list.") - - return candidate_masks diff --git a/itrialspace/src/itrialspace/synthesis/scripts/infer_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/infer_controlnet.py deleted file mode 100644 index 606a4d3036812599ace3a5b003638abe9d2d8a5a..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/infer_controlnet.py +++ /dev/null @@ -1,237 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import argparse -import json -import logging -import os -import sys -from datetime import datetime - -import torch -import torch.distributed as dist -from monai.data import MetaTensor, decollate_batch -from monai.networks.utils import copy_model_state -from monai.transforms import SaveImage -from monai.utils import RankFilter - -from .sample import check_input, ldm_conditional_sample_one_image -from .utils import define_instance, prepare_maisi_controlnet_json_dataloader, setup_ddp - - -@torch.inference_mode() -def main(): - parser = argparse.ArgumentParser(description="maisi.controlnet.infer") - parser.add_argument( - "-e", - "--environment-file", - default="./configs/environment_maisi_controlnet_train.json", - help="environment json file that stores environment path", - ) - parser.add_argument( - "-c", - "--config-file", - default="./configs/config_maisi.json", - help="config json file that stores network hyper-parameters", - ) - parser.add_argument( - "-t", - "--training-config", - default="./configs/config_maisi_controlnet_train.json", - help="config json file that stores training hyper-parameters", - ) - parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") - - args = parser.parse_args() - - # Step 0: configuration - logger = logging.getLogger("maisi.controlnet.infer") - # whether to use distributed data parallel - use_ddp = args.gpus > 1 - if use_ddp: - rank = int(os.environ["LOCAL_RANK"]) - world_size = int(os.environ["WORLD_SIZE"]) - device = setup_ddp(rank, world_size) - logger.addFilter(RankFilter()) - else: - rank = 0 - world_size = 1 - device = torch.device(f"cuda:{rank}") - - torch.cuda.set_device(device) - logger.info(f"Number of GPUs: {torch.cuda.device_count()}") - logger.info(f"World_size: {world_size}") - - with open(args.environment_file, "r") as env_file: - env_dict = json.load(env_file) - with open(args.config_file, "r") as config_file: - config_dict = json.load(config_file) - with open(args.training_config, "r") as training_config_file: - training_config_dict = json.load(training_config_file) - - for k, v in env_dict.items(): - setattr(args, k, v) - for k, v in config_dict.items(): - setattr(args, k, v) - for k, v in training_config_dict.items(): - setattr(args, k, v) - - # Step 1: set data loader - _, val_loader = prepare_maisi_controlnet_json_dataloader( - json_data_list=args.json_data_list, - data_base_dir=args.data_base_dir, - rank=rank, - world_size=world_size, - batch_size=args.controlnet_train["batch_size"], - cache_rate=args.controlnet_train["cache_rate"], - fold=args.controlnet_train["fold"], - ) - - # Step 2: define AE, diffusion model and controlnet - # define AE - autoencoder = define_instance(args, "autoencoder_def").to(device) - # load trained autoencoder model - if args.trained_autoencoder_path is not None: - if not os.path.exists(args.trained_autoencoder_path): - raise ValueError("Please download the autoencoder checkpoint.") - autoencoder_ckpt = torch.load(args.trained_autoencoder_path, weights_only=True) - autoencoder.load_state_dict(autoencoder_ckpt) - logger.info(f"Load trained diffusion model from {args.trained_autoencoder_path}.") - else: - logger.info("trained autoencoder model is not loaded.") - - # define diffusion Model - unet = define_instance(args, "diffusion_unet_def").to(device) - include_body_region = unet.include_top_region_index_input - include_modality = unet.num_class_embeds is not None - - # load trained diffusion model - if args.trained_diffusion_path is not None: - if not os.path.exists(args.trained_diffusion_path): - raise ValueError("Please download the trained diffusion unet checkpoint.") - diffusion_model_ckpt = torch.load( - args.trained_diffusion_path, map_location=device, weights_only=False - ) - unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) - # load scale factor from diffusion model checkpoint - scale_factor = diffusion_model_ckpt["scale_factor"] - logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") - logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") - else: - logger.info("trained diffusion model is not loaded.") - scale_factor = 1.0 - logger.info(f"set scale_factor -> {scale_factor}.") - - # define ControlNet - controlnet = define_instance(args, "controlnet_def").to(device) - # copy weights from the DM to the controlnet - copy_model_state(controlnet, unet.state_dict()) - # load trained controlnet model if it is provided - if args.trained_controlnet_path is not None: - if not os.path.exists(args.trained_controlnet_path): - raise ValueError("Please download the trained ControlNet checkpoint.") - controlnet.load_state_dict( - torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ - "controlnet_state_dict" - ] - ) - logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") - else: - logger.info("trained controlnet is not loaded.") - - noise_scheduler = define_instance(args, "noise_scheduler") - - # Step 3: inference - autoencoder.eval() - controlnet.eval() - unet.eval() - - for batch in val_loader: - - # get label mask - labels = batch["label"].to(device) - # get corresponding conditions - if include_body_region: - top_region_index_tensor = batch["top_region_index"].to(device) - bottom_region_index_tensor = batch["bottom_region_index"].to(device) - else: - top_region_index_tensor = None - bottom_region_index_tensor = None - spacing_tensor = batch["spacing"].to(device) - modality_tensor = args.controlnet_infer["modality"] * torch.ones( - (len(labels),), dtype=torch.long - ).to(device) - out_spacing = tuple((batch["spacing"].squeeze().numpy() / 100).tolist()) - # get target dimension - dim = batch["dim"] - output_size = (dim[0].item(), dim[1].item(), dim[2].item()) - latent_shape = ( - args.latent_channels, - output_size[0] // 4, - output_size[1] // 4, - output_size[2] // 4, - ) - # check if output_size and out_spacing are valid. - check_input(None, None, None, output_size, out_spacing, None) - # generate a single synthetic image using a latent diffusion model with controlnet. - synthetic_images, _ = ldm_conditional_sample_one_image( - autoencoder=autoencoder, - diffusion_unet=unet, - controlnet=controlnet, - noise_scheduler=noise_scheduler, - scale_factor=scale_factor, - device=device, - combine_label_or=labels, - top_region_index_tensor=top_region_index_tensor, - bottom_region_index_tensor=bottom_region_index_tensor, - spacing_tensor=spacing_tensor, - modality_tensor=modality_tensor, - latent_shape=latent_shape, - output_size=output_size, - noise_factor=1.0, - num_inference_steps=args.controlnet_infer["num_inference_steps"], - autoencoder_sliding_window_infer_size=args.controlnet_infer[ - "autoencoder_sliding_window_infer_size" - ], - autoencoder_sliding_window_infer_overlap=args.controlnet_infer[ - "autoencoder_sliding_window_infer_overlap" - ], - ) - # save image/label pairs - labels = decollate_batch(batch)[0]["label"] - real_object_name = labels.meta.get("filename_or_obj", "default_name.nii.gz") - labels.meta["filename_or_obj"] = real_object_name - output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") - synthetic_images = MetaTensor(synthetic_images.squeeze(0), meta=labels.meta) - img_saver = SaveImage( - output_dir=args.output_dir, - output_postfix="image", - separate_folder=False, - ) - img_saver(synthetic_images) - label_saver = SaveImage( - output_dir=args.output_dir, - output_postfix="label", - separate_folder=False, - ) - label_saver(labels) - if use_ddp: - dist.destroy_process_group() - - -if __name__ == "__main__": - logging.basicConfig( - stream=sys.stdout, - level=logging.INFO, - format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py deleted file mode 100644 index 1ca27fb9d5e6a94c171d37e611aefab49fd0bdfb..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py +++ /dev/null @@ -1,241 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import argparse -import json -import logging -import os -import sys -from datetime import datetime - -import torch -import torch.distributed as dist -from monai.data import MetaTensor, decollate_batch -from monai.networks.utils import copy_model_state -from monai.transforms import SaveImage -from monai.utils import RankFilter - -from .sample import check_input, ldm_conditional_sample_one_image -from .utils import ( - define_instance, - prepare_maisi_controlnet_json_dataloader, - prepare_maisi_controlnet_test_dataloader, - setup_ddp, -) - - -@torch.inference_mode() -def main(): - parser = argparse.ArgumentParser(description="maisi.controlnet.infer") - parser.add_argument( - "-e", - "--environment-file", - default="./configs/environment_maisi_controlnet_train.json", - help="environment json file that stores environment path", - ) - parser.add_argument( - "-c", - "--config-file", - default="./configs/config_maisi.json", - help="config json file that stores network hyper-parameters", - ) - parser.add_argument( - "-t", - "--training-config", - default="./configs/config_maisi_controlnet_train.json", - help="config json file that stores training hyper-parameters", - ) - parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") - - args = parser.parse_args() - - # Step 0: configuration - logger = logging.getLogger("maisi.controlnet.infer") - # whether to use distributed data parallel - use_ddp = args.gpus > 1 - if use_ddp: - rank = int(os.environ["LOCAL_RANK"]) - world_size = int(os.environ["WORLD_SIZE"]) - device = setup_ddp(rank, world_size) - logger.addFilter(RankFilter()) - else: - rank = 0 - world_size = 1 - device = torch.device(f"cuda:{rank}") - - torch.cuda.set_device(device) - logger.info(f"Number of GPUs: {torch.cuda.device_count()}") - logger.info(f"World_size: {world_size}") - - with open(args.environment_file, "r") as env_file: - env_dict = json.load(env_file) - with open(args.config_file, "r") as config_file: - config_dict = json.load(config_file) - with open(args.training_config, "r") as training_config_file: - training_config_dict = json.load(training_config_file) - - for k, v in env_dict.items(): - setattr(args, k, v) - for k, v in config_dict.items(): - setattr(args, k, v) - for k, v in training_config_dict.items(): - setattr(args, k, v) - - # Step 1: set data loader - val_loader = prepare_maisi_controlnet_test_dataloader( - json_data_list=args.json_data_list, - data_base_dir=args.data_base_dir, - batch_size=args.controlnet_train["batch_size"], - cache_rate=args.controlnet_train["cache_rate"], - rank=rank, - world_size=world_size, - ) - - # Step 2: define AE, diffusion model and controlnet - # define AE - autoencoder = define_instance(args, "autoencoder_def").to(device) - # load trained autoencoder model - if args.trained_autoencoder_path is not None: - if not os.path.exists(args.trained_autoencoder_path): - raise ValueError("Please download the autoencoder checkpoint.") - autoencoder_ckpt = torch.load(args.trained_autoencoder_path, weights_only=True) - autoencoder.load_state_dict(autoencoder_ckpt) - logger.info(f"Load trained diffusion model from {args.trained_autoencoder_path}.") - else: - logger.info("trained autoencoder model is not loaded.") - - # define diffusion Model - unet = define_instance(args, "diffusion_unet_def").to(device) - include_body_region = unet.include_top_region_index_input - include_modality = unet.num_class_embeds is not None - - # load trained diffusion model - if args.trained_diffusion_path is not None: - if not os.path.exists(args.trained_diffusion_path): - raise ValueError("Please download the trained diffusion unet checkpoint.") - diffusion_model_ckpt = torch.load( - args.trained_diffusion_path, map_location=device, weights_only=False - ) - unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) - # load scale factor from diffusion model checkpoint - scale_factor = diffusion_model_ckpt["scale_factor"] - logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") - logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") - else: - logger.info("trained diffusion model is not loaded.") - scale_factor = 1.0 - logger.info(f"set scale_factor -> {scale_factor}.") - - # define ControlNet - controlnet = define_instance(args, "controlnet_def").to(device) - # copy weights from the DM to the controlnet - copy_model_state(controlnet, unet.state_dict()) - # load trained controlnet model if it is provided - if args.trained_controlnet_path is not None: - if not os.path.exists(args.trained_controlnet_path): - raise ValueError("Please download the trained ControlNet checkpoint.") - controlnet.load_state_dict( - torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ - "controlnet_state_dict" - ] - ) - logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") - else: - logger.info("trained controlnet is not loaded.") - - noise_scheduler = define_instance(args, "noise_scheduler") - - # Step 3: inference - autoencoder.eval() - controlnet.eval() - unet.eval() - - for batch in val_loader: - - # get label mask - labels = batch["label"].to(device) - # get corresponding conditions - if include_body_region: - top_region_index_tensor = batch["top_region_index"].to(device) - bottom_region_index_tensor = batch["bottom_region_index"].to(device) - else: - top_region_index_tensor = None - bottom_region_index_tensor = None - spacing_tensor = batch["spacing"].to(device) - modality_tensor = args.controlnet_infer["modality"] * torch.ones( - (len(labels),), dtype=torch.long - ).to(device) - out_spacing = tuple((batch["spacing"].squeeze().numpy() / 100).tolist()) - # get target dimension - dim = batch["dim"] - output_size = (dim[0].item(), dim[1].item(), dim[2].item()) - latent_shape = ( - args.latent_channels, - output_size[0] // 4, - output_size[1] // 4, - output_size[2] // 4, - ) - # check if output_size and out_spacing are valid. - check_input(None, None, None, output_size, out_spacing, None) - # generate a single synthetic image using a latent diffusion model with controlnet. - synthetic_images, _ = ldm_conditional_sample_one_image( - autoencoder=autoencoder, - diffusion_unet=unet, - controlnet=controlnet, - noise_scheduler=noise_scheduler, - scale_factor=scale_factor, - device=device, - combine_label_or=labels, - top_region_index_tensor=top_region_index_tensor, - bottom_region_index_tensor=bottom_region_index_tensor, - spacing_tensor=spacing_tensor, - modality_tensor=modality_tensor, - latent_shape=latent_shape, - output_size=output_size, - noise_factor=1.0, - num_inference_steps=args.controlnet_infer["num_inference_steps"], - autoencoder_sliding_window_infer_size=args.controlnet_infer[ - "autoencoder_sliding_window_infer_size" - ], - autoencoder_sliding_window_infer_overlap=args.controlnet_infer[ - "autoencoder_sliding_window_infer_overlap" - ], - ) - # save image/label pairs - labels = decollate_batch(batch)[0]["label"] - real_object_name = labels.meta.get("filename_or_obj", "default_name.nii.gz") - labels.meta["filename_or_obj"] = real_object_name - output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") - synthetic_images = MetaTensor(synthetic_images.squeeze(0), meta=labels.meta) - img_saver = SaveImage( - output_dir=args.output_dir, - output_postfix="image", - separate_folder=False, - ) - img_saver(synthetic_images) - label_saver = SaveImage( - output_dir=args.output_dir, - output_postfix="label", - separate_folder=False, - ) - label_saver(labels) - if use_ddp: - dist.destroy_process_group() - - -if __name__ == "__main__": - logging.basicConfig( - stream=sys.stdout, - level=logging.INFO, - format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/infer_test_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/infer_test_controlnet.py deleted file mode 100644 index 0c173ca878401bb5fc93d95d4b78f8ae5803654d..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/infer_test_controlnet.py +++ /dev/null @@ -1,241 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import argparse -import json -import logging -import os -import sys -from datetime import datetime - -import torch -import torch.distributed as dist -from monai.data import MetaTensor, decollate_batch -from monai.networks.utils import copy_model_state -from monai.transforms import SaveImage -from monai.utils import RankFilter - -from .sample import check_input, ldm_conditional_sample_one_image -from .utils import ( - define_instance, - prepare_maisi_controlnet_infer_dataloader, - prepare_maisi_controlnet_json_dataloader, - setup_ddp, -) - - -@torch.inference_mode() -def main(): - parser = argparse.ArgumentParser(description="maisi.controlnet.infer") - parser.add_argument( - "-e", - "--environment-file", - default="./configs/environment_maisi_controlnet_train.json", - help="environment json file that stores environment path", - ) - parser.add_argument( - "-c", - "--config-file", - default="./configs/config_maisi.json", - help="config json file that stores network hyper-parameters", - ) - parser.add_argument( - "-t", - "--training-config", - default="./configs/config_maisi_controlnet_train.json", - help="config json file that stores training hyper-parameters", - ) - parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") - - args = parser.parse_args() - - # Step 0: configuration - logger = logging.getLogger("maisi.controlnet.infer") - # whether to use distributed data parallel - use_ddp = args.gpus > 1 - if use_ddp: - rank = int(os.environ["LOCAL_RANK"]) - world_size = int(os.environ["WORLD_SIZE"]) - device = setup_ddp(rank, world_size) - logger.addFilter(RankFilter()) - else: - rank = 0 - world_size = 1 - device = torch.device(f"cuda:{rank}") - - torch.cuda.set_device(device) - logger.info(f"Number of GPUs: {torch.cuda.device_count()}") - logger.info(f"World_size: {world_size}") - - with open(args.environment_file, "r") as env_file: - env_dict = json.load(env_file) - with open(args.config_file, "r") as config_file: - config_dict = json.load(config_file) - with open(args.training_config, "r") as training_config_file: - training_config_dict = json.load(training_config_file) - - for k, v in env_dict.items(): - setattr(args, k, v) - for k, v in config_dict.items(): - setattr(args, k, v) - for k, v in training_config_dict.items(): - setattr(args, k, v) - - # Step 1: set data loader - val_loader = prepare_maisi_controlnet_infer_dataloader( - json_data_list=args.json_data_list, - data_base_dir=args.data_base_dir, - batch_size=args.controlnet_train["batch_size"], - cache_rate=args.controlnet_train["cache_rate"], - rank=rank, - world_size=world_size, - ) - - # Step 2: define AE, diffusion model and controlnet - # define AE - autoencoder = define_instance(args, "autoencoder_def").to(device) - # load trained autoencoder model - if args.trained_autoencoder_path is not None: - if not os.path.exists(args.trained_autoencoder_path): - raise ValueError("Please download the autoencoder checkpoint.") - autoencoder_ckpt = torch.load(args.trained_autoencoder_path, weights_only=True) - autoencoder.load_state_dict(autoencoder_ckpt) - logger.info(f"Load trained diffusion model from {args.trained_autoencoder_path}.") - else: - logger.info("trained autoencoder model is not loaded.") - - # define diffusion Model - unet = define_instance(args, "diffusion_unet_def").to(device) - include_body_region = unet.include_top_region_index_input - include_modality = unet.num_class_embeds is not None - - # load trained diffusion model - if args.trained_diffusion_path is not None: - if not os.path.exists(args.trained_diffusion_path): - raise ValueError("Please download the trained diffusion unet checkpoint.") - diffusion_model_ckpt = torch.load( - args.trained_diffusion_path, map_location=device, weights_only=False - ) - unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) - # load scale factor from diffusion model checkpoint - scale_factor = diffusion_model_ckpt["scale_factor"] - logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") - logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") - else: - logger.info("trained diffusion model is not loaded.") - scale_factor = 1.0 - logger.info(f"set scale_factor -> {scale_factor}.") - - # define ControlNet - controlnet = define_instance(args, "controlnet_def").to(device) - # copy weights from the DM to the controlnet - copy_model_state(controlnet, unet.state_dict()) - # load trained controlnet model if it is provided - if args.trained_controlnet_path is not None: - if not os.path.exists(args.trained_controlnet_path): - raise ValueError("Please download the trained ControlNet checkpoint.") - controlnet.load_state_dict( - torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ - "controlnet_state_dict" - ] - ) - logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") - else: - logger.info("trained controlnet is not loaded.") - - noise_scheduler = define_instance(args, "noise_scheduler") - - # Step 3: inference - autoencoder.eval() - controlnet.eval() - unet.eval() - - for batch in val_loader: - - # get label mask - labels = batch["label"].to(device) - # get corresponding conditions - if include_body_region: - top_region_index_tensor = batch["top_region_index"].to(device) - bottom_region_index_tensor = batch["bottom_region_index"].to(device) - else: - top_region_index_tensor = None - bottom_region_index_tensor = None - spacing_tensor = batch["spacing"].to(device) - modality_tensor = args.controlnet_infer["modality"] * torch.ones( - (len(labels),), dtype=torch.long - ).to(device) - out_spacing = tuple((batch["spacing"].squeeze().numpy() / 100).tolist()) - # get target dimension - dim = batch["dim"] - output_size = (dim[0].item(), dim[1].item(), dim[2].item()) - latent_shape = ( - args.latent_channels, - output_size[0] // 4, - output_size[1] // 4, - output_size[2] // 4, - ) - # check if output_size and out_spacing are valid. - check_input(None, None, None, output_size, out_spacing, None) - # generate a single synthetic image using a latent diffusion model with controlnet. - synthetic_images, _ = ldm_conditional_sample_one_image( - autoencoder=autoencoder, - diffusion_unet=unet, - controlnet=controlnet, - noise_scheduler=noise_scheduler, - scale_factor=scale_factor, - device=device, - combine_label_or=labels, - top_region_index_tensor=top_region_index_tensor, - bottom_region_index_tensor=bottom_region_index_tensor, - spacing_tensor=spacing_tensor, - modality_tensor=modality_tensor, - latent_shape=latent_shape, - output_size=output_size, - noise_factor=1.0, - num_inference_steps=args.controlnet_infer["num_inference_steps"], - autoencoder_sliding_window_infer_size=args.controlnet_infer[ - "autoencoder_sliding_window_infer_size" - ], - autoencoder_sliding_window_infer_overlap=args.controlnet_infer[ - "autoencoder_sliding_window_infer_overlap" - ], - ) - # save image/label pairs - labels = decollate_batch(batch)[0]["label"] - real_object_name = labels.meta.get("filename_or_obj", "default_name.nii.gz") - labels.meta["filename_or_obj"] = real_object_name - output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") - synthetic_images = MetaTensor(synthetic_images.squeeze(0), meta=labels.meta) - img_saver = SaveImage( - output_dir=args.output_dir, - output_postfix="image", - separate_folder=False, - ) - img_saver(synthetic_images) - label_saver = SaveImage( - output_dir=args.output_dir, - output_postfix="label", - separate_folder=False, - ) - label_saver(labels) - if use_ddp: - dist.destroy_process_group() - - -if __name__ == "__main__": - logging.basicConfig( - stream=sys.stdout, - level=logging.INFO, - format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/inference.py b/itrialspace/src/itrialspace/synthesis/scripts/inference.py deleted file mode 100644 index 0e3474c061048a96897af36cdfeb67e9bee777a4..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/inference.py +++ /dev/null @@ -1,311 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -#     http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# # MAISI Inference Script -import argparse -import json -import logging -import os -import sys -import tempfile - -import monai -import torch -from monai.apps import download_url -from monai.config import print_config -from monai.transforms import LoadImage, Orientation -from monai.utils import set_determinism -from scripts.sample import LDMSampler, check_input -from scripts.utils import define_instance -from scripts.utils_plot import find_label_center_loc, get_xyz_plot, show_image - - -def main(): - parser = argparse.ArgumentParser(description="maisi.controlnet.training") - parser.add_argument( - "-e", - "--environment-file", - default="./configs/environment.json", - help="environment json file that stores environment path", - ) - parser.add_argument( - "-c", - "--config-file", - default="./configs/config_maisi.json", - help="config json file that stores network hyper-parameters", - ) - parser.add_argument( - "-i", - "--inference-file", - default="./configs/config_infer.json", - help="config json file that stores inference hyper-parameters", - ) - parser.add_argument( - "-x", - "--extra-config-file", - default=None, - help="config json file that stores inference extra parameters", - ) - parser.add_argument( - "-s", - "--random-seed", - default=None, - help="random seed, can be None or int", - ) - parser.add_argument( - "--version", - default="maisi3d-rflow", - type=str, - help="maisi_version, choose from ['maisi3d-ddpm', 'maisi3d-rflow']", - ) - args = parser.parse_args() - # Step 0: configuration - logger = logging.getLogger("maisi.inference") - - maisi_version = args.version - - # ## Set deterministic training for reproducibility - if args.random_seed is not None: - set_determinism(seed=args.random_seed) - - # ## Setup data directory - # You can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. - # This allows you to save results and reuse downloads. - # If not specified a temporary directory will be used. - - directory = os.environ.get("MONAI_DATA_DIRECTORY") - if directory is not None: - os.makedirs(directory, exist_ok=True) - root_dir = tempfile.mkdtemp() if directory is None else directory - print(root_dir) - - # TODO: remove the `files` after the files are uploaded to the NGC - files = [ - { - "path": "models/autoencoder_epoch273.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials" - "/model_zoo/model_maisi_autoencoder_epoch273_alternative.pt", - }, - { - "path": "models/mask_generation_autoencoder.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai" - "/tutorials/mask_generation_autoencoder.pt", - }, - { - "path": "models/mask_generation_diffusion_unet.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai" - "/tutorials/model_zoo/model_maisi_mask_generation_diffusion_unet_v2.pt", - }, - { - "path": "configs/all_anatomy_size_condtions.json", - "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/all_anatomy_size_condtions.json", - }, - { - "path": "datasets/all_masks_flexible_size_and_spacing_4000.zip", - "url": "https://developer.download.nvidia.com/assets/Clara/monai" - "/tutorials/all_masks_flexible_size_and_spacing_4000.zip", - }, - ] - - if maisi_version == "maisi3d-ddpm": - files += [ - { - "path": "models/diff_unet_3d_ddpm.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/model_zoo" - "/model_maisi_input_unet3d_data-all_steps1000size512ddpm_random_current_inputx_v1_alternative.pt", - }, - { - "path": "models/controlnet_3d_ddpm.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/model_zoo" - "/model_maisi_controlnet-20datasets-e20wl100fold0bc_noi_dia_fsize_current_alternative.pt", - }, - { - "path": "configs/candidate_masks_flexible_size_and_spacing_3000.json", - "url": "https://developer.download.nvidia.com/assets/Clara/monai" - "/tutorials/candidate_masks_flexible_size_and_spacing_3000.json", - }, - ] - elif maisi_version == "maisi3d-rflow": - files += [ - { - "path": "models/diff_unet_3d_rflow.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/" - "diff_unet_ckpt_rflow_epoch19350.pt", - }, - { - "path": "models/controlnet_3d_rflow.pt", - "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/" - "controlnet_rflow_epoch60.pt", - }, - { - "path": "configs/candidate_masks_flexible_size_and_spacing_4000.json", - "url": "https://developer.download.nvidia.com/assets/Clara/monai" - "/tutorials/candidate_masks_flexible_size_and_spacing_4000.json", - }, - ] - else: - raise ValueError( - f"maisi_version has to be chosen from ['maisi3d-ddpm', 'maisi3d-rflow'], yet got {maisi_version}." - ) - - for file in files: - file["path"] = ( - file["path"] - if "datasets/" not in file["path"] - else os.path.join(root_dir, file["path"]) - ) - download_url(url=file["url"], filepath=file["path"]) - - # ## Read in environment setting, including data directory, model directory, and output directory - # The information for data directory, model directory, and output directory are saved in ./configs/environment.json - env_dict = json.load(open(args.environment_file, "r")) - for k, v in env_dict.items(): - # Update the path to the downloaded dataset in MONAI_DATA_DIRECTORY - val = v if "datasets/" not in v else os.path.join(root_dir, v) - setattr(args, k, val) - print(f"{k}: {val}") - print("Global config variables have been loaded.") - - # ## Read in configuration setting, including network definition, body region and anatomy to generate, etc. - # - # The information for the inference input, like body region and anatomy to generate, is stored in "./configs/config_infer.json". - # Please refer to README.md for the details. - config_dict = json.load(open(args.config_file, "r")) - for k, v in config_dict.items(): - setattr(args, k, v) - - # check the format of inference inputs - config_infer_dict = json.load(open(args.inference_file, "r")) - # override num_split if asked - if "autoencoder_tp_num_splits" in config_infer_dict: - args.autoencoder_def["num_splits"] = config_infer_dict["autoencoder_tp_num_splits"] - args.mask_generation_autoencoder_def["num_splits"] = config_infer_dict[ - "autoencoder_tp_num_splits" - ] - for k, v in config_infer_dict.items(): - setattr(args, k, v) - print(f"{k}: {v}") - - # - # ## Read in optional extra configuration setting - typically acceleration options (TRT) - # - # - if args.extra_config_file is not None: - extra_config_dict = json.load(open(args.extra_config_file, "r")) - for k, v in extra_config_dict.items(): - setattr(args, k, v) - print(f"{k}: {v}") - - check_input( - args.body_region, - args.anatomy_list, - args.label_dict_json, - args.output_size, - args.spacing, - args.controllable_anatomy_size, - ) - latent_shape = [ - args.latent_channels, - args.output_size[0] // 4, - args.output_size[1] // 4, - args.output_size[2] // 4, - ] - print("Network definition and inference inputs have been loaded.") - - # ## Initialize networks and noise scheduler, then load the trained model weights. - # The networks and noise scheduler are defined in `config_file`. We will read them in and load the model weights. - noise_scheduler = define_instance(args, "noise_scheduler") - mask_generation_noise_scheduler = define_instance(args, "mask_generation_noise_scheduler") - - device = torch.device("cuda") - - autoencoder = define_instance(args, "autoencoder").to(device) - checkpoint_autoencoder = torch.load(args.trained_autoencoder_path, weights_only=True) - autoencoder.load_state_dict(checkpoint_autoencoder) - - diffusion_unet = define_instance(args, "diffusion_unet").to(device) - checkpoint_diffusion_unet = torch.load(args.trained_diffusion_path, weights_only=False) - diffusion_unet.load_state_dict(checkpoint_diffusion_unet["unet_state_dict"], strict=True) - scale_factor = checkpoint_diffusion_unet["scale_factor"].to(device) - - controlnet = define_instance(args, "controlnet").to(device) - checkpoint_controlnet = torch.load(args.trained_controlnet_path, weights_only=False) - monai.networks.utils.copy_model_state(controlnet, diffusion_unet.state_dict()) - controlnet.load_state_dict(checkpoint_controlnet["controlnet_state_dict"], strict=True) - - mask_generation_autoencoder = define_instance(args, "mask_generation_autoencoder").to(device) - checkpoint_mask_generation_autoencoder = torch.load( - args.trained_mask_generation_autoencoder_path, weights_only=True - ) - mask_generation_autoencoder.load_state_dict(checkpoint_mask_generation_autoencoder) - - mask_generation_diffusion_unet = define_instance(args, "mask_generation_diffusion").to(device) - checkpoint_mask_generation_diffusion_unet = torch.load( - args.trained_mask_generation_diffusion_path, weights_only=False - ) - mask_generation_diffusion_unet.load_state_dict( - checkpoint_mask_generation_diffusion_unet["unet_state_dict"] - ) - mask_generation_scale_factor = checkpoint_mask_generation_diffusion_unet["scale_factor"] - - print("All the trained model weights have been loaded.") - - # ## Define the LDM Sampler, which contains functions that will perform the inference. - ldm_sampler = LDMSampler( - args.body_region, - args.anatomy_list, - args.all_mask_files_json, - args.all_anatomy_size_conditions_json, - args.all_mask_files_base_dir, - args.label_dict_json, - args.label_dict_remap_json, - autoencoder, - diffusion_unet, - controlnet, - noise_scheduler, - scale_factor, - mask_generation_autoencoder, - mask_generation_diffusion_unet, - mask_generation_scale_factor, - mask_generation_noise_scheduler, - device, - latent_shape, - args.mask_generation_latent_shape, - args.output_size, - args.output_dir, - args.controllable_anatomy_size, - image_output_ext=args.image_output_ext, - label_output_ext=args.label_output_ext, - spacing=args.spacing, - modality=args.modality, - num_inference_steps=args.num_inference_steps, - mask_generation_num_inference_steps=args.mask_generation_num_inference_steps, - random_seed=args.random_seed, - autoencoder_sliding_window_infer_size=args.autoencoder_sliding_window_infer_size, - autoencoder_sliding_window_infer_overlap=args.autoencoder_sliding_window_infer_overlap, - ) - - print(f"The generated image/mask pairs will be saved in {args.output_dir}.") - output_filenames = ldm_sampler.sample_multiple_images(args.num_output_samples) - print("MAISI image/mask generation finished") - - -if __name__ == "__main__": - logging.basicConfig( - stream=sys.stdout, - level=logging.INFO, - format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - torch.cuda.reset_peak_memory_stats() - main() - peak_memory_gb = torch.cuda.max_memory_allocated() / (1024**3) # Convert to GB - print(f"Peak GPU memory usage: {peak_memory_gb:.2f} GB") diff --git a/itrialspace/src/itrialspace/synthesis/scripts/quality_check.py b/itrialspace/src/itrialspace/synthesis/scripts/quality_check.py deleted file mode 100644 index 7e5b83ab3a6b46954992fdb62be977cd792d2ee2..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/quality_check.py +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import numpy as np - - -def get_masked_data(label_data, image_data, labels): - """ - Extracts and returns the image data corresponding to specified labels within a 3D volume. - - This function efficiently masks the `image_data` array based on the provided `labels` in the `label_data` array. - The function handles cases with both a large and small number of labels, optimizing performance accordingly. - - Args: - label_data (np.ndarray): A NumPy array containing label data, representing different anatomical - regions or classes in a 3D medical image. - image_data (np.ndarray): A NumPy array containing the image data from which the relevant regions - will be extracted. - labels (list of int): A list of integers representing the label values to be used for masking. - - Returns: - np.ndarray: A NumPy array containing the elements of `image_data` that correspond to the specified - labels in `label_data`. If no labels are provided, an empty array is returned. - - Raises: - ValueError: If `image_data` and `label_data` do not have the same shape. - - Example: - label_int_dict = {"liver": [1], "kidney": [5, 14]} - masked_data = get_masked_data(label_data, image_data, label_int_dict["kidney"]) - """ - - # Check if the shapes of image_data and label_data match - if image_data.shape != label_data.shape: - raise ValueError( - f"Shape mismatch: image_data has shape {image_data.shape}, " - f"but label_data has shape {label_data.shape}. They must be the same." - ) - - if not labels: - return np.array([]) # Return an empty array if no labels are provided - - labels = list(set(labels)) # remove duplicate items - - # Optimize performance based on the number of labels - num_label_acceleration_thresh = 3 - if len(labels) >= num_label_acceleration_thresh: - # if many labels, np.isin is faster - mask = np.isin(label_data, labels) - else: - # Use logical OR to combine masks if the number of labels is small - mask = np.zeros_like(label_data, dtype=bool) - for label in labels: - mask = np.logical_or(mask, label_data == label) - - # Retrieve the masked data - masked_data = image_data[mask.astype(bool)] - - return masked_data - - -def is_outlier(statistics, image_data, label_data, label_int_dict): - """ - Perform a quality check on the generated image by comparing its statistics with precomputed thresholds. - - Args: - statistics (dict): Dictionary containing precomputed statistics including mean +/- 3sigma ranges. - image_data (np.ndarray): The image data to be checked, typically a 3D NumPy array. - label_data (np.ndarray): The label data corresponding to the image, used for masking regions of interest. - label_int_dict (dict): Dictionary mapping label names to their corresponding integer lists. - e.g., label_int_dict = {"liver": [1], "kidney": [5, 14]} - - Returns: - dict: A dictionary with labels as keys, each containing the quality check result, - including whether it's an outlier, the median value, and the thresholds used. - If no data is found for a label, the median value will be `None` and `is_outlier` will be `False`. - - Example: - # Example input data - statistics = { - "liver": { - "sigma_6_low": -21.596463547885904, - "sigma_6_high": 156.27881534763367 - }, - "kidney": { - "sigma_6_low": -15.0, - "sigma_6_high": 120.0 - } - } - label_int_dict = { - "liver": [1], - "kidney": [5, 14] - } - image_data = np.random.rand(100, 100, 100) # Replace with actual image data - label_data = np.zeros((100, 100, 100)) # Replace with actual label data - label_data[40:60, 40:60, 40:60] = 1 # Example region for liver - label_data[70:90, 70:90, 70:90] = 5 # Example region for kidney - result = is_outlier(statistics, image_data, label_data, label_int_dict) - """ - outlier_results = {} - - for label_name, stats in statistics.items(): - # Get the thresholds from the statistics - low_thresh = min( - stats["sigma_6_low"], stats["percentile_0_5"] - ) # or "sigma_12_low" depending on your needs - high_thresh = max( - stats["sigma_6_high"], stats["percentile_99_5"] - ) # or "sigma_12_high" depending on your needs - - if label_name == "bone": - high_thresh = 1000.0 - - # Retrieve the corresponding label integers - labels = label_int_dict.get(label_name, []) - masked_data = get_masked_data(label_data, image_data, labels) - masked_data = masked_data[~np.isnan(masked_data)] - - if len(masked_data) == 0 or masked_data.size == 0: - outlier_results[label_name] = { - "is_outlier": False, - "median_value": None, - "low_thresh": low_thresh, - "high_thresh": high_thresh, - } - continue - - # Compute the median of the masked region - median_value = np.nanmedian(masked_data) - - if np.isnan(median_value): - median_value = None - is_outlier = False - else: - # Determine if the median value is an outlier - is_outlier = median_value < low_thresh or median_value > high_thresh - - outlier_results[label_name] = { - "is_outlier": is_outlier, - "median_value": median_value, - "low_thresh": low_thresh, - "high_thresh": high_thresh, - } - - return outlier_results diff --git a/itrialspace/src/itrialspace/synthesis/scripts/rectified_flow.py b/itrialspace/src/itrialspace/synthesis/scripts/rectified_flow.py deleted file mode 100644 index cf402ae222a39c8b943dd76b79387fad212bd9fa..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/rectified_flow.py +++ /dev/null @@ -1,337 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/hpcaitech/Open-Sora/blob/main/opensora/schedulers/rf/rectified_flow.py -# which has the following license: -# https://github.com/hpcaitech/Open-Sora/blob/main/LICENSE -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - -from __future__ import annotations - -from typing import Union - -import numpy as np -import torch -from monai.utils import StrEnum -from torch.distributions import LogisticNormal - -from .ddpm import DDPMPredictionType -from .scheduler import Scheduler - - -class RFlowPredictionType(StrEnum): - """ - Set of valid prediction type names for the RFlow scheduler's `prediction_type` argument. - - v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf - """ - - V_PREDICTION = DDPMPredictionType.V_PREDICTION - - -def timestep_transform( - t, - input_img_size_numel, - base_img_size_numel=32 * 32 * 32, - scale=1.0, - num_train_timesteps=1000, - spatial_dim=3, -): - """ - Applies a transformation to the timestep based on image resolution scaling. - - Args: - t (torch.Tensor): The original timestep(s). - input_img_size_numel (torch.Tensor): The input image's size (H * W * D). - base_img_size_numel (int): reference H*W*D size, usually smaller than input_img_size_numel. - scale (float): Scaling factor for the transformation. - num_train_timesteps (int): Total number of training timesteps. - spatial_dim (int): Number of spatial dimensions in the image. - - Returns: - torch.Tensor: Transformed timestep(s). - """ - t = t / num_train_timesteps - ratio_space = (input_img_size_numel / base_img_size_numel) ** (1.0 / spatial_dim) - - ratio = ratio_space * scale - new_t = ratio * t / (1 + (ratio - 1) * t) - - new_t = new_t * num_train_timesteps - return new_t - - -class RFlowScheduler(Scheduler): - """ - A rectified flow scheduler for guiding the diffusion process in a generative model. - - Supports uniform and logit-normal sampling methods, timestep transformation for - different resolutions, and noise addition during diffusion. - - Args: - num_train_timesteps (int): Total number of training timesteps. - use_discrete_timesteps (bool): Whether to use discrete timesteps. - sample_method (str): Training time step sampling method ('uniform' or 'logit-normal'). - loc (float): Location parameter for logit-normal distribution, used only if sample_method='logit-normal'. - scale (float): Scale parameter for logit-normal distribution, used only if sample_method='logit-normal'. - use_timestep_transform (bool): Whether to apply timestep transformation. - If true, there will be more inference timesteps at early(noisy) stages for larger image volumes. - transform_scale (float): Scaling factor for timestep transformation, used only if use_timestep_transform=True. - steps_offset (int): Offset added to computed timesteps, used only if use_timestep_transform=True. - base_img_size_numel (int): Reference image volume size for scaling, used only if use_timestep_transform=True. - spatial_dim (int): 2 or 3, incidcating 2D or 3D images, used only if use_timestep_transform=True. - - Example: - - .. code-block:: python - - # define a scheduler - noise_scheduler = RFlowScheduler( - num_train_timesteps = 1000, - use_discrete_timesteps = True, - sample_method = 'logit-normal', - use_timestep_transform = True, - base_img_size_numel = 32 * 32 * 32, - spatial_dim = 3 - ) - - # during training - inputs = torch.ones(2,4,64,64,32) - noise = torch.randn_like(inputs) - timesteps = noise_scheduler.sample_timesteps(inputs) - noisy_inputs = noise_scheduler.add_noise(original_samples=inputs, noise=noise, timesteps=timesteps) - predicted_velocity = diffusion_unet( - x=noisy_inputs, - timesteps=timesteps - ) - loss = loss_l1(predicted_velocity, (inputs - noise)) - - # during inference - noisy_inputs = torch.randn(2,4,64,64,32) - input_img_size_numel = torch.prod(torch.tensor(noisy_inputs.shape[-3:]) - noise_scheduler.set_timesteps( - num_inference_steps=30, input_img_size_numel=input_img_size_numel) - ) - all_next_timesteps = torch.cat( - (noise_scheduler.timesteps[1:], torch.tensor([0], dtype=noise_scheduler.timesteps.dtype)) - ) - for t, next_t in tqdm( - zip(noise_scheduler.timesteps, all_next_timesteps), - total=min(len(noise_scheduler.timesteps), len(all_next_timesteps)), - ): - predicted_velocity = diffusion_unet( - x=noisy_inputs, - timesteps=timesteps - ) - noisy_inputs, _ = noise_scheduler.step(predicted_velocity, t, noisy_inputs, next_t) - final_output = noisy_inputs - """ - - def __init__( - self, - num_train_timesteps: int = 1000, - use_discrete_timesteps: bool = True, - sample_method: str = "uniform", - loc: float = 0.0, - scale: float = 1.0, - use_timestep_transform: bool = False, - transform_scale: float = 1.0, - steps_offset: int = 0, - base_img_size_numel: int = 32 * 32 * 32, - spatial_dim: int = 3, - ): - # rectified flow only accepts velocity prediction - self.prediction_type = RFlowPredictionType.V_PREDICTION - - self.num_train_timesteps = num_train_timesteps - self.use_discrete_timesteps = use_discrete_timesteps - self.base_img_size_numel = base_img_size_numel - self.spatial_dim = spatial_dim - - # sample method - if sample_method not in ["uniform", "logit-normal"]: - raise ValueError( - f"sample_method = {sample_method}, which has to be chosen from ['uniform', 'logit-normal']." - ) - self.sample_method = sample_method - if sample_method == "logit-normal": - self.distribution = LogisticNormal(torch.tensor([loc]), torch.tensor([scale])) - self.sample_t = lambda x: self.distribution.sample((x.shape[0],))[:, 0].to(x.device) - - # timestep transform - self.use_timestep_transform = use_timestep_transform - self.transform_scale = transform_scale - self.steps_offset = steps_offset - - def add_noise( - self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor - ) -> torch.Tensor: - """ - Add noise to the original samples. - - Args: - original_samples: original samples - noise: noise to add to samples - timesteps: timesteps tensor with shape of (N,), indicating the timestep to be computed for each sample. - - Returns: - noisy_samples: sample with added noise - """ - timepoints: torch.Tensor = timesteps.float() / self.num_train_timesteps - timepoints = 1 - timepoints # [1,1/1000] - - # expand timepoint to noise shape - if noise.ndim == 5: - timepoints = timepoints[..., None, None, None, None].expand(-1, *noise.shape[1:]) - elif noise.ndim == 4: - timepoints = timepoints[..., None, None, None].expand(-1, *noise.shape[1:]) - else: - raise ValueError( - f"noise tensor has to be 4D or 5D tensor, yet got shape of {noise.shape}" - ) - - noisy_samples: torch.Tensor = timepoints * original_samples + (1 - timepoints) * noise - - return noisy_samples - - def set_timesteps( - self, - num_inference_steps: int, - device: str | torch.device | None = None, - input_img_size_numel: int | None = None, - ) -> None: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. - device: target device to put the data. - input_img_size_numel: int, H*W*D of the image, used with self.use_timestep_transform is True. - """ - if num_inference_steps > self.num_train_timesteps or num_inference_steps < 1: - raise ValueError( - f"`num_inference_steps`: {num_inference_steps} should be at least 1, " - "and cannot be larger than `self.num_train_timesteps`:" - f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" - f" maximal {self.num_train_timesteps} timesteps." - ) - - self.num_inference_steps = num_inference_steps - # prepare timesteps - timesteps = [ - (1.0 - i / self.num_inference_steps) * self.num_train_timesteps - for i in range(self.num_inference_steps) - ] - if self.use_discrete_timesteps: - timesteps = [int(round(t)) for t in timesteps] - if self.use_timestep_transform: - timesteps = [ - timestep_transform( - t, - input_img_size_numel=input_img_size_numel, - base_img_size_numel=self.base_img_size_numel, - num_train_timesteps=self.num_train_timesteps, - spatial_dim=self.spatial_dim, - ) - for t in timesteps - ] - timesteps_np = np.array(timesteps).astype(np.float16) - if self.use_discrete_timesteps: - timesteps_np = timesteps_np.astype(np.int64) - self.timesteps = torch.from_numpy(timesteps_np).to(device) - self.timesteps += self.steps_offset - - def sample_timesteps(self, x_start): - """ - Randomly samples training timesteps using the chosen sampling method. - - Args: - x_start (torch.Tensor): The input tensor for sampling. - - Returns: - torch.Tensor: Sampled timesteps. - """ - if self.sample_method == "uniform": - t = torch.rand((x_start.shape[0],), device=x_start.device) * self.num_train_timesteps - elif self.sample_method == "logit-normal": - t = self.sample_t(x_start) * self.num_train_timesteps - - if self.use_discrete_timesteps: - t = t.long() - - if self.use_timestep_transform: - input_img_size_numel = torch.prod(torch.tensor(x_start.shape[2:])) - t = timestep_transform( - t, - input_img_size_numel=input_img_size_numel, - base_img_size_numel=self.base_img_size_numel, - num_train_timesteps=self.num_train_timesteps, - spatial_dim=len(x_start.shape) - 2, - ) - - return t - - def step( - self, - model_output: torch.Tensor, - timestep: int, - sample: torch.Tensor, - next_timestep: Union[int, None] = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Predicts the next sample in the diffusion process. - - Args: - model_output (torch.Tensor): Output from the trained diffusion model. - timestep (int): Current timestep in the diffusion chain. - sample (torch.Tensor): Current sample in the process. - next_timestep (Union[int, None]): Optional next timestep. - - Returns: - tuple[torch.Tensor, torch.Tensor]: Predicted sample at the next step and additional info. - """ - # Ensure num_inference_steps exists and is a valid integer - if not hasattr(self, "num_inference_steps") or not isinstance( - self.num_inference_steps, int - ): - raise AttributeError( - "num_inference_steps is missing or not an integer in the class." - "Please run self.set_timesteps(num_inference_steps,device,input_img_size_numel) to set it." - ) - - v_pred = model_output - - if next_timestep is not None: - next_timestep = int(next_timestep) - dt: float = ( - float(timestep - next_timestep) / self.num_train_timesteps - ) # Now next_timestep is guaranteed to be int - else: - dt = ( - 1.0 / float(self.num_inference_steps) if self.num_inference_steps > 0 else 0.0 - ) # Avoid division by zero - - pred_post_sample = sample + v_pred * dt - pred_original_sample = sample + v_pred * timestep / self.num_train_timesteps - - return pred_post_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/sample.py b/itrialspace/src/itrialspace/synthesis/scripts/sample.py deleted file mode 100644 index 2a96cdf57de004c1c51ec69544c0a7d30d389479..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/sample.py +++ /dev/null @@ -1,1228 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import gc -import json -import logging -import math -import os -import random -import time -import warnings -from datetime import datetime - -import monai -import torch -from monai.data import MetaTensor -from monai.inferers.inferer import DiffusionInferer, SlidingWindowInferer -from monai.networks.schedulers import DDPMScheduler, RFlowScheduler -from monai.transforms import Compose, SaveImage -from monai.utils import set_determinism -from tqdm import tqdm - -from .augmentation import augmentation -from .find_masks import find_masks -from .quality_check import is_outlier -from .utils import ( - binarize_labels, - dynamic_infer, - general_mask_generation_post_process, - get_body_region_index_from_mask, - remap_labels, -) - - -class ReconModel(torch.nn.Module): - """ - A PyTorch module for reconstructing images from latent representations. - - Attributes: - autoencoder: The autoencoder model used for decoding. - scale_factor: Scaling factor applied to the input before decoding. - """ - - def __init__(self, autoencoder, scale_factor): - super().__init__() - self.autoencoder = autoencoder - self.scale_factor = scale_factor - - def forward(self, z): - """ - Decode the input latent representation to an image. - - Args: - z (torch.Tensor): The input latent representation. - - Returns: - torch.Tensor: The reconstructed image. - """ - recon_pt_nda = self.autoencoder.decode_stage_2_outputs(z / self.scale_factor) - return recon_pt_nda - - -def initialize_noise_latents(latent_shape, device): - """ - Initialize random noise latents for image generation with float16. - - Args: - latent_shape (tuple): The shape of the latent space. - device (torch.device): The device to create the tensor on. - - Returns: - torch.Tensor: Initialized noise latents. - """ - return ( - torch.randn( - [ - 1, - ] - + list(latent_shape) - ) - .half() - .to(device) - ) - - -def ldm_conditional_sample_one_mask( - autoencoder, - diffusion_unet, - noise_scheduler, - scale_factor, - anatomy_size, - device, - latent_shape, - label_dict_remap_json, - num_inference_steps=1000, - autoencoder_sliding_window_infer_size=[96, 96, 96], - autoencoder_sliding_window_infer_overlap=0.6667, -): - """ - Generate a single synthetic mask using a latent diffusion model. - - Args: - autoencoder (nn.Module): The autoencoder model. - diffusion_unet (nn.Module): The diffusion U-Net model. - noise_scheduler: The noise scheduler for the diffusion process. - scale_factor (float): Scaling factor for the latent space. - anatomy_size (torch.Tensor): Tensor specifying the desired anatomy sizes. - device (torch.device): The device to run the computation on. - latent_shape (tuple): The shape of the latent space. - label_dict_remap_json (str): Path to the JSON file for label remapping. - num_inference_steps (int): Number of inference steps for the diffusion process. - autoencoder_sliding_window_infer_size (list, optional): Size of the sliding window for inference. Defaults to [96, 96, 96]. - autoencoder_sliding_window_infer_overlap (float, optional): Overlap ratio for sliding window inference. Defaults to 0.6667. - - Returns: - torch.Tensor: The generated synthetic mask. - """ - recon_model = ReconModel(autoencoder=autoencoder, scale_factor=scale_factor).to(device) - - with torch.no_grad(), torch.amp.autocast("cuda"): - # Generate random noise - latents = initialize_noise_latents(latent_shape, device) - anatomy_size = torch.FloatTensor(anatomy_size).unsqueeze(0).unsqueeze(0).half().to(device) - # synthesize latents - if ( - isinstance(noise_scheduler, DDPMScheduler) - and num_inference_steps < noise_scheduler.num_train_timesteps - ): - warnings.warn( - "**************************************************************\n" - "* WARNING: Mask noise_scheduler is a DDPMScheduler.\n" - "* We expect num_inference_steps = noise_scheduler.num_train_timesteps" - f" = {noise_scheduler.num_train_timesteps}.\n" - f"* Yet got num_inference_steps = {num_inference_steps}.\n" - "* The generated image quality is not guaranteed.\n" - "**************************************************************" - ) - - noise_scheduler.set_timesteps(num_inference_steps=num_inference_steps) - # mask generator is DDPM - inferer_ddpm = DiffusionInferer(noise_scheduler) - latents = inferer_ddpm.sample( - input_noise=latents, - diffusion_model=diffusion_unet, - scheduler=noise_scheduler, - verbose=True, - conditioning=anatomy_size.to(device), - ) - - inferer = SlidingWindowInferer( - roi_size=autoencoder_sliding_window_infer_size, - sw_batch_size=1, - progress=True, - mode="gaussian", - overlap=autoencoder_sliding_window_infer_overlap, - sw_device=device, - device=torch.device("cpu"), - ) - synthetic_mask = dynamic_infer(inferer, recon_model, latents) - synthetic_mask = torch.softmax(synthetic_mask, dim=1) - synthetic_mask = torch.argmax(synthetic_mask, dim=1, keepdim=True) - # mapping raw index to 132 labels - synthetic_mask = remap_labels(synthetic_mask, label_dict_remap_json) - - ###### post process ##### - data = synthetic_mask.squeeze().cpu().detach().numpy() - - labels = [23, 24, 26, 27, 128] - target_tumor_label = None - for index, size in enumerate(anatomy_size[0, 0, 5:10]): - if size.item() != -1.0: - target_tumor_label = labels[index] - - logging.info(f"target_tumor_label for postprocess:{target_tumor_label}") - data = general_mask_generation_post_process( - data, target_tumor_label=target_tumor_label, device=device - ) - synthetic_mask = torch.from_numpy(data).unsqueeze(0).unsqueeze(0).to(device) - - return synthetic_mask - - -def ldm_conditional_sample_one_image( - autoencoder, - diffusion_unet, - controlnet, - noise_scheduler, - scale_factor, - device, - combine_label_or, - spacing_tensor, - latent_shape, - output_size, - noise_factor, - top_region_index_tensor=None, - bottom_region_index_tensor=None, - modality_tensor=None, - num_inference_steps=1000, - autoencoder_sliding_window_infer_size=[96, 96, 96], - autoencoder_sliding_window_infer_overlap=0.6667, -): - """ - Generate a single synthetic image using a latent diffusion model with controlnet. - - Args: - autoencoder (nn.Module): The autoencoder model. - diffusion_unet (nn.Module): The diffusion U-Net model. - controlnet (nn.Module): The controlnet model. - noise_scheduler: The noise scheduler for the diffusion process. - scale_factor (float): Scaling factor for the latent space. - device (torch.device): The device to run the computation on. - combine_label_or (torch.Tensor): The combined label tensor. - spacing_tensor (torch.Tensor): Tensor specifying the spacing. - latent_shape (tuple): The shape of the latent space. - output_size (tuple): The desired output size of the image. - noise_factor (float): Factor to scale the initial noise. - top_region_index_tensor (torch.Tensor): Tensor specifying the top region index. Defaults to None. - bottom_region_index_tensor (torch.Tensor): Tensor specifying the bottom region index. Defaults to None. - modality_tensor (torch.Tensor): Int Tensor specifying the modality. - num_inference_steps (int): Number of inference steps for the diffusion process. - autoencoder_sliding_window_infer_size (list, optional): Size of the sliding window for inference. Defaults to [96, 96, 96]. - autoencoder_sliding_window_infer_overlap (float, optional): Overlap ratio for sliding window inference. Defaults to 0.6667. - - Returns: - tuple: A tuple containing the synthetic image and its corresponding label. - """ - # CT image intensity range - a_min = -1000 - a_max = 1000 - # autoencoder output intensity range - b_min = 0.0 - b_max = 1 - - include_body_region = diffusion_unet.include_top_region_index_input - include_modality = diffusion_unet.num_class_embeds is not None - - recon_model = ReconModel(autoencoder=autoencoder, scale_factor=scale_factor).to(device) - - with torch.no_grad(), torch.amp.autocast("cuda"): - logging.info("---- Start generating latent features... ----") - start_time = time.time() - # generate segmentation mask - combine_label = combine_label_or.to(device) - if ( - output_size[0] != combine_label.shape[2] - or output_size[1] != combine_label.shape[3] - or output_size[2] != combine_label.shape[4] - ): - logging.info( - "output_size is not a desired value. Need to interpolate the mask to match with output_size. The result image will be very low quality." - ) - combine_label = torch.nn.functional.interpolate( - combine_label, size=output_size, mode="nearest" - ) - - controlnet_cond_vis = binarize_labels(combine_label.as_tensor().long()).half() - - # Generate random noise - latents = initialize_noise_latents(latent_shape, device) * noise_factor - - # synthesize latents - if isinstance(noise_scheduler, RFlowScheduler): - noise_scheduler.set_timesteps( - num_inference_steps=num_inference_steps, - input_img_size_numel=torch.prod(torch.tensor(latents.shape[2:])), - ) - else: - noise_scheduler.set_timesteps(num_inference_steps=num_inference_steps) - - if ( - isinstance(noise_scheduler, DDPMScheduler) - and num_inference_steps < noise_scheduler.num_train_timesteps - ): - warnings.warn( - "**************************************************************\n" - "* WARNING: Image noise_scheduler is a DDPMScheduler.\n" - "* We expect num_inference_steps = noise_scheduler.num_train_timesteps" - f" = {noise_scheduler.num_train_timesteps}.\n" - f"* Yet got num_inference_steps = {num_inference_steps}.\n" - "* The generated image quality is not guaranteed.\n" - "**************************************************************" - ) - - all_timesteps = noise_scheduler.timesteps - all_next_timesteps = torch.cat( - (all_timesteps[1:], torch.tensor([0], dtype=all_timesteps.dtype)) - ) - progress_bar = tqdm( - zip(all_timesteps, all_next_timesteps), - total=min(len(all_timesteps), len(all_next_timesteps)), - ) - for t, next_t in progress_bar: - # get controlnet output - # Create a dictionary to store the inputs - controlnet_inputs = { - "x": latents, - "timesteps": torch.Tensor((t,)).to(device), - "controlnet_cond": controlnet_cond_vis, - } - if include_modality: - controlnet_inputs.update( - { - "class_labels": modality_tensor, - } - ) - down_block_res_samples, mid_block_res_sample = controlnet(**controlnet_inputs) - - # get diffusion network output - # Create a dictionary to store the inputs - unet_inputs = { - "x": latents, - "timesteps": torch.Tensor((t,)).to(device), - "spacing_tensor": spacing_tensor, - "down_block_additional_residuals": down_block_res_samples, - "mid_block_additional_residual": mid_block_res_sample, - } - # Add extra arguments if include_body_region is True - if include_body_region: - unet_inputs.update( - { - "top_region_index_tensor": top_region_index_tensor, - "bottom_region_index_tensor": bottom_region_index_tensor, - } - ) - if include_modality: - unet_inputs.update( - { - "class_labels": modality_tensor, - } - ) - model_output = diffusion_unet(**unet_inputs) - - if not isinstance(noise_scheduler, RFlowScheduler): - latents, _ = noise_scheduler.step(model_output, t, latents) # type: ignore - else: - latents, _ = noise_scheduler.step(model_output, t, latents, next_t) # type: ignore - end_time = time.time() - logging.info( - f"---- DM/ControlNet Latent features generation time: {end_time - start_time} seconds ----" - ) - del ( - unet_inputs, - controlnet_inputs, - model_output, - controlnet_cond_vis, - down_block_res_samples, - mid_block_res_sample, - ) - gc.collect() - torch.cuda.empty_cache() - - # decode latents to synthesized images - logging.info("---- Start decoding latent features into images... ----") - start_time = time.time() - - inferer = SlidingWindowInferer( - roi_size=autoencoder_sliding_window_infer_size, - sw_batch_size=1, - progress=True, - mode="gaussian", - overlap=autoencoder_sliding_window_infer_overlap, - sw_device=device, - device=torch.device("cpu"), - ) - synthetic_images = dynamic_infer(inferer, recon_model, latents) - synthetic_images = torch.clip(synthetic_images, b_min, b_max).cpu() - end_time = time.time() - logging.info(f"---- Image VAE decoding time: {end_time - start_time} seconds ----") - - ## post processing: - # project output to [0, 1] - synthetic_images = (synthetic_images - b_min) / (b_max - b_min) - # project output to [-1000, 1000] - synthetic_images = synthetic_images * (a_max - a_min) + a_min - # regularize background intensities - synthetic_images = crop_img_body_mask(synthetic_images, combine_label) - torch.cuda.empty_cache() - - return synthetic_images, combine_label - - -def filter_mask_with_organs(combine_label, anatomy_list): - """ - Filter a mask to only include specified organs. - - Args: - combine_label (torch.Tensor): The input mask. - anatomy_list (list): List of organ labels to keep. - - Returns: - torch.Tensor: The filtered mask. - """ - # final output mask file has shape of output_size, contains labels in anatomy_list - # it is already interpolated to target size - combine_label = combine_label.long() - # filter out the organs that are not in anatomy_list - for i in range(len(anatomy_list)): - organ = anatomy_list[i] - # replace it with a negative value so it will get mixed - combine_label[combine_label == organ] = -(i + 1) - # zero-out voxels with value not in anatomy_list - combine_label[combine_label > 0] = 0 - # output positive values - combine_label = -combine_label - return combine_label - - -def crop_img_body_mask(synthetic_images, combine_label): - """ - Crop the synthetic image using a body mask. - - Args: - synthetic_images (torch.Tensor): The synthetic images. - combine_label (torch.Tensor): The body mask. - - Returns: - torch.Tensor: The cropped synthetic images. - """ - synthetic_images[combine_label == 0] = -1000 - return synthetic_images - - -def check_input( - body_region, - anatomy_list, - label_dict_json, - output_size, - spacing, - controllable_anatomy_size=[("pancreas", 0.5)], -): - """ - Validate input parameters for image generation. - - Args: - body_region (list): List of body regions. - anatomy_list (list): List of anatomical structures. - label_dict_json (str): Path to the label dictionary JSON file. - output_size (tuple): Desired output size of the image. - spacing (tuple): Desired voxel spacing. - controllable_anatomy_size (list): List of tuples specifying controllable anatomy sizes. - - Raises: - ValueError: If any input parameter is invalid. - """ - # check output_size and spacing format - if output_size[0] != output_size[1]: - raise ValueError( - f"The first two components of output_size need to be equal, yet got {output_size}." - ) - if (output_size[0] not in [256, 384, 512]) or ( - output_size[2] not in [128, 256, 384, 512, 640, 768] - ): - raise ValueError( - f"The output_size[0] have to be chosen from [256, 384, 512], and output_size[2] have to be chosen from [128, 256, 384, 512, 640, 768], yet got {output_size}." - ) - - if spacing[0] != spacing[1]: - raise ValueError( - f"The first two components of spacing need to be equal, yet got {spacing}." - ) - if spacing[0] < 0.5 or spacing[0] > 3.0 or spacing[2] < 0.5 or spacing[2] > 5.0: - raise ValueError( - f"spacing[0] have to be between 0.5 and 3.0 mm, spacing[2] have to be between 0.5 and 5.0 mm, yet got {spacing}." - ) - - if output_size[0] * spacing[0] < 256: - FOV = [output_size[axis] * spacing[axis] for axis in range(3)] - raise ValueError( - f"`'spacing'({spacing}mm) and 'output_size'({output_size}) together decide the output field of view (FOV). The FOV will be {FOV}mm. We recommend the FOV in x and y axis to be at least 256mm for head, and at least 384mm for other body regions like abdomen. There is no such restriction for z-axis." - ) - - if controllable_anatomy_size == None: - logging.info("`controllable_anatomy_size` is not provided.") - return - - # check controllable_anatomy_size format - if len(controllable_anatomy_size) > 10: - raise ValueError( - f"The length of list controllable_anatomy_size has to be less than 10. Yet got length equal to {len(controllable_anatomy_size)}." - ) - available_controllable_organ = [ - "liver", - "gallbladder", - "stomach", - "pancreas", - "colon", - ] - available_controllable_tumor = [ - "hepatic tumor", - "bone lesion", - "lung tumor", - "colon cancer primaries", - "pancreatic tumor", - ] - available_controllable_anatomy = available_controllable_organ + available_controllable_tumor - controllable_tumor = [] - controllable_organ = [] - for controllable_anatomy_size_pair in controllable_anatomy_size: - if controllable_anatomy_size_pair[0] not in available_controllable_anatomy: - raise ValueError( - f"The controllable_anatomy have to be chosen from {available_controllable_anatomy}, yet got {controllable_anatomy_size_pair[0]}." - ) - if controllable_anatomy_size_pair[0] in available_controllable_tumor: - controllable_tumor += [controllable_anatomy_size_pair[0]] - if controllable_anatomy_size_pair[0] in available_controllable_organ: - controllable_organ += [controllable_anatomy_size_pair[0]] - if controllable_anatomy_size_pair[1] == -1: - continue - if controllable_anatomy_size_pair[1] < 0 or controllable_anatomy_size_pair[1] > 1.0: - raise ValueError( - f"The controllable size scale have to be between 0 and 1,0, or equal to -1, yet got {controllable_anatomy_size_pair[1]}." - ) - if len(controllable_tumor + controllable_organ) != len( - list(set(controllable_tumor + controllable_organ)) - ): - raise ValueError( - f"Please do not repeat controllable_anatomy. Got {controllable_tumor + controllable_organ}." - ) - if len(controllable_tumor) > 1: - raise ValueError(f"Only one controllable tumor is supported. Yet got {controllable_tumor}.") - - if len(controllable_anatomy_size) > 0: - logging.info( - f"`controllable_anatomy_size` is not empty.\nWe will ignore `body_region` and `anatomy_list` and synthesize based on `controllable_anatomy_size`: ({controllable_anatomy_size})." - ) - else: - logging.info( - f"`controllable_anatomy_size` is empty.\nWe will synthesize based on `body_region`: ({body_region}) and `anatomy_list`: ({anatomy_list})." - ) - # check body_region format - available_body_region = [ - "head", - "chest", - "thorax", - "abdomen", - "pelvis", - "lower", - ] - for region in body_region: - if region not in available_body_region: - raise ValueError( - f"The components in body_region have to be chosen from {available_body_region}, yet got {region}." - ) - - # check anatomy_list format - with open(label_dict_json) as f: - label_dict = json.load(f) - for anatomy in anatomy_list: - if anatomy not in label_dict.keys(): - raise ValueError( - f"The components in anatomy_list have to be chosen from {label_dict.keys()}, yet got {anatomy}." - ) - logging.info( - f"The generate results will have voxel size to be {spacing}mm, volume size to be {output_size}." - ) - - return - - -class LDMSampler: - """ - A sampler class for generating synthetic medical images and masks using latent diffusion models. - - Attributes: - Various attributes related to model configuration, input parameters, and generation settings. - """ - - def __init__( - self, - body_region, - anatomy_list, - all_mask_files_json, - all_anatomy_size_condtions_json, - all_mask_files_base_dir, - label_dict_json, - label_dict_remap_json, - autoencoder, - diffusion_unet, - controlnet, - noise_scheduler, - scale_factor, - mask_generation_autoencoder, - mask_generation_diffusion_unet, - mask_generation_scale_factor, - mask_generation_noise_scheduler, - device, - latent_shape, - mask_generation_latent_shape, - output_size, - output_dir, - controllable_anatomy_size, - image_output_ext=".nii.gz", - label_output_ext=".nii.gz", - real_img_median_statistics="./configs/image_median_statistics.json", - spacing=[1, 1, 1], - modality=1, - num_inference_steps=None, - mask_generation_num_inference_steps=None, - random_seed=None, - autoencoder_sliding_window_infer_size=[96, 96, 96], - autoencoder_sliding_window_infer_overlap=0.6667, - ) -> None: - """ - Initialize the LDMSampler with various parameters and models. - - Args: - Various parameters related to model configuration, input settings, and output specifications. - """ - self.random_seed = random_seed - if random_seed is not None: - set_determinism(seed=random_seed) - - with open(label_dict_json, "r") as f: - label_dict = json.load(f) - self.all_anatomy_size_condtions_json = all_anatomy_size_condtions_json - - # intialize variables - self.body_region = body_region - self.anatomy_list = [label_dict[organ] for organ in anatomy_list] - self.all_mask_files_json = all_mask_files_json - self.data_root = all_mask_files_base_dir - self.label_dict_remap_json = label_dict_remap_json - self.autoencoder = autoencoder - self.diffusion_unet = diffusion_unet - self.controlnet = controlnet - self.noise_scheduler = noise_scheduler - self.scale_factor = scale_factor - self.mask_generation_autoencoder = mask_generation_autoencoder - self.mask_generation_diffusion_unet = mask_generation_diffusion_unet - self.mask_generation_scale_factor = mask_generation_scale_factor - self.mask_generation_noise_scheduler = mask_generation_noise_scheduler - self.device = device - self.latent_shape = latent_shape - self.mask_generation_latent_shape = mask_generation_latent_shape - self.output_size = output_size - self.output_dir = output_dir - self.noise_factor = 1.0 - self.controllable_anatomy_size = controllable_anatomy_size - if len(self.controllable_anatomy_size): - logging.info("controllable_anatomy_size is given, mask generation is triggered!") - # overwrite the anatomy_list by given organs in self.controllable_anatomy_size - self.anatomy_list = [ - label_dict[organ_and_size[0]] for organ_and_size in self.controllable_anatomy_size - ] - self.image_output_ext = image_output_ext - self.label_output_ext = label_output_ext - # Set the default value for number of inference steps to 1000 - self.num_inference_steps = num_inference_steps if num_inference_steps is not None else 1000 - self.mask_generation_num_inference_steps = ( - mask_generation_num_inference_steps - if mask_generation_num_inference_steps is not None - else 1000 - ) - - if any(size % 16 != 0 for size in autoencoder_sliding_window_infer_size): - raise ValueError( - f"autoencoder_sliding_window_infer_size must be divisible by 16.\n Got {autoencoder_sliding_window_infer_size}" - ) - if not (0 <= autoencoder_sliding_window_infer_overlap <= 1): - raise ValueError( - f"Value of autoencoder_sliding_window_infer_overlap must be between 0 and 1.\n Got {autoencoder_sliding_window_infer_overlap}" - ) - self.autoencoder_sliding_window_infer_size = autoencoder_sliding_window_infer_size - self.autoencoder_sliding_window_infer_overlap = autoencoder_sliding_window_infer_overlap - - # quality check args - self.max_try_time = 2 # if not pass quality check, will try self.max_try_time times - with open(real_img_median_statistics, "r") as json_file: - self.median_statistics = json.load(json_file) - self.label_int_dict = { - "liver": [1], - "spleen": [3], - "pancreas": [4], - "kidney": [5, 14], - "lung": [28, 29, 30, 31, 31], - "brain": [22], - "hepatic tumor": [26], - "bone lesion": [128], - "lung tumor": [23], - "colon cancer primaries": [27], - "pancreatic tumor": [24], - "bone": list(range(33, 57)) + list(range(63, 98)) + [120, 122, 127], - } - - # networks - self.autoencoder.eval() - self.diffusion_unet.eval() - self.controlnet.eval() - self.mask_generation_autoencoder.eval() - self.mask_generation_diffusion_unet.eval() - - self.spacing = spacing - self.modality_tensor = modality * torch.ones((1,), dtype=torch.long).to(device) - self.include_body_region = self.diffusion_unet.include_top_region_index_input - self.include_modality = self.diffusion_unet.num_class_embeds is not None - - val_transforms_list = [ - monai.transforms.LoadImaged(keys=["pseudo_label"]), - monai.transforms.EnsureChannelFirstd(keys=["pseudo_label"]), - monai.transforms.Orientationd(keys=["pseudo_label"], axcodes="RAS"), - monai.transforms.EnsureTyped(keys=["pseudo_label"], dtype=torch.uint8), - monai.transforms.Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), - monai.transforms.Lambdad(keys="spacing", func=lambda x: x * 1e2), - ] - if self.include_body_region: - val_transforms_list += [ - monai.transforms.Lambdad( - keys="top_region_index", func=lambda x: torch.FloatTensor(x) - ), - monai.transforms.Lambdad( - keys="bottom_region_index", func=lambda x: torch.FloatTensor(x) - ), - monai.transforms.Lambdad(keys="top_region_index", func=lambda x: x * 1e2), - monai.transforms.Lambdad(keys="bottom_region_index", func=lambda x: x * 1e2), - ] - - self.val_transforms = Compose(val_transforms_list) - logging.info("LDM sampler initialized.") - - def sample_multiple_images(self, num_img): - """ - Generate multiple synthetic images and masks. - - Args: - num_img (int): Number of images to generate. - """ - modality_tensor = self.modality_tensor - output_filenames = [] - if len(self.controllable_anatomy_size) > 0: - # we will use mask generation instead of finding candidate masks - # create a dummy selected_mask_files for placeholder - selected_mask_files = list(range(num_img)) - # prerpare organ size conditions - anatomy_size_condtion = self.prepare_anatomy_size_condtion( - self.controllable_anatomy_size - ) - else: - need_resample = False - # find candidate mask and save to candidate_mask_files - candidate_mask_files = find_masks( - self.body_region, - self.anatomy_list, - self.spacing, - self.output_size, - True, - self.all_mask_files_json, - self.data_root, - ) - if len(candidate_mask_files) < num_img: - # if we cannot find enough masks based on the exact match of anatomy list, spacing, and output size, - # then we will try to find the closest mask in terms of spacing, and output size. - logging.info("Resample mask file to get desired output size and spacing") - candidate_mask_files = self.find_closest_masks(num_img) - need_resample = True - - selected_mask_files = self.select_mask(candidate_mask_files, num_img) - logging.info(f"Images will be generated based on {selected_mask_files}.") - if len(selected_mask_files) < num_img: - raise ValueError( - ( - f"len(selected_mask_files) ({len(selected_mask_files)}) < num_img ({num_img}). " - "This should not happen. Please revisit function select_mask(self, candidate_mask_files, num_img)." - ) - ) - - num_generated_img = 0 - for index_s in range(len(selected_mask_files)): - item = selected_mask_files[index_s] - if num_generated_img >= num_img: - break - logging.info("---- Start preparing masks... ----") - start_time = time.time() - if len(self.controllable_anatomy_size) > 0: - # generate a synthetic mask - ( - combine_label_or, - top_region_index_tensor, - bottom_region_index_tensor, - spacing_tensor, - ) = self.prepare_one_mask_and_meta_info(anatomy_size_condtion) - else: - # read in mask file - mask_file = item["mask_file"] - if_aug = item["if_aug"] - ( - combine_label_or, - top_region_index_tensor, - bottom_region_index_tensor, - spacing_tensor, - ) = self.read_mask_information(mask_file) - if need_resample: - combine_label_or = self.ensure_output_size_and_spacing(combine_label_or) - # mask augmentation - if if_aug: - combine_label_or = augmentation( - combine_label_or, self.output_size, self.random_seed - ) - end_time = time.time() - logging.info(f"---- Mask preparation time: {end_time - start_time} seconds ----") - torch.cuda.empty_cache() - # generate image/label pairs - to_generate = True - try_time = 0 - # start generation - synthetic_images, synthetic_labels = self.sample_one_pair( - combine_label_or, - top_region_index_tensor, - bottom_region_index_tensor, - spacing_tensor, - modality_tensor, - ) - # synthetic image quality check - pass_quality_check = self.quality_check( - synthetic_images.cpu().detach().numpy(), combine_label_or.cpu().detach().numpy() - ) - print(num_img - num_generated_img, (len(selected_mask_files) - index_s)) - if pass_quality_check or (num_img - num_generated_img) >= ( - len(selected_mask_files) - index_s - ): - if not pass_quality_check: - logging.info( - "Generated image/label pair did not pass quality check, but will still save them. " - "Please consider changing spacing and output_size to facilitate a more realistic setting." - ) - num_generated_img = num_generated_img + 1 - # save image/label pairs - output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") - synthetic_labels.meta["filename_or_obj"] = "sample.nii.gz" - synthetic_images = MetaTensor(synthetic_images, meta=synthetic_labels.meta) - img_saver = SaveImage( - output_dir=self.output_dir, - output_postfix=output_postfix + "_image", - output_ext=self.image_output_ext, - separate_folder=False, - ) - img_saver(synthetic_images[0]) - synthetic_images_filename = os.path.join( - self.output_dir, "sample_" + output_postfix + "_image" + self.image_output_ext - ) - # filter out the organs that are not in anatomy_list - synthetic_labels = filter_mask_with_organs(synthetic_labels, self.anatomy_list) - label_saver = SaveImage( - output_dir=self.output_dir, - output_postfix=output_postfix + "_label", - output_ext=self.label_output_ext, - separate_folder=False, - ) - label_saver(synthetic_labels[0]) - synthetic_labels_filename = os.path.join( - self.output_dir, "sample_" + output_postfix + "_label" + self.label_output_ext - ) - output_filenames.append([synthetic_images_filename, synthetic_labels_filename]) - to_generate = False - else: - logging.info( - "Generated image/label pair did not pass quality check, will re-generate another pair." - ) - return output_filenames - - def select_mask(self, candidate_mask_files, num_img): - """ - Select mask files for image generation. - - Args: - candidate_mask_files (list): List of candidate mask files. - num_img (int): Number of images to generate. - - Returns: - list: Selected mask files with augmentation flags. - """ - selected_mask_files = [] - random.shuffle(candidate_mask_files) - - for n in range(len(candidate_mask_files)): - mask_file = candidate_mask_files[n % len(candidate_mask_files)] - selected_mask_files.append({"mask_file": mask_file, "if_aug": True}) - return selected_mask_files - - def sample_one_pair( - self, - combine_label_or_aug, - top_region_index_tensor, - bottom_region_index_tensor, - spacing_tensor, - modality_tensor, - ): - """ - Generate a single pair of synthetic image and mask. - - Args: - combine_label_or_aug (torch.Tensor): Combined label tensor or augmented label. - top_region_index_tensor (torch.Tensor): Tensor specifying the top region index. - bottom_region_index_tensor (torch.Tensor): Tensor specifying the bottom region index. - spacing_tensor (torch.Tensor): Tensor specifying the spacing. - modality_tensor (torch.Tensor): Int Tensor specifying the modality. - - Returns: - tuple: A tuple containing the synthetic image and its corresponding label. - """ - # generate image/label pairs - synthetic_images, synthetic_labels = ldm_conditional_sample_one_image( - autoencoder=self.autoencoder, - diffusion_unet=self.diffusion_unet, - controlnet=self.controlnet, - noise_scheduler=self.noise_scheduler, - scale_factor=self.scale_factor, - device=self.device, - combine_label_or=combine_label_or_aug, - top_region_index_tensor=top_region_index_tensor, - bottom_region_index_tensor=bottom_region_index_tensor, - spacing_tensor=spacing_tensor, - modality_tensor=modality_tensor, - latent_shape=self.latent_shape, - output_size=self.output_size, - noise_factor=self.noise_factor, - num_inference_steps=self.num_inference_steps, - autoencoder_sliding_window_infer_size=self.autoencoder_sliding_window_infer_size, - autoencoder_sliding_window_infer_overlap=self.autoencoder_sliding_window_infer_overlap, - ) - return synthetic_images, synthetic_labels - - def prepare_anatomy_size_condtion( - self, - controllable_anatomy_size, - ): - """ - Prepare anatomy size conditions for mask generation. - - Args: - controllable_anatomy_size (list): List of tuples specifying controllable anatomy sizes. - - Returns: - list: Prepared anatomy size conditions. - """ - anatomy_size_idx = { - "gallbladder": 0, - "liver": 1, - "stomach": 2, - "pancreas": 3, - "colon": 4, - "lung tumor": 5, - "pancreatic tumor": 6, - "hepatic tumor": 7, - "colon cancer primaries": 8, - "bone lesion": 9, - } - provide_anatomy_size = [None for _ in range(10)] - logging.info(f"controllable_anatomy_size: {controllable_anatomy_size}") - for element in controllable_anatomy_size: - anatomy_name, anatomy_size = element - provide_anatomy_size[anatomy_size_idx[anatomy_name]] = anatomy_size - - with open(self.all_anatomy_size_condtions_json, "r") as f: - all_anatomy_size_condtions = json.load(f) - - # loop through the database and find closest combinations - candidate_list = [] - for anatomy_size in all_anatomy_size_condtions: - size = anatomy_size["organ_size"] - diff = 0 - for db_size, provide_size in zip(size, provide_anatomy_size): - if provide_size is None: - continue - diff += abs(provide_size - db_size) - candidate_list.append((size, diff)) - candidate_condition = sorted(candidate_list, key=lambda x: x[1])[0][0] - - # overwrite the anatomy size provided by users - for element in controllable_anatomy_size: - anatomy_name, anatomy_size = element - candidate_condition[anatomy_size_idx[anatomy_name]] = anatomy_size - - return candidate_condition - - def prepare_one_mask_and_meta_info(self, anatomy_size_condtion): - """ - Prepare a single mask and its associated meta information. - - Args: - anatomy_size_condtion (list): Anatomy size conditions. - - Returns: - tuple: A tuple containing the prepared mask and associated tensors. - """ - combine_label_or = self.sample_one_mask(anatomy_size=anatomy_size_condtion) - # TODO: current mask generation model only can generate 256^3 volumes with 1.5 mm spacing. - affine = torch.zeros((4, 4)) - affine[0, 0] = 1.5 - affine[1, 1] = 1.5 - affine[2, 2] = 1.5 - affine[3, 3] = 1.0 # dummy - combine_label_or = MetaTensor(combine_label_or, affine=affine) - combine_label_or = self.ensure_output_size_and_spacing(combine_label_or) - - top_region_index, bottom_region_index = get_body_region_index_from_mask(combine_label_or) - - spacing_tensor = torch.FloatTensor(self.spacing).unsqueeze(0).half().to(self.device) * 1e2 - top_region_index_tensor = ( - torch.FloatTensor(top_region_index).unsqueeze(0).half().to(self.device) * 1e2 - ) - bottom_region_index_tensor = ( - torch.FloatTensor(bottom_region_index).unsqueeze(0).half().to(self.device) * 1e2 - ) - - return combine_label_or, top_region_index_tensor, bottom_region_index_tensor, spacing_tensor - - def sample_one_mask(self, anatomy_size): - """ - Generate a single synthetic mask. - - Args: - anatomy_size (list): Anatomy size specifications. - - Returns: - torch.Tensor: The generated synthetic mask. - """ - # generate one synthetic mask - synthetic_mask = ldm_conditional_sample_one_mask( - self.mask_generation_autoencoder, - self.mask_generation_diffusion_unet, - self.mask_generation_noise_scheduler, - self.mask_generation_scale_factor, - anatomy_size, - self.device, - self.mask_generation_latent_shape, - label_dict_remap_json=self.label_dict_remap_json, - num_inference_steps=self.mask_generation_num_inference_steps, - autoencoder_sliding_window_infer_size=self.autoencoder_sliding_window_infer_size, - autoencoder_sliding_window_infer_overlap=self.autoencoder_sliding_window_infer_overlap, - ) - return synthetic_mask - - def ensure_output_size_and_spacing(self, labels, check_contains_target_labels=True): - """ - Ensure the output mask has the correct size and spacing. - - Args: - labels (torch.Tensor): Input label tensor. - check_contains_target_labels (bool): Whether to check if the resampled mask contains target labels. - - Returns: - torch.Tensor: Resampled label tensor. - - Raises: - ValueError: If the resampled mask doesn't contain required class labels. - """ - current_spacing = [labels.affine[0, 0], labels.affine[1, 1], labels.affine[2, 2]] - current_shape = list(labels.squeeze().shape) - - need_resample = False - # check spacing - for i, j in zip(current_spacing, self.spacing): - if i != j: - need_resample = True - # check output size - for i, j in zip(current_shape, self.output_size): - if i != j: - need_resample = True - # resample to target size and spacing - if need_resample: - logging.info("Resampling mask to target shape and spacing") - logging.info(f"Resize Spacing: {current_spacing} -> {self.spacing}") - logging.info(f"Output size: {current_shape} -> {self.output_size}") - spacing = monai.transforms.Spacing(pixdim=tuple(self.spacing), mode="nearest") - pad_crop = monai.transforms.ResizeWithPadOrCrop(spatial_size=tuple(self.output_size)) - labels = pad_crop(spacing(labels.squeeze(0))).unsqueeze(0).to(labels.dtype) - - contained_labels = torch.unique(labels) - if check_contains_target_labels: - # check if the resampled mask still contains those target labels - for anatomy_label in self.anatomy_list: - if anatomy_label not in contained_labels: - raise ValueError( - f"Resampled mask does not contain required class labels {anatomy_label}. Please tune spacing and output size." - ) - return labels - - def read_mask_information(self, mask_file): - """ - Read mask information from a file. - - Args: - mask_file (str): Path to the mask file. - - Returns: - tuple: A tuple containing the mask tensor and associated information. - """ - val_data = self.val_transforms(mask_file) - - for key in ["pseudo_label", "spacing", "top_region_index", "bottom_region_index"]: - if isinstance(val_data[key], torch.Tensor): - val_data[key] = val_data[key].unsqueeze(0).to(self.device) - else: - val_data[key] = None - - return ( - val_data["pseudo_label"], - val_data["top_region_index"], - val_data["bottom_region_index"], - val_data["spacing"], - ) - - def find_closest_masks(self, num_img): - """ - Find the closest matching masks from the database. - - Args: - num_img (int): Number of images to generate. - - Returns: - list: List of closest matching mask candidates. - - Raises: - ValueError: If suitable candidates cannot be found. - """ - # first check the database based on anatomy list - candidates = find_masks( - self.body_region, - self.anatomy_list, - self.spacing, - self.output_size, - False, - self.all_mask_files_json, - self.data_root, - ) - - if len(candidates) < num_img: - raise ValueError(f"candidate masks are less than {num_img}).") - - # loop through the database and find closest combinations - new_candidates = [] - for c in candidates: - diff = 0 - include_c = True - for axis in range(3): - if abs(c["dim"][axis]) < self.output_size[axis] - 64: - # we cannot upsample the mask too much - include_c = False - break - # check diff in FOV, major metric - diff += abs( - ( - abs(c["dim"][axis] * c["spacing"][axis]) - - self.output_size[axis] * self.spacing[axis] - ) - / 10 - ) - # check diff in dim - diff += abs((abs(c["dim"][axis]) - self.output_size[axis]) / 100) - # check diff in spacing - diff += abs(abs(c["spacing"][axis]) - self.spacing[axis]) - if include_c: - new_candidates.append((c, diff)) - - # choose top-2*num_img candidates (at least 5) - num_candidates = max(self.max_try_time * num_img, 5) - new_candidates = sorted(new_candidates, key=lambda x: x[1]) - - final_candidates = [] - # check top-2*num_img candidates and update spacing after resampling - for c, _ in new_candidates: - c = self.resample_mask_check_organ_list(c) - if c is not None: - final_candidates.append(c) - if len(final_candidates) >= num_candidates: - break - if len(final_candidates) == 0: - raise ValueError("Cannot find body region with given organ list.") - return final_candidates - - def resample_mask_check_organ_list(self, mask): - """ - Resample mask and check if the resampled mask contains the required organ list. - - Args: - mask (dict): input mask. - - Returns: - dict: resampled mask. If None, means the resampled mask does not contain the required organ list - - Raises: - ValueError: If suitable candidates cannot be found. - """ - - image_loader = monai.transforms.LoadImage(image_only=True, ensure_channel_first=True) - label = image_loader(mask["pseudo_label"]) - try: - label = self.ensure_output_size_and_spacing(label.unsqueeze(0)) - except ValueError as e: - if "Resampled mask does not contain required class labels" in str(e): - return None - else: - raise e - # get region_index after resample - top_region_index, bottom_region_index = get_body_region_index_from_mask(label) - mask["top_region_index"] = top_region_index - mask["bottom_region_index"] = bottom_region_index - mask["spacing"] = self.spacing - mask["dim"] = self.output_size - return mask - - def quality_check(self, image_data, label_data): - """ - Perform a quality check on the generated image. - Args: - image_data (np.ndarray): The generated image. - label_data (np.ndarray): The corresponding whole body mask. - Returns: - bool: True if the image passes the quality check, False otherwise. - """ - outlier_results = is_outlier( - self.median_statistics, image_data, label_data, self.label_int_dict - ) - for label, result in outlier_results.items(): - if result.get("is_outlier", False): - logging.info( - f"Generated image quality check for label '{label}' failed: median value {result['median_value']} is outside the acceptable range ({result['low_thresh']} - {result['high_thresh']})." - ) - return False - return True diff --git a/itrialspace/src/itrialspace/synthesis/scripts/scheduler.py b/itrialspace/src/itrialspace/synthesis/scripts/scheduler.py deleted file mode 100644 index 66dd2dc6703018449d626f4ded55b6944dd36179..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/scheduler.py +++ /dev/null @@ -1,223 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/huggingface/diffusers -# which has the following license: -# https://github.com/huggingface/diffusers/blob/main/LICENSE -# -# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - - -from __future__ import annotations - -import torch -import torch.nn as nn -from monai.utils import ComponentStore, unsqueeze_right - -NoiseSchedules = ComponentStore("NoiseSchedules", "Functions to generate noise schedules") - - -@NoiseSchedules.add_def("linear_beta", "Linear beta schedule") -def _linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): - """ - Linear beta noise schedule function. - - Args: - num_train_timesteps: number of timesteps - beta_start: start of beta range, default 1e-4 - beta_end: end of beta range, default 2e-2 - - Returns: - betas: beta schedule tensor - """ - return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) - - -@NoiseSchedules.add_def("scaled_linear_beta", "Scaled linear beta schedule") -def _scaled_linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): - """ - Scaled linear beta noise schedule function. - - Args: - num_train_timesteps: number of timesteps - beta_start: start of beta range, default 1e-4 - beta_end: end of beta range, default 2e-2 - - Returns: - betas: beta schedule tensor - """ - return ( - torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) - ** 2 - ) - - -@NoiseSchedules.add_def("sigmoid_beta", "Sigmoid beta schedule") -def _sigmoid_beta( - num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2, sig_range: float = 6 -): - """ - Sigmoid beta noise schedule function. - - Args: - num_train_timesteps: number of timesteps - beta_start: start of beta range, default 1e-4 - beta_end: end of beta range, default 2e-2 - sig_range: pos/neg range of sigmoid input, default 6 - - Returns: - betas: beta schedule tensor - """ - betas = torch.linspace(-sig_range, sig_range, num_train_timesteps) - return torch.sigmoid(betas) * (beta_end - beta_start) + beta_start - - -@NoiseSchedules.add_def("cosine", "Cosine schedule") -def _cosine_beta(num_train_timesteps: int, s: float = 8e-3): - """ - Cosine noise schedule, see https://arxiv.org/abs/2102.09672 - - Args: - num_train_timesteps: number of timesteps - s: smoothing factor, default 8e-3 (see referenced paper) - - Returns: - (betas, alphas, alpha_cumprod) values - """ - x = torch.linspace(0, num_train_timesteps, num_train_timesteps + 1) - alphas_cumprod = torch.cos(((x / num_train_timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2 - alphas_cumprod /= alphas_cumprod[0].item() - betas = 1.0 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) - betas = torch.clip(betas, 0.0, 0.999) - alphas = 1.0 - betas - alphas_cumprod = torch.cumprod(alphas, dim=0) - return betas, alphas, alphas_cumprod - - -class Scheduler(nn.Module): - """ - Base class for other schedulers based on a noise schedule function. - - This class is meant as the base for other schedulers which implement their own way of sampling or stepping. Here - the class defines beta, alpha, and alpha_cumprod values from a noise schedule function named with `schedule`, - which is the name of a component in NoiseSchedules. These components must all be callables which return either - the beta schedule alone or a triple containing (betas, alphas, alphas_cumprod) values. New schedule functions - can be provided by using the NoiseSchedules.add_def, for example: - - .. code-block:: python - - from monai.networks.schedulers import NoiseSchedules, DDPMScheduler - - @NoiseSchedules.add_def("my_beta_schedule", "Some description of your function") - def _beta_function(num_train_timesteps, beta_start=1e-4, beta_end=2e-2): - return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) - - scheduler = DDPMScheduler(num_train_timesteps=1000, schedule="my_beta_schedule") - - All such functions should have an initial positional integer argument `num_train_timesteps` stating the number of - timesteps the schedule is for, otherwise any other arguments can be given which will be passed by keyword through - the constructor's `schedule_args` value. To see what noise functions are available, print the object NoiseSchedules - to get a listing of stored objects with their docstring descriptions. - - Note: in previous versions of the schedulers the argument `schedule_beta` was used to state the beta schedule - type, this now replaced with `schedule` and most names used with the previous argument now have "_beta" appended - to them, eg. 'schedule_beta="linear"' -> 'schedule="linear_beta"'. The `beta_start` and `beta_end` arguments are - still used for some schedules but these are provided as keyword arguments now. - - Args: - num_train_timesteps: number of diffusion steps used to train the model. - schedule: member of NoiseSchedules, - a named function returning the beta tensor or (betas, alphas, alphas_cumprod) triple - schedule_args: arguments to pass to the schedule function - """ - - def __init__( - self, num_train_timesteps: int = 1000, schedule: str = "linear_beta", **schedule_args - ) -> None: - super().__init__() - schedule_args["num_train_timesteps"] = num_train_timesteps - noise_sched = NoiseSchedules[schedule](**schedule_args) - - # set betas, alphas, alphas_cumprod based off return value from noise function - if isinstance(noise_sched, tuple): - self.betas, self.alphas, self.alphas_cumprod = noise_sched - else: - self.betas = noise_sched - self.alphas = 1.0 - self.betas - self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) - - self.num_train_timesteps = num_train_timesteps - self.one = torch.tensor(1.0) - - # settable values - self.num_inference_steps: int | None = None - self.timesteps = torch.arange(num_train_timesteps - 1, -1, -1) - - def add_noise( - self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor - ) -> torch.Tensor: - """ - Add noise to the original samples. - - Args: - original_samples: original samples - noise: noise to add to samples - timesteps: timesteps tensor indicating the timestep to be computed for each sample. - - Returns: - noisy_samples: sample with added noise - """ - # Make sure alphas_cumprod and timestep have same device and dtype as original_samples - self.alphas_cumprod = self.alphas_cumprod.to( - device=original_samples.device, dtype=original_samples.dtype - ) - timesteps = timesteps.to(original_samples.device) - - sqrt_alpha_cumprod: torch.Tensor = unsqueeze_right( - self.alphas_cumprod[timesteps] ** 0.5, original_samples.ndim - ) - sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( - (1 - self.alphas_cumprod[timesteps]) ** 0.5, original_samples.ndim - ) - - noisy_samples = sqrt_alpha_cumprod * original_samples + sqrt_one_minus_alpha_prod * noise - return noisy_samples - - def get_velocity( - self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor - ) -> torch.Tensor: - # Make sure alphas_cumprod and timestep have same device and dtype as sample - self.alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype) - timesteps = timesteps.to(sample.device) - - sqrt_alpha_prod: torch.Tensor = unsqueeze_right( - self.alphas_cumprod[timesteps] ** 0.5, sample.ndim - ) - sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( - (1 - self.alphas_cumprod[timesteps]) ** 0.5, sample.ndim - ) - - velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample - return velocity diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__init__.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index decce11c372a1eaabfd04fb01a3961a8349688a8..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddim.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddim.cpython-310.pyc deleted file mode 100644 index 38e286b25a1009c4949d7eff73ebcd9b6348385e..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddim.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddpm.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddpm.cpython-310.pyc deleted file mode 100644 index 351c0b6243e04465eeb1594df89e3767e7e0ddf0..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddpm.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/pndm.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/pndm.cpython-310.pyc deleted file mode 100644 index 0a899993bb1c796e0ab99407ea44cd9928deb078..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/pndm.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/rectified_flow.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/rectified_flow.cpython-310.pyc deleted file mode 100644 index e5bd3ba39d6b807b03c89e59af52dd2cbcfe23af..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/rectified_flow.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/scheduler.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/scheduler.cpython-310.pyc deleted file mode 100644 index 8d9ee70f75fdb355eac781b4964e7b075fc82f08..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/scheduler.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddim.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddim.py deleted file mode 100644 index 28297fee334dfe9efbdfa936825de76b8e4ac7cf..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddim.py +++ /dev/null @@ -1,320 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/huggingface/diffusers -# which has the following license: -# https://github.com/huggingface/diffusers/blob/main/LICENSE -# -# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - -from __future__ import annotations - -import numpy as np -import torch - -from .ddpm import DDPMPredictionType -from .scheduler import Scheduler - -DDIMPredictionType = DDPMPredictionType - - -class DDIMScheduler(Scheduler): - """ - Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising - diffusion probabilistic models (DDPMs) with non-Markovian guidance. Based on: Song et al. "Denoising Diffusion - Implicit Models" https://arxiv.org/abs/2010.02502 - - Args: - num_train_timesteps: number of diffusion steps used to train the model. - schedule: member of NoiseSchedules, name of noise schedule function in component store - clip_sample: option to clip predicted sample between -1 and 1 for numerical stability. - set_alpha_to_one: each diffusion step uses the value of alphas product at that step and at the previous one. - For the final step there is no previous alpha. When this option is `True` the previous alpha product is - fixed to `1`, otherwise it uses the value of alpha at step 0. - steps_offset: an offset added to the inference steps. You can use a combination of `steps_offset=1` and - `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in - stable diffusion. - prediction_type: member of DDPMPredictionType - clip_sample_min: minimum clipping value when clip_sample equals True - clip_sample_max: maximum clipping value when clip_sample equals True - schedule_args: arguments to pass to the schedule function - - """ - - def __init__( - self, - num_train_timesteps: int = 1000, - schedule: str = "linear_beta", - clip_sample: bool = True, - set_alpha_to_one: bool = True, - steps_offset: int = 0, - prediction_type: str = DDIMPredictionType.EPSILON, - clip_sample_min: float = -1.0, - clip_sample_max: float = 1.0, - **schedule_args, - ) -> None: - super().__init__(num_train_timesteps, schedule, **schedule_args) - - if prediction_type not in DDIMPredictionType.__members__.values(): - raise ValueError("Argument `prediction_type` must be a member of DDIMPredictionType") - - self.prediction_type = prediction_type - - # At every step in ddim, we are looking into the previous alphas_cumprod - # For the final step, there is no previous alphas_cumprod because we are already at 0 - # `set_alpha_to_one` decides whether we set this parameter simply to one or - # whether we use the final alpha of the "non-previous" one. - self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0] - - # standard deviation of the initial noise distribution - self.init_noise_sigma = 1.0 - - self.timesteps = torch.from_numpy( - np.arange(0, self.num_train_timesteps)[::-1].astype(np.int64) - ) - - self.clip_sample = clip_sample - self.clip_sample_values = [clip_sample_min, clip_sample_max] - self.steps_offset = steps_offset - - # default the number of inference timesteps to the number of train steps - self.num_inference_steps: int - self.set_timesteps(self.num_train_timesteps) - - def set_timesteps( - self, num_inference_steps: int, device: str | torch.device | None = None - ) -> None: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. - device: target device to put the data. - """ - if num_inference_steps > self.num_train_timesteps: - raise ValueError( - f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.num_train_timesteps`:" - f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" - f" maximal {self.num_train_timesteps} timesteps." - ) - - self.num_inference_steps = num_inference_steps - step_ratio = self.num_train_timesteps // self.num_inference_steps - if self.steps_offset >= step_ratio: - raise ValueError( - f"`steps_offset`: {self.steps_offset} cannot be greater than or equal to " - f"`num_train_timesteps // num_inference_steps : {step_ratio}` as this will cause timesteps to exceed" - f" the max train timestep." - ) - - # creates integer timesteps by multiplying by ratio - # casting to int to avoid issues when num_inference_step is power of 3 - timesteps = ( - (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64) - ) - self.timesteps = torch.from_numpy(timesteps).to(device) - self.timesteps += self.steps_offset - - def _get_variance(self, timestep: int, prev_timestep: int) -> torch.Tensor: - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = ( - self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod - ) - beta_prod_t = 1 - alpha_prod_t - beta_prod_t_prev = 1 - alpha_prod_t_prev - - variance: torch.Tensor = (beta_prod_t_prev / beta_prod_t) * ( - 1 - alpha_prod_t / alpha_prod_t_prev - ) - - return variance - - def step( - self, - model_output: torch.Tensor, - timestep: int, - sample: torch.Tensor, - eta: float = 0.0, - generator: torch.Generator | None = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - - Args: - model_output: direct output from learned diffusion model. - timestep: current discrete timestep in the diffusion chain. - sample: current instance of sample being created by diffusion process. - eta: weight of noise for added noise in diffusion step. - generator: random number generator. - - Returns: - pred_prev_sample: Predicted previous sample - pred_original_sample: Predicted original sample - """ - # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf - # Ideally, read DDIM paper in-detail understanding - - # Notation ( -> - # - model_output -> e_theta(x_t, t) - # - pred_original_sample -> f_theta(x_t, t) or x_0 - # - std_dev_t -> sigma_t - # - eta -> η - # - pred_sample_direction -> "direction pointing to x_t" - # - pred_prev_sample -> "x_t-1" - - # 1. get previous step value (=t-1) - prev_timestep = timestep - self.num_train_timesteps // self.num_inference_steps - - # 2. compute alphas, betas - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = ( - self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod - ) - - beta_prod_t = 1 - alpha_prod_t - - # predefinitions satisfy pylint/mypy, these values won't be ultimately used - pred_original_sample = sample - pred_epsilon = model_output - - # 3. compute predicted original sample from predicted noise also called - # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - if self.prediction_type == DDIMPredictionType.EPSILON: - pred_original_sample = (sample - (beta_prod_t**0.5) * model_output) / ( - alpha_prod_t**0.5 - ) - pred_epsilon = model_output - elif self.prediction_type == DDIMPredictionType.SAMPLE: - pred_original_sample = model_output - pred_epsilon = (sample - (alpha_prod_t**0.5) * pred_original_sample) / ( - beta_prod_t**0.5 - ) - elif self.prediction_type == DDIMPredictionType.V_PREDICTION: - pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output - pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample - - # 4. Clip "predicted x_0" - if self.clip_sample: - pred_original_sample = torch.clamp( - pred_original_sample, self.clip_sample_values[0], self.clip_sample_values[1] - ) - - # 5. compute variance: "sigma_t(η)" -> see formula (16) - # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) - variance = self._get_variance(timestep, prev_timestep) - std_dev_t = eta * variance**0.5 - - # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * pred_epsilon - - # 7. compute x_t-1 without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - pred_prev_sample = alpha_prod_t_prev**0.5 * pred_original_sample + pred_sample_direction - - if eta > 0: - # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 - device: torch.device = torch.device( - model_output.device if torch.is_tensor(model_output) else "cpu" - ) - noise = torch.randn( - model_output.shape, dtype=model_output.dtype, generator=generator, device=device - ) - variance = self._get_variance(timestep, prev_timestep) ** 0.5 * eta * noise - - pred_prev_sample = pred_prev_sample + variance - - return pred_prev_sample, pred_original_sample - - def reversed_step( - self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Predict the sample at the next timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - - Args: - model_output: direct output from learned diffusion model. - timestep: current discrete timestep in the diffusion chain. - sample: current instance of sample being created by diffusion process. - - Returns: - pred_prev_sample: Predicted previous sample - pred_original_sample: Predicted original sample - """ - # See Appendix F at https://arxiv.org/pdf/2105.05233.pdf, or Equation (6) in https://arxiv.org/pdf/2203.04306.pdf - - # Notation ( -> - # - model_output -> e_theta(x_t, t) - # - pred_original_sample -> f_theta(x_t, t) or x_0 - # - std_dev_t -> sigma_t - # - eta -> η - # - pred_sample_direction -> "direction pointing to x_t" - # - pred_post_sample -> "x_t+1" - - # 1. get previous step value (=t+1) - prev_timestep = timestep + self.num_train_timesteps // self.num_inference_steps - - # 2. compute alphas, betas at timestep t+1 - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = ( - self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod - ) - - beta_prod_t = 1 - alpha_prod_t - - # predefinitions satisfy pylint/mypy, these values won't be ultimately used - pred_original_sample = sample - pred_epsilon = model_output - - # 3. compute predicted original sample from predicted noise also called - # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - - if self.prediction_type == DDIMPredictionType.EPSILON: - pred_original_sample = ( - sample - beta_prod_t ** (0.5) * model_output - ) / alpha_prod_t ** (0.5) - pred_epsilon = model_output - elif self.prediction_type == DDIMPredictionType.SAMPLE: - pred_original_sample = model_output - pred_epsilon = ( - sample - alpha_prod_t ** (0.5) * pred_original_sample - ) / beta_prod_t ** (0.5) - elif self.prediction_type == DDIMPredictionType.V_PREDICTION: - pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output - pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample - - # 4. Clip "predicted x_0" - if self.clip_sample: - pred_original_sample = torch.clamp( - pred_original_sample, self.clip_sample_values[0], self.clip_sample_values[1] - ) - - # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - pred_sample_direction = (1 - alpha_prod_t_prev) ** (0.5) * pred_epsilon - - # 6. compute x_t+1 without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - pred_post_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction - - return pred_post_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddpm.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddpm.py deleted file mode 100644 index 6b797cc931133a6b2c77c745e8dd2d484c898405..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddpm.py +++ /dev/null @@ -1,274 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/huggingface/diffusers -# which has the following license: -# https://github.com/huggingface/diffusers/blob/main/LICENSE -# -# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - -from __future__ import annotations - -import numpy as np -import torch -from monai.utils import StrEnum - -from .scheduler import Scheduler - - -class DDPMVarianceType(StrEnum): - """ - Valid names for DDPM Scheduler's `variance_type` argument. Options to clip the variance used when adding noise - to the denoised sample. - """ - - FIXED_SMALL = "fixed_small" - FIXED_LARGE = "fixed_large" - LEARNED = "learned" - LEARNED_RANGE = "learned_range" - - -class DDPMPredictionType(StrEnum): - """ - Set of valid prediction type names for the DDPM scheduler's `prediction_type` argument. - - epsilon: predicting the noise of the diffusion process - sample: directly predicting the noisy sample - v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf - """ - - EPSILON = "epsilon" - SAMPLE = "sample" - V_PREDICTION = "v_prediction" - - -class DDPMScheduler(Scheduler): - """ - Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and - Langevin dynamics sampling. Based on: Ho et al., "Denoising Diffusion Probabilistic Models" - https://arxiv.org/abs/2006.11239 - - Args: - num_train_timesteps: number of diffusion steps used to train the model. - schedule: member of NoiseSchedules, name of noise schedule function in component store - variance_type: member of DDPMVarianceType - clip_sample: option to clip predicted sample between -1 and 1 for numerical stability. - prediction_type: member of DDPMPredictionType - clip_sample_min: minimum clipping value when clip_sample equals True - clip_sample_max: maximum clipping value when clip_sample equals True - schedule_args: arguments to pass to the schedule function - """ - - def __init__( - self, - num_train_timesteps: int = 1000, - schedule: str = "linear_beta", - variance_type: str = DDPMVarianceType.FIXED_SMALL, - clip_sample: bool = True, - prediction_type: str = DDPMPredictionType.EPSILON, - clip_sample_min: float = -1.0, - clip_sample_max: float = 1.0, - **schedule_args, - ) -> None: - super().__init__(num_train_timesteps, schedule, **schedule_args) - - if variance_type not in DDPMVarianceType.__members__.values(): - raise ValueError("Argument `variance_type` must be a member of `DDPMVarianceType`") - - if prediction_type not in DDPMPredictionType.__members__.values(): - raise ValueError("Argument `prediction_type` must be a member of `DDPMPredictionType`") - - self.clip_sample = clip_sample - self.clip_sample_values = [clip_sample_min, clip_sample_max] - self.variance_type = variance_type - self.prediction_type = prediction_type - - def set_timesteps( - self, num_inference_steps: int, device: str | torch.device | None = None - ) -> None: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. - device: target device to put the data. - """ - if num_inference_steps > self.num_train_timesteps: - raise ValueError( - f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.num_train_timesteps`:" - f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" - f" maximal {self.num_train_timesteps} timesteps." - ) - - self.num_inference_steps = num_inference_steps - step_ratio = self.num_train_timesteps // self.num_inference_steps - # creates integer timesteps by multiplying by ratio - # casting to int to avoid issues when num_inference_step is power of 3 - timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].astype(np.int64) - self.timesteps = torch.from_numpy(timesteps).to(device) - - def _get_mean(self, timestep: int, x_0: torch.Tensor, x_t: torch.Tensor) -> torch.Tensor: - """ - Compute the mean of the posterior at timestep t. - - Args: - timestep: current timestep. - x0: the noise-free input. - x_t: the input noised to timestep t. - - Returns: - Returns the mean - """ - # these attributes are used for calculating the posterior, q(x_{t-1}|x_t,x_0), - # (see formula (5-7) from https://arxiv.org/pdf/2006.11239.pdf) - alpha_t = self.alphas[timestep] - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = self.alphas_cumprod[timestep - 1] if timestep > 0 else self.one - - x_0_coefficient = alpha_prod_t_prev.sqrt() * self.betas[timestep] / (1 - alpha_prod_t) - x_t_coefficient = alpha_t.sqrt() * (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) - - mean: torch.Tensor = x_0_coefficient * x_0 + x_t_coefficient * x_t - - return mean - - def _get_variance( - self, timestep: int, predicted_variance: torch.Tensor | None = None - ) -> torch.Tensor: - """ - Compute the variance of the posterior at timestep t. - - Args: - timestep: current timestep. - predicted_variance: variance predicted by the model. - - Returns: - Returns the variance - """ - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = self.alphas_cumprod[timestep - 1] if timestep > 0 else self.one - - # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) - # and sample from it to get previous sample - # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample - variance: torch.Tensor = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * self.betas[timestep] - # hacks - were probably added for training stability - if self.variance_type == DDPMVarianceType.FIXED_SMALL: - variance = torch.clamp(variance, min=1e-20) - elif self.variance_type == DDPMVarianceType.FIXED_LARGE: - variance = self.betas[timestep] - elif self.variance_type == DDPMVarianceType.LEARNED and predicted_variance is not None: - return predicted_variance - elif ( - self.variance_type == DDPMVarianceType.LEARNED_RANGE and predicted_variance is not None - ): - min_log = variance - max_log = self.betas[timestep] - frac = (predicted_variance + 1) / 2 - variance = frac * max_log + (1 - frac) * min_log - - return variance - - def step( - self, - model_output: torch.Tensor, - timestep: int, - sample: torch.Tensor, - generator: torch.Generator | None = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - - Args: - model_output: direct output from learned diffusion model. - timestep: current discrete timestep in the diffusion chain. - sample: current instance of sample being created by diffusion process. - generator: random number generator. - - Returns: - pred_prev_sample: Predicted previous sample - """ - if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in [ - "learned", - "learned_range", - ]: - model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1) - else: - predicted_variance = None - - # 1. compute alphas, betas - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = self.alphas_cumprod[timestep - 1] if timestep > 0 else self.one - beta_prod_t = 1 - alpha_prod_t - beta_prod_t_prev = 1 - alpha_prod_t_prev - - # 2. compute predicted original sample from predicted noise also called - # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf - if self.prediction_type == DDPMPredictionType.EPSILON: - pred_original_sample = ( - sample - beta_prod_t ** (0.5) * model_output - ) / alpha_prod_t ** (0.5) - elif self.prediction_type == DDPMPredictionType.SAMPLE: - pred_original_sample = model_output - elif self.prediction_type == DDPMPredictionType.V_PREDICTION: - pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output - - # 3. Clip "predicted x_0" - if self.clip_sample: - pred_original_sample = torch.clamp( - pred_original_sample, self.clip_sample_values[0], self.clip_sample_values[1] - ) - - # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t - # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf - pred_original_sample_coeff = ( - alpha_prod_t_prev ** (0.5) * self.betas[timestep] - ) / beta_prod_t - current_sample_coeff = self.alphas[timestep] ** (0.5) * beta_prod_t_prev / beta_prod_t - - # 5. Compute predicted previous sample µ_t - # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf - pred_prev_sample = ( - pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample - ) - - # 6. Add noise - variance: torch.Tensor = torch.tensor(0) - if timestep > 0: - noise = torch.randn( - model_output.size(), - dtype=model_output.dtype, - layout=model_output.layout, - generator=generator, - device=model_output.device, - ) - variance = ( - self._get_variance(timestep, predicted_variance=predicted_variance) ** 0.5 - ) * noise - - pred_prev_sample = pred_prev_sample + variance - - return pred_prev_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/pndm.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/pndm.py deleted file mode 100644 index 6901aac7f189d3e58151fae6694e5ac583bfae96..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/pndm.py +++ /dev/null @@ -1,332 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/huggingface/diffusers -# which has the following license: -# https://github.com/huggingface/diffusers/blob/main/LICENSE -# -# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - -from __future__ import annotations - -from typing import Any - -import numpy as np -import torch -from monai.utils import StrEnum - -from .scheduler import Scheduler - - -class PNDMPredictionType(StrEnum): - """ - Set of valid prediction type names for the PNDM scheduler's `prediction_type` argument. - - epsilon: predicting the noise of the diffusion process - v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf - """ - - EPSILON = "epsilon" - V_PREDICTION = "v_prediction" - - -class PNDMScheduler(Scheduler): - """ - Pseudo numerical methods for diffusion models (PNDM) proposes using more advanced ODE integration techniques, - namely Runge-Kutta method and a linear multi-step method. Based on: Liu et al., - "Pseudo Numerical Methods for Diffusion Models on Manifolds" https://arxiv.org/abs/2202.09778 - - Args: - num_train_timesteps: number of diffusion steps used to train the model. - schedule: member of NoiseSchedules, name of noise schedule function in component store - skip_prk_steps: - allows the scheduler to skip the Runge-Kutta steps that are defined in the original paper as being required - before plms step. - set_alpha_to_one: - each diffusion step uses the value of alphas product at that step and at the previous one. For the final - step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`, - otherwise it uses the value of alpha at step 0. - prediction_type: member of DDPMPredictionType - steps_offset: - an offset added to the inference steps. You can use a combination of `offset=1` and - `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in - stable diffusion. - schedule_args: arguments to pass to the schedule function - """ - - def __init__( - self, - num_train_timesteps: int = 1000, - schedule: str = "linear_beta", - skip_prk_steps: bool = False, - set_alpha_to_one: bool = False, - prediction_type: str = PNDMPredictionType.EPSILON, - steps_offset: int = 0, - **schedule_args, - ) -> None: - super().__init__(num_train_timesteps, schedule, **schedule_args) - - if prediction_type not in PNDMPredictionType.__members__.values(): - raise ValueError("Argument `prediction_type` must be a member of PNDMPredictionType") - - self.prediction_type = prediction_type - - self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0] - - # standard deviation of the initial noise distribution - self.init_noise_sigma = 1.0 - - # For now we only support F-PNDM, i.e. the runge-kutta method - # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf - # mainly at formula (9), (12), (13) and the Algorithm 2. - self.pndm_order = 4 - - self.skip_prk_steps = skip_prk_steps - self.steps_offset = steps_offset - - # running values - self.cur_model_output = torch.Tensor() - self.counter = 0 - self.cur_sample = torch.Tensor() - self.ets: list = [] - - # default the number of inference timesteps to the number of train steps - self.set_timesteps(num_train_timesteps) - - def set_timesteps( - self, num_inference_steps: int, device: str | torch.device | None = None - ) -> None: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. - device: target device to put the data. - """ - if num_inference_steps > self.num_train_timesteps: - raise ValueError( - f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.num_train_timesteps`:" - f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" - f" maximal {self.num_train_timesteps} timesteps." - ) - - self.num_inference_steps = num_inference_steps - step_ratio = self.num_train_timesteps // self.num_inference_steps - # creates integer timesteps by multiplying by ratio - # casting to int to avoid issues when num_inference_step is power of 3 - self._timesteps = (np.arange(0, num_inference_steps) * step_ratio).round().astype(np.int64) - self._timesteps += self.steps_offset - - if self.skip_prk_steps: - # for some models like stable diffusion the prk steps can/should be skipped to - # produce better results. When using PNDM with `self.skip_prk_steps` the implementation - # is based on crowsonkb's PLMS sampler implementation: https://github.com/CompVis/latent-diffusion/pull/51 - self.prk_timesteps = np.array([]) - self.plms_timesteps = self._timesteps[::-1] - - else: - prk_timesteps = np.array(self._timesteps[-self.pndm_order :]).repeat(2) + np.tile( - np.array([0, self.num_train_timesteps // num_inference_steps // 2]), self.pndm_order - ) - self.prk_timesteps = (prk_timesteps[:-1].repeat(2)[1:-1])[::-1].copy() - self.plms_timesteps = self._timesteps[:-3][ - ::-1 - ].copy() # we copy to avoid having negative strides which are not supported by torch.from_numpy - - timesteps = np.concatenate([self.prk_timesteps, self.plms_timesteps]).astype(np.int64) - self.timesteps = torch.from_numpy(timesteps).to(device) - # update num_inference_steps - necessary if we use prk steps - self.num_inference_steps = len(self.timesteps) - - self.ets = [] - self.counter = 0 - - def step( - self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor - ) -> tuple[torch.Tensor, Any]: - """ - Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - This function calls `step_prk()` or `step_plms()` depending on the internal variable `counter`. - - Args: - model_output: direct output from learned diffusion model. - timestep: current discrete timestep in the diffusion chain. - sample: current instance of sample being created by diffusion process. - Returns: - pred_prev_sample: Predicted previous sample - """ - # return a tuple for consistency with samplers that return (previous pred, original sample pred) - - if self.counter < len(self.prk_timesteps) and not self.skip_prk_steps: - return self.step_prk(model_output=model_output, timestep=timestep, sample=sample), None - else: - return self.step_plms(model_output=model_output, timestep=timestep, sample=sample), None - - def step_prk( - self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor - ) -> torch.Tensor: - """ - Step function propagating the sample with the Runge-Kutta method. RK takes 4 forward passes to approximate the - solution to the differential equation. - - Args: - model_output: direct output from learned diffusion model. - timestep: current discrete timestep in the diffusion chain. - sample: current instance of sample being created by diffusion process. - - Returns: - pred_prev_sample: Predicted previous sample - """ - if self.num_inference_steps is None: - raise ValueError( - "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" - ) - - diff_to_prev = ( - 0 if self.counter % 2 else self.num_train_timesteps // self.num_inference_steps // 2 - ) - prev_timestep = timestep - diff_to_prev - timestep = self.prk_timesteps[self.counter // 4 * 4] - - if self.counter % 4 == 0: - self.cur_model_output = 1 / 6 * model_output - self.ets.append(model_output) - self.cur_sample = sample - elif (self.counter - 1) % 4 == 0: - self.cur_model_output += 1 / 3 * model_output - elif (self.counter - 2) % 4 == 0: - self.cur_model_output += 1 / 3 * model_output - elif (self.counter - 3) % 4 == 0: - model_output = self.cur_model_output + 1 / 6 * model_output - self.cur_model_output = torch.Tensor() - - # cur_sample should not be an empty torch.Tensor() - cur_sample = self.cur_sample if self.cur_sample.numel() != 0 else sample - - prev_sample: torch.Tensor = self._get_prev_sample( - cur_sample, timestep, prev_timestep, model_output - ) - self.counter += 1 - - return prev_sample - - def step_plms(self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor) -> Any: - """ - Step function propagating the sample with the linear multi-step method. This has one forward pass with multiple - times to approximate the solution. - - Args: - model_output: direct output from learned diffusion model. - timestep: current discrete timestep in the diffusion chain. - sample: current instance of sample being created by diffusion process. - - Returns: - pred_prev_sample: Predicted previous sample - """ - if self.num_inference_steps is None: - raise ValueError( - "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" - ) - - if not self.skip_prk_steps and len(self.ets) < 3: - raise ValueError( - f"{self.__class__} can only be run AFTER scheduler has been run " - "in 'prk' mode for at least 12 iterations " - ) - - prev_timestep = timestep - self.num_train_timesteps // self.num_inference_steps - - if self.counter != 1: - self.ets = self.ets[-3:] - self.ets.append(model_output) - else: - prev_timestep = timestep - timestep = timestep + self.num_train_timesteps // self.num_inference_steps - - if len(self.ets) == 1 and self.counter == 0: - model_output = model_output - self.cur_sample = sample - elif len(self.ets) == 1 and self.counter == 1: - model_output = (model_output + self.ets[-1]) / 2 - sample = self.cur_sample - self.cur_sample = torch.Tensor() - elif len(self.ets) == 2: - model_output = (3 * self.ets[-1] - self.ets[-2]) / 2 - elif len(self.ets) == 3: - model_output = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 - else: - model_output = (1 / 24) * ( - 55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4] - ) - - prev_sample = self._get_prev_sample(sample, timestep, prev_timestep, model_output) - self.counter += 1 - - return prev_sample - - def _get_prev_sample( - self, sample: torch.Tensor, timestep: int, prev_timestep: int, model_output: torch.Tensor - ): - # See formula (9) of PNDM paper https://arxiv.org/pdf/2202.09778.pdf - # this function computes x_(t−δ) using the formula of (9) - # Note that x_t needs to be added to both sides of the equation - - # Notation ( -> - # alpha_prod_t -> α_t - # alpha_prod_t_prev -> α_(t−δ) - # beta_prod_t -> (1 - α_t) - # beta_prod_t_prev -> (1 - α_(t−δ)) - # sample -> x_t - # model_output -> e_θ(x_t, t) - # prev_sample -> x_(t−δ) - alpha_prod_t = self.alphas_cumprod[timestep] - alpha_prod_t_prev = ( - self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod - ) - beta_prod_t = 1 - alpha_prod_t - beta_prod_t_prev = 1 - alpha_prod_t_prev - - if self.prediction_type == PNDMPredictionType.V_PREDICTION: - model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample - - # corresponds to (α_(t−δ) - α_t) divided by - # denominator of x_t in formula (9) and plus 1 - # Note: (α_(t−δ) - α_t) / (sqrt(α_t) * (sqrt(α_(t−δ)) + sqr(α_t))) = - # sqrt(α_(t−δ)) / sqrt(α_t)) - sample_coeff = (alpha_prod_t_prev / alpha_prod_t) ** (0.5) - - # corresponds to denominator of e_θ(x_t, t) in formula (9) - model_output_denom_coeff = alpha_prod_t * beta_prod_t_prev ** (0.5) + ( - alpha_prod_t * beta_prod_t * alpha_prod_t_prev - ) ** (0.5) - - # full formula (9) - prev_sample = ( - sample_coeff * sample - - (alpha_prod_t_prev - alpha_prod_t) * model_output / model_output_denom_coeff - ) - - return prev_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py deleted file mode 100644 index cf402ae222a39c8b943dd76b79387fad212bd9fa..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py +++ /dev/null @@ -1,337 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/hpcaitech/Open-Sora/blob/main/opensora/schedulers/rf/rectified_flow.py -# which has the following license: -# https://github.com/hpcaitech/Open-Sora/blob/main/LICENSE -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - -from __future__ import annotations - -from typing import Union - -import numpy as np -import torch -from monai.utils import StrEnum -from torch.distributions import LogisticNormal - -from .ddpm import DDPMPredictionType -from .scheduler import Scheduler - - -class RFlowPredictionType(StrEnum): - """ - Set of valid prediction type names for the RFlow scheduler's `prediction_type` argument. - - v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf - """ - - V_PREDICTION = DDPMPredictionType.V_PREDICTION - - -def timestep_transform( - t, - input_img_size_numel, - base_img_size_numel=32 * 32 * 32, - scale=1.0, - num_train_timesteps=1000, - spatial_dim=3, -): - """ - Applies a transformation to the timestep based on image resolution scaling. - - Args: - t (torch.Tensor): The original timestep(s). - input_img_size_numel (torch.Tensor): The input image's size (H * W * D). - base_img_size_numel (int): reference H*W*D size, usually smaller than input_img_size_numel. - scale (float): Scaling factor for the transformation. - num_train_timesteps (int): Total number of training timesteps. - spatial_dim (int): Number of spatial dimensions in the image. - - Returns: - torch.Tensor: Transformed timestep(s). - """ - t = t / num_train_timesteps - ratio_space = (input_img_size_numel / base_img_size_numel) ** (1.0 / spatial_dim) - - ratio = ratio_space * scale - new_t = ratio * t / (1 + (ratio - 1) * t) - - new_t = new_t * num_train_timesteps - return new_t - - -class RFlowScheduler(Scheduler): - """ - A rectified flow scheduler for guiding the diffusion process in a generative model. - - Supports uniform and logit-normal sampling methods, timestep transformation for - different resolutions, and noise addition during diffusion. - - Args: - num_train_timesteps (int): Total number of training timesteps. - use_discrete_timesteps (bool): Whether to use discrete timesteps. - sample_method (str): Training time step sampling method ('uniform' or 'logit-normal'). - loc (float): Location parameter for logit-normal distribution, used only if sample_method='logit-normal'. - scale (float): Scale parameter for logit-normal distribution, used only if sample_method='logit-normal'. - use_timestep_transform (bool): Whether to apply timestep transformation. - If true, there will be more inference timesteps at early(noisy) stages for larger image volumes. - transform_scale (float): Scaling factor for timestep transformation, used only if use_timestep_transform=True. - steps_offset (int): Offset added to computed timesteps, used only if use_timestep_transform=True. - base_img_size_numel (int): Reference image volume size for scaling, used only if use_timestep_transform=True. - spatial_dim (int): 2 or 3, incidcating 2D or 3D images, used only if use_timestep_transform=True. - - Example: - - .. code-block:: python - - # define a scheduler - noise_scheduler = RFlowScheduler( - num_train_timesteps = 1000, - use_discrete_timesteps = True, - sample_method = 'logit-normal', - use_timestep_transform = True, - base_img_size_numel = 32 * 32 * 32, - spatial_dim = 3 - ) - - # during training - inputs = torch.ones(2,4,64,64,32) - noise = torch.randn_like(inputs) - timesteps = noise_scheduler.sample_timesteps(inputs) - noisy_inputs = noise_scheduler.add_noise(original_samples=inputs, noise=noise, timesteps=timesteps) - predicted_velocity = diffusion_unet( - x=noisy_inputs, - timesteps=timesteps - ) - loss = loss_l1(predicted_velocity, (inputs - noise)) - - # during inference - noisy_inputs = torch.randn(2,4,64,64,32) - input_img_size_numel = torch.prod(torch.tensor(noisy_inputs.shape[-3:]) - noise_scheduler.set_timesteps( - num_inference_steps=30, input_img_size_numel=input_img_size_numel) - ) - all_next_timesteps = torch.cat( - (noise_scheduler.timesteps[1:], torch.tensor([0], dtype=noise_scheduler.timesteps.dtype)) - ) - for t, next_t in tqdm( - zip(noise_scheduler.timesteps, all_next_timesteps), - total=min(len(noise_scheduler.timesteps), len(all_next_timesteps)), - ): - predicted_velocity = diffusion_unet( - x=noisy_inputs, - timesteps=timesteps - ) - noisy_inputs, _ = noise_scheduler.step(predicted_velocity, t, noisy_inputs, next_t) - final_output = noisy_inputs - """ - - def __init__( - self, - num_train_timesteps: int = 1000, - use_discrete_timesteps: bool = True, - sample_method: str = "uniform", - loc: float = 0.0, - scale: float = 1.0, - use_timestep_transform: bool = False, - transform_scale: float = 1.0, - steps_offset: int = 0, - base_img_size_numel: int = 32 * 32 * 32, - spatial_dim: int = 3, - ): - # rectified flow only accepts velocity prediction - self.prediction_type = RFlowPredictionType.V_PREDICTION - - self.num_train_timesteps = num_train_timesteps - self.use_discrete_timesteps = use_discrete_timesteps - self.base_img_size_numel = base_img_size_numel - self.spatial_dim = spatial_dim - - # sample method - if sample_method not in ["uniform", "logit-normal"]: - raise ValueError( - f"sample_method = {sample_method}, which has to be chosen from ['uniform', 'logit-normal']." - ) - self.sample_method = sample_method - if sample_method == "logit-normal": - self.distribution = LogisticNormal(torch.tensor([loc]), torch.tensor([scale])) - self.sample_t = lambda x: self.distribution.sample((x.shape[0],))[:, 0].to(x.device) - - # timestep transform - self.use_timestep_transform = use_timestep_transform - self.transform_scale = transform_scale - self.steps_offset = steps_offset - - def add_noise( - self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor - ) -> torch.Tensor: - """ - Add noise to the original samples. - - Args: - original_samples: original samples - noise: noise to add to samples - timesteps: timesteps tensor with shape of (N,), indicating the timestep to be computed for each sample. - - Returns: - noisy_samples: sample with added noise - """ - timepoints: torch.Tensor = timesteps.float() / self.num_train_timesteps - timepoints = 1 - timepoints # [1,1/1000] - - # expand timepoint to noise shape - if noise.ndim == 5: - timepoints = timepoints[..., None, None, None, None].expand(-1, *noise.shape[1:]) - elif noise.ndim == 4: - timepoints = timepoints[..., None, None, None].expand(-1, *noise.shape[1:]) - else: - raise ValueError( - f"noise tensor has to be 4D or 5D tensor, yet got shape of {noise.shape}" - ) - - noisy_samples: torch.Tensor = timepoints * original_samples + (1 - timepoints) * noise - - return noisy_samples - - def set_timesteps( - self, - num_inference_steps: int, - device: str | torch.device | None = None, - input_img_size_numel: int | None = None, - ) -> None: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. - device: target device to put the data. - input_img_size_numel: int, H*W*D of the image, used with self.use_timestep_transform is True. - """ - if num_inference_steps > self.num_train_timesteps or num_inference_steps < 1: - raise ValueError( - f"`num_inference_steps`: {num_inference_steps} should be at least 1, " - "and cannot be larger than `self.num_train_timesteps`:" - f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" - f" maximal {self.num_train_timesteps} timesteps." - ) - - self.num_inference_steps = num_inference_steps - # prepare timesteps - timesteps = [ - (1.0 - i / self.num_inference_steps) * self.num_train_timesteps - for i in range(self.num_inference_steps) - ] - if self.use_discrete_timesteps: - timesteps = [int(round(t)) for t in timesteps] - if self.use_timestep_transform: - timesteps = [ - timestep_transform( - t, - input_img_size_numel=input_img_size_numel, - base_img_size_numel=self.base_img_size_numel, - num_train_timesteps=self.num_train_timesteps, - spatial_dim=self.spatial_dim, - ) - for t in timesteps - ] - timesteps_np = np.array(timesteps).astype(np.float16) - if self.use_discrete_timesteps: - timesteps_np = timesteps_np.astype(np.int64) - self.timesteps = torch.from_numpy(timesteps_np).to(device) - self.timesteps += self.steps_offset - - def sample_timesteps(self, x_start): - """ - Randomly samples training timesteps using the chosen sampling method. - - Args: - x_start (torch.Tensor): The input tensor for sampling. - - Returns: - torch.Tensor: Sampled timesteps. - """ - if self.sample_method == "uniform": - t = torch.rand((x_start.shape[0],), device=x_start.device) * self.num_train_timesteps - elif self.sample_method == "logit-normal": - t = self.sample_t(x_start) * self.num_train_timesteps - - if self.use_discrete_timesteps: - t = t.long() - - if self.use_timestep_transform: - input_img_size_numel = torch.prod(torch.tensor(x_start.shape[2:])) - t = timestep_transform( - t, - input_img_size_numel=input_img_size_numel, - base_img_size_numel=self.base_img_size_numel, - num_train_timesteps=self.num_train_timesteps, - spatial_dim=len(x_start.shape) - 2, - ) - - return t - - def step( - self, - model_output: torch.Tensor, - timestep: int, - sample: torch.Tensor, - next_timestep: Union[int, None] = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Predicts the next sample in the diffusion process. - - Args: - model_output (torch.Tensor): Output from the trained diffusion model. - timestep (int): Current timestep in the diffusion chain. - sample (torch.Tensor): Current sample in the process. - next_timestep (Union[int, None]): Optional next timestep. - - Returns: - tuple[torch.Tensor, torch.Tensor]: Predicted sample at the next step and additional info. - """ - # Ensure num_inference_steps exists and is a valid integer - if not hasattr(self, "num_inference_steps") or not isinstance( - self.num_inference_steps, int - ): - raise AttributeError( - "num_inference_steps is missing or not an integer in the class." - "Please run self.set_timesteps(num_inference_steps,device,input_img_size_numel) to set it." - ) - - v_pred = model_output - - if next_timestep is not None: - next_timestep = int(next_timestep) - dt: float = ( - float(timestep - next_timestep) / self.num_train_timesteps - ) # Now next_timestep is guaranteed to be int - else: - dt = ( - 1.0 / float(self.num_inference_steps) if self.num_inference_steps > 0 else 0.0 - ) # Avoid division by zero - - pred_post_sample = sample + v_pred * dt - pred_original_sample = sample + v_pred * timestep / self.num_train_timesteps - - return pred_post_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/scheduler.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/scheduler.py deleted file mode 100644 index 66dd2dc6703018449d626f4ded55b6944dd36179..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/scheduler.py +++ /dev/null @@ -1,223 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ========================================================================= -# Adapted from https://github.com/huggingface/diffusers -# which has the following license: -# https://github.com/huggingface/diffusers/blob/main/LICENSE -# -# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ========================================================================= - - -from __future__ import annotations - -import torch -import torch.nn as nn -from monai.utils import ComponentStore, unsqueeze_right - -NoiseSchedules = ComponentStore("NoiseSchedules", "Functions to generate noise schedules") - - -@NoiseSchedules.add_def("linear_beta", "Linear beta schedule") -def _linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): - """ - Linear beta noise schedule function. - - Args: - num_train_timesteps: number of timesteps - beta_start: start of beta range, default 1e-4 - beta_end: end of beta range, default 2e-2 - - Returns: - betas: beta schedule tensor - """ - return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) - - -@NoiseSchedules.add_def("scaled_linear_beta", "Scaled linear beta schedule") -def _scaled_linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): - """ - Scaled linear beta noise schedule function. - - Args: - num_train_timesteps: number of timesteps - beta_start: start of beta range, default 1e-4 - beta_end: end of beta range, default 2e-2 - - Returns: - betas: beta schedule tensor - """ - return ( - torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) - ** 2 - ) - - -@NoiseSchedules.add_def("sigmoid_beta", "Sigmoid beta schedule") -def _sigmoid_beta( - num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2, sig_range: float = 6 -): - """ - Sigmoid beta noise schedule function. - - Args: - num_train_timesteps: number of timesteps - beta_start: start of beta range, default 1e-4 - beta_end: end of beta range, default 2e-2 - sig_range: pos/neg range of sigmoid input, default 6 - - Returns: - betas: beta schedule tensor - """ - betas = torch.linspace(-sig_range, sig_range, num_train_timesteps) - return torch.sigmoid(betas) * (beta_end - beta_start) + beta_start - - -@NoiseSchedules.add_def("cosine", "Cosine schedule") -def _cosine_beta(num_train_timesteps: int, s: float = 8e-3): - """ - Cosine noise schedule, see https://arxiv.org/abs/2102.09672 - - Args: - num_train_timesteps: number of timesteps - s: smoothing factor, default 8e-3 (see referenced paper) - - Returns: - (betas, alphas, alpha_cumprod) values - """ - x = torch.linspace(0, num_train_timesteps, num_train_timesteps + 1) - alphas_cumprod = torch.cos(((x / num_train_timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2 - alphas_cumprod /= alphas_cumprod[0].item() - betas = 1.0 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) - betas = torch.clip(betas, 0.0, 0.999) - alphas = 1.0 - betas - alphas_cumprod = torch.cumprod(alphas, dim=0) - return betas, alphas, alphas_cumprod - - -class Scheduler(nn.Module): - """ - Base class for other schedulers based on a noise schedule function. - - This class is meant as the base for other schedulers which implement their own way of sampling or stepping. Here - the class defines beta, alpha, and alpha_cumprod values from a noise schedule function named with `schedule`, - which is the name of a component in NoiseSchedules. These components must all be callables which return either - the beta schedule alone or a triple containing (betas, alphas, alphas_cumprod) values. New schedule functions - can be provided by using the NoiseSchedules.add_def, for example: - - .. code-block:: python - - from monai.networks.schedulers import NoiseSchedules, DDPMScheduler - - @NoiseSchedules.add_def("my_beta_schedule", "Some description of your function") - def _beta_function(num_train_timesteps, beta_start=1e-4, beta_end=2e-2): - return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) - - scheduler = DDPMScheduler(num_train_timesteps=1000, schedule="my_beta_schedule") - - All such functions should have an initial positional integer argument `num_train_timesteps` stating the number of - timesteps the schedule is for, otherwise any other arguments can be given which will be passed by keyword through - the constructor's `schedule_args` value. To see what noise functions are available, print the object NoiseSchedules - to get a listing of stored objects with their docstring descriptions. - - Note: in previous versions of the schedulers the argument `schedule_beta` was used to state the beta schedule - type, this now replaced with `schedule` and most names used with the previous argument now have "_beta" appended - to them, eg. 'schedule_beta="linear"' -> 'schedule="linear_beta"'. The `beta_start` and `beta_end` arguments are - still used for some schedules but these are provided as keyword arguments now. - - Args: - num_train_timesteps: number of diffusion steps used to train the model. - schedule: member of NoiseSchedules, - a named function returning the beta tensor or (betas, alphas, alphas_cumprod) triple - schedule_args: arguments to pass to the schedule function - """ - - def __init__( - self, num_train_timesteps: int = 1000, schedule: str = "linear_beta", **schedule_args - ) -> None: - super().__init__() - schedule_args["num_train_timesteps"] = num_train_timesteps - noise_sched = NoiseSchedules[schedule](**schedule_args) - - # set betas, alphas, alphas_cumprod based off return value from noise function - if isinstance(noise_sched, tuple): - self.betas, self.alphas, self.alphas_cumprod = noise_sched - else: - self.betas = noise_sched - self.alphas = 1.0 - self.betas - self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) - - self.num_train_timesteps = num_train_timesteps - self.one = torch.tensor(1.0) - - # settable values - self.num_inference_steps: int | None = None - self.timesteps = torch.arange(num_train_timesteps - 1, -1, -1) - - def add_noise( - self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor - ) -> torch.Tensor: - """ - Add noise to the original samples. - - Args: - original_samples: original samples - noise: noise to add to samples - timesteps: timesteps tensor indicating the timestep to be computed for each sample. - - Returns: - noisy_samples: sample with added noise - """ - # Make sure alphas_cumprod and timestep have same device and dtype as original_samples - self.alphas_cumprod = self.alphas_cumprod.to( - device=original_samples.device, dtype=original_samples.dtype - ) - timesteps = timesteps.to(original_samples.device) - - sqrt_alpha_cumprod: torch.Tensor = unsqueeze_right( - self.alphas_cumprod[timesteps] ** 0.5, original_samples.ndim - ) - sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( - (1 - self.alphas_cumprod[timesteps]) ** 0.5, original_samples.ndim - ) - - noisy_samples = sqrt_alpha_cumprod * original_samples + sqrt_one_minus_alpha_prod * noise - return noisy_samples - - def get_velocity( - self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor - ) -> torch.Tensor: - # Make sure alphas_cumprod and timestep have same device and dtype as sample - self.alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype) - timesteps = timesteps.to(sample.device) - - sqrt_alpha_prod: torch.Tensor = unsqueeze_right( - self.alphas_cumprod[timesteps] ** 0.5, sample.ndim - ) - sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( - (1 - self.alphas_cumprod[timesteps]) ** 0.5, sample.ndim - ) - - velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample - return velocity diff --git a/itrialspace/src/itrialspace/synthesis/scripts/train_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/train_controlnet.py deleted file mode 100644 index bcbbd3621f7b0c2615af554c9b8000e495ad2c09..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/train_controlnet.py +++ /dev/null @@ -1,379 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import argparse -import json -import logging -import os -import sys -import time -from datetime import timedelta -from pathlib import Path - -import torch -import torch.distributed as dist -import torch.nn.functional as F -from monai.networks.schedulers import RFlowScheduler - -# from .schedulers.rectified_flow import RFlowScheduler -from monai.networks.schedulers.ddpm import DDPMPredictionType -from monai.networks.utils import copy_model_state -from monai.utils import RankFilter -from torch.amp import GradScaler, autocast -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.utils.tensorboard import SummaryWriter - -from .utils import ( - binarize_labels, - define_instance, - prepare_maisi_controlnet_json_dataloader, - setup_ddp, -) - - -def main(): - parser = argparse.ArgumentParser(description="maisi.controlnet.training") - parser.add_argument( - "-e", - "--environment-file", - default="./configs/environment_maisi_controlnet_train.json", - help="environment json file that stores environment path", - ) - parser.add_argument( - "-c", - "--config-file", - default="./configs/config_maisi-ddpm.json", - help="config json file that stores network hyper-parameters", - ) - parser.add_argument( - "-t", - "--training-config", - default="./configs/config_maisi_controlnet_train.json", - help="config json file that stores training hyper-parameters", - ) - parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") - - args = parser.parse_args() - - # Step 0: configuration - logger = logging.getLogger("maisi.controlnet.training") - # whether to use distributed data parallel - use_ddp = args.gpus > 1 - if use_ddp: - rank = int(os.environ["LOCAL_RANK"]) - world_size = int(os.environ["WORLD_SIZE"]) - device = setup_ddp(rank, world_size) - logger.addFilter(RankFilter()) - else: - rank = 0 - world_size = 1 - device = torch.device(f"cuda:{rank}") - - torch.cuda.set_device(device) - logger.info(f"Number of GPUs: {torch.cuda.device_count()}") - logger.info(f"World_size: {world_size}") - - with open(args.environment_file, "r") as env_file: - env_dict = json.load(env_file) - with open(args.config_file, "r") as config_file: - config_dict = json.load(config_file) - with open(args.training_config, "r") as training_config_file: - training_config_dict = json.load(training_config_file) - - for k, v in env_dict.items(): - setattr(args, k, v) - for k, v in config_dict.items(): - setattr(args, k, v) - for k, v in training_config_dict.items(): - setattr(args, k, v) - - # initialize tensorboard writer - if rank == 0: - tensorboard_path = os.path.join(args.tfevent_path, args.exp_name) - Path(tensorboard_path).mkdir(parents=True, exist_ok=True) - tensorboard_writer = SummaryWriter(tensorboard_path) - - # Step 1: set data loader - train_loader, _ = prepare_maisi_controlnet_json_dataloader( - json_data_list=args.json_data_list, - data_base_dir=args.data_base_dir, - rank=rank, - world_size=world_size, - batch_size=args.controlnet_train["batch_size"], - cache_rate=args.controlnet_train["cache_rate"], - fold=args.controlnet_train["fold"], - ) - - # Step 2: define diffusion model and controlnet - # define diffusion Model - unet = define_instance(args, "diffusion_unet_def").to(device) - include_body_region = unet.include_top_region_index_input - include_modality = unet.num_class_embeds is not None - - # load trained diffusion model - if args.trained_diffusion_path is not None: - if not os.path.exists(args.trained_diffusion_path): - raise ValueError("Please download the trained diffusion unet checkpoint.") - diffusion_model_ckpt = torch.load( - args.trained_diffusion_path, map_location=device, weights_only=False - ) - unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) - # load scale factor from diffusion model checkpoint - scale_factor = diffusion_model_ckpt["scale_factor"] - logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") - logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") - else: - logger.info("trained diffusion model is not loaded.") - scale_factor = 1.0 - logger.info(f"set scale_factor -> {scale_factor}.") - - # define ControlNet - controlnet = define_instance(args, "controlnet_def").to(device) - # copy weights from the DM to the controlnet - copy_model_state(controlnet, unet.state_dict()) - # load trained controlnet model if it is provided - if args.trained_controlnet_path is not None: - if not os.path.exists(args.trained_controlnet_path): - raise ValueError("Please download the trained ControlNet checkpoint.") - controlnet.load_state_dict( - torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ - "controlnet_state_dict" - ] - ) - logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") - else: - logger.info("train controlnet model from scratch.") - # we freeze the parameters of the diffusion model. - for p in unet.parameters(): - p.requires_grad = False - - noise_scheduler = define_instance(args, "noise_scheduler") - - if use_ddp: - controlnet = DDP( - controlnet, device_ids=[device], output_device=rank, find_unused_parameters=True - ) - - # Step 3: training config - weighted_loss = args.controlnet_train["weighted_loss"] - weighted_loss_label = args.controlnet_train["weighted_loss_label"] - optimizer = torch.optim.AdamW(params=controlnet.parameters(), lr=args.controlnet_train["lr"]) - total_steps = ( - args.controlnet_train["n_epochs"] * len(train_loader.dataset) - ) / args.controlnet_train["batch_size"] - logger.info(f"total number of training steps: {total_steps}.") - - lr_scheduler = torch.optim.lr_scheduler.PolynomialLR( - optimizer, total_iters=total_steps, power=2.0 - ) - - # Step 4: training - n_epochs = args.controlnet_train["n_epochs"] - scaler = GradScaler("cuda") - total_step = 0 - best_loss = 1e4 - - if weighted_loss > 1.0: - logger.info(f"apply weighted loss = {weighted_loss} on labels: {weighted_loss_label}") - - controlnet.train() - unet.eval() - prev_time = time.time() - for epoch in range(n_epochs): - epoch_loss_ = 0 - for step, batch in enumerate(train_loader): - # logger.info(f"Reading image: {batch['image']}") - # logger.info(f"Reading image: {batch['image'].meta['filename_or_obj']}") - # logger.info(f"[Data Load] Step {step+1}: Reading sample {batch.get('image', 'N/A')}") - # get image embedding and label mask and scale image embedding by the provided scale_factor - images = batch["image"].to(device) * scale_factor - labels = batch["label"].to(device) - # get corresponding conditions - if include_body_region: - top_region_index_tensor = batch["top_region_index"].to(device) - bottom_region_index_tensor = batch["bottom_region_index"].to(device) - # We trained with only CT in this version - if include_modality: - modality_tensor = torch.ones((len(images),), dtype=torch.long).to(device) - spacing_tensor = batch["spacing"].to(device) - - optimizer.zero_grad(set_to_none=True) - - with autocast("cuda", enabled=True): - # generate random noise - noise_shape = list(images.shape) - noise = torch.randn(noise_shape, dtype=images.dtype).to(device) - - # use binary encoding to encode segmentation mask - controlnet_cond = binarize_labels(labels.as_tensor().to(torch.uint8)).float() - - # create timesteps - if isinstance(noise_scheduler, RFlowScheduler): - timesteps = noise_scheduler.sample_timesteps(images) - else: - timesteps = torch.randint( - 0, - noise_scheduler.num_train_timesteps, - (images.shape[0],), - device=images.device, - ).long() - - # create noisy latent - noisy_latent = noise_scheduler.add_noise( - original_samples=images, noise=noise, timesteps=timesteps - ) - - # get controlnet output - # Create a dictionary to store the inputs - controlnet_inputs = { - "x": noisy_latent, - "timesteps": timesteps, - "controlnet_cond": controlnet_cond, - } - if include_modality: - controlnet_inputs.update( - { - "class_labels": modality_tensor, - } - ) - down_block_res_samples, mid_block_res_sample = controlnet(**controlnet_inputs) - - # get diffusion network output - # Create a dictionary to store the inputs - unet_inputs = { - "x": noisy_latent, - "timesteps": timesteps, - "spacing_tensor": spacing_tensor, - "down_block_additional_residuals": down_block_res_samples, - "mid_block_additional_residual": mid_block_res_sample, - } - # Add extra arguments if include_body_region is True - if include_body_region: - unet_inputs.update( - { - "top_region_index_tensor": top_region_index_tensor, - "bottom_region_index_tensor": bottom_region_index_tensor, - } - ) - if include_modality: - unet_inputs.update( - { - "class_labels": modality_tensor, - } - ) - model_output = unet(**unet_inputs) - - if noise_scheduler.prediction_type == DDPMPredictionType.EPSILON: - # predict noise - model_gt = noise - elif noise_scheduler.prediction_type == DDPMPredictionType.SAMPLE: - # predict sample - model_gt = images - elif noise_scheduler.prediction_type == DDPMPredictionType.V_PREDICTION: - # predict velocity - model_gt = images - noise - else: - raise ValueError( - "noise scheduler prediction type has to be chosen from ", - f"[{DDPMPredictionType.EPSILON},{DDPMPredictionType.SAMPLE},{DDPMPredictionType.V_PREDICTION}]", - ) - - if weighted_loss > 1.0: - weights = torch.ones_like(images).to(images.device) - roi = torch.zeros([noise_shape[0]] + [1] + noise_shape[2:]).to(images.device) - interpolate_label = F.interpolate(labels, size=images.shape[2:], mode="nearest") - # assign larger weights for ROI (tumor) - for label in weighted_loss_label: - roi[interpolate_label == label] = 1 - weights[roi.repeat(1, images.shape[1], 1, 1, 1) == 1] = weighted_loss - loss = ( - F.l1_loss(model_output.float(), model_gt.float(), reduction="none") * weights - ).mean() - else: - loss = F.l1_loss(model_output.float(), model_gt.float()) - - scaler.scale(loss).backward() - scaler.step(optimizer) - scaler.update() - lr_scheduler.step() - total_step += 1 - - if rank == 0: - # write train loss for each batch into tensorboard - tensorboard_writer.add_scalar( - "train/train_controlnet_loss_iter", loss.detach().cpu().item(), total_step - ) - batches_done = step + 1 - batches_left = len(train_loader) - batches_done - time_left = timedelta(seconds=batches_left * (time.time() - prev_time)) - prev_time = time.time() - logger.info( - "\r[Epoch %d/%d] [Batch %d/%d] [LR: %.8f] [loss: %.4f] ETA: %s " - % ( - epoch + 1, - n_epochs, - step + 1, - len(train_loader), - lr_scheduler.get_last_lr()[0], - loss.detach().cpu().item(), - time_left, - ) - ) - epoch_loss_ += loss.detach() - - epoch_loss = epoch_loss_ / (step + 1) - - if use_ddp: - dist.barrier() - dist.all_reduce(epoch_loss, op=torch.distributed.ReduceOp.AVG) - - if rank == 0: - tensorboard_writer.add_scalar( - "train/train_controlnet_loss_epoch", epoch_loss.cpu().item(), total_step - ) - # save controlnet only on master GPU (rank 0) - controlnet_state_dict = ( - controlnet.module.state_dict() if world_size > 1 else controlnet.state_dict() - ) - torch.save( - { - "epoch": epoch + 1, - "loss": epoch_loss, - "controlnet_state_dict": controlnet_state_dict, - }, - f"{args.model_dir}/{args.exp_name}_current.pt", - ) - - if epoch_loss < best_loss: - best_loss = epoch_loss - logger.info(f"best loss -> {best_loss}.") - torch.save( - { - "epoch": epoch + 1, - "loss": best_loss, - "controlnet_state_dict": controlnet_state_dict, - }, - f"{args.model_dir}/{args.exp_name}_best.pt", - ) - - torch.cuda.empty_cache() - if use_ddp: - dist.destroy_process_group() - - -if __name__ == "__main__": - logging.basicConfig( - stream=sys.stdout, - level=logging.INFO, - format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/transforms.py b/itrialspace/src/itrialspace/synthesis/scripts/transforms.py deleted file mode 100644 index 49533feccac4d84bb1f41998900e89edd6bd158b..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/transforms.py +++ /dev/null @@ -1,354 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import warnings -from typing import List, Optional - -import torch -from monai.transforms import ( - Compose, - DivisiblePadd, - EnsureChannelFirstd, - EnsureTyped, - Lambdad, - LoadImaged, - Orientationd, - RandAdjustContrastd, - RandBiasFieldd, - RandFlipd, - RandGibbsNoised, - RandHistogramShiftd, - RandRotate90d, - RandRotated, - RandScaleIntensityd, - RandShiftIntensityd, - RandSpatialCropd, - RandZoomd, - ResizeWithPadOrCropd, - ScaleIntensityRanged, - ScaleIntensityRangePercentilesd, - SelectItemsd, - Spacingd, - SpatialPadd, -) - -SUPPORT_MODALITIES = ["ct", "mri"] - - -def define_fixed_intensity_transform(modality: str, image_keys: List[str] = ["image"]) -> List: - """ - Define fixed intensity transform based on the modality. - - Args: - modality (str): The imaging modality, either 'ct' or 'mri'. - image_keys (List[str], optional): List of image keys. Defaults to ["image"]. - - Returns: - List: A list of intensity transforms. - """ - if modality not in SUPPORT_MODALITIES: - warnings.warn( - f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." - ) - - modality = modality.lower() # Normalize modality to lowercase - - intensity_transforms = { - "mri": [ - ScaleIntensityRangePercentilesd( - keys=image_keys, lower=0.0, upper=99.5, b_min=0.0, b_max=1, clip=False - ) - ], - "ct": [ - ScaleIntensityRanged( - keys=image_keys, a_min=-1000, a_max=1000, b_min=0.0, b_max=1.0, clip=True - ) - ], - } - - if modality not in intensity_transforms: - return [] - - return intensity_transforms[modality] - - -def define_random_intensity_transform(modality: str, image_keys: List[str] = ["image"]) -> List: - """ - Define random intensity transform based on the modality. - - Args: - modality (str): The imaging modality, either 'ct' or 'mri'. - image_keys (List[str], optional): List of image keys. Defaults to ["image"]. - - Returns: - List: A list of random intensity transforms. - """ - modality = modality.lower() # Normalize modality to lowercase - if modality not in SUPPORT_MODALITIES: - warnings.warn( - f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." - ) - - if modality == "ct": - return [] # CT HU intensity is stable across different datasets - elif modality == "mri": - return [ - RandBiasFieldd(keys=image_keys, prob=0.3, coeff_range=(0.0, 0.3)), - RandGibbsNoised(keys=image_keys, prob=0.3, alpha=(0.5, 1.0)), - RandAdjustContrastd(keys=image_keys, prob=0.3, gamma=(0.5, 2.0)), - RandHistogramShiftd(keys=image_keys, prob=0.05, num_control_points=10), - ] - else: - return [] - - -def define_vae_transform( - is_train: bool, - modality: str, - random_aug: bool, - k: int = 4, - patch_size: List[int] = [128, 128, 128], - val_patch_size: Optional[List[int]] = None, - output_dtype: torch.dtype = torch.float32, - spacing_type: str = "original", - spacing: Optional[List[float]] = None, - image_keys: List[str] = ["image"], - label_keys: List[str] = [], - additional_keys: List[str] = [], - select_channel: int = 0, -) -> tuple: - """ - Define the MAISI VAE transform pipeline for training or validation. - - Args: - is_train (bool): Whether it's for training or not. If True, the output transform will consider random_aug, the cropping will use "patch_size" for random cropping. If False, the output transform will alwasy treat "random_aug" as False, will use "val_patch_size" for central cropping. - modality (str): The imaging modality, either 'ct' or 'mri'. - random_aug (bool): Whether to apply random data augmentation. - k (int, optional): Patches should be divisible by k. Defaults to 4. - patch_size (List[int], optional): Size of the patches. Defaults to [128, 128, 128]. Will random crop patch for training. - val_patch_size (Optional[List[int]], optional): Size of validation patches. Defaults to None. If None, will use the whole volume for validation. If given, will central crop a patch for validation. - output_dtype (torch.dtype, optional): Output data type. Defaults to torch.float32. - spacing_type (str, optional): Type of spacing. Defaults to "original". Choose from ["original", "fixed", "rand_zoom"]. - spacing (Optional[List[float]], optional): Spacing values. Defaults to None. - image_keys (List[str], optional): List of image keys. Defaults to ["image"]. - label_keys (List[str], optional): List of label keys. Defaults to []. - additional_keys (List[str], optional): List of additional keys. Defaults to []. - select_channel (int, optional): Channel to select for multi-channel MRI. Defaults to 0. - - Returns: - tuple: A tuple containing Composed Transform train_transforms or val_transforms depending on 'is_train'. - """ - modality = modality.lower() # Normalize modality to lowercase - if modality not in SUPPORT_MODALITIES: - warnings.warn( - f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." - ) - - if spacing_type not in ["original", "fixed", "rand_zoom"]: - raise ValueError( - f"spacing_type has to be chosen from ['original', 'fixed', 'rand_zoom']. Got {spacing_type}." - ) - - keys = image_keys + label_keys + additional_keys - interp_mode = ["bilinear"] * len(image_keys) + ["nearest"] * len(label_keys) - - common_transform = [ - SelectItemsd(keys=keys, allow_missing_keys=True), - LoadImaged(keys=keys, allow_missing_keys=True), - EnsureChannelFirstd(keys=keys, allow_missing_keys=True), - Orientationd(keys=keys, axcodes="RAS", allow_missing_keys=True), - ] - - if modality == "mri": - common_transform.append( - Lambdad(keys=image_keys, func=lambda x: x[select_channel : select_channel + 1, ...]) - ) - - common_transform.extend(define_fixed_intensity_transform(modality, image_keys=image_keys)) - - if spacing_type == "fixed": - common_transform.append( - Spacingd( - keys=image_keys + label_keys, - allow_missing_keys=True, - pixdim=spacing, - mode=interp_mode, - ) - ) - - random_transform = [] - if is_train and random_aug: - random_transform.extend(define_random_intensity_transform(modality, image_keys=image_keys)) - random_transform.extend( - [ - RandFlipd(keys=keys, allow_missing_keys=True, prob=0.5, spatial_axis=axis) - for axis in range(3) - ] - + [ - RandRotate90d(keys=keys, allow_missing_keys=True, prob=0.5, spatial_axes=axes) - for axes in [(0, 1), (1, 2), (0, 2)] - ] - + [ - RandScaleIntensityd( - keys=image_keys, allow_missing_keys=True, prob=0.3, factors=(0.9, 1.1) - ), - RandShiftIntensityd( - keys=image_keys, allow_missing_keys=True, prob=0.3, offsets=0.05 - ), - ] - ) - - if spacing_type == "rand_zoom": - random_transform.extend( - [ - RandZoomd( - keys=image_keys + label_keys, - allow_missing_keys=True, - prob=0.3, - min_zoom=0.5, - max_zoom=1.5, - keep_size=False, - mode=interp_mode, - ), - RandRotated( - keys=image_keys + label_keys, - allow_missing_keys=True, - prob=0.3, - range_x=0.1, - range_y=0.1, - range_z=0.1, - keep_size=True, - mode=interp_mode, - ), - ] - ) - - if is_train: - train_crop = [ - SpatialPadd(keys=keys, spatial_size=patch_size, allow_missing_keys=True), - RandSpatialCropd( - keys=keys, - roi_size=patch_size, - allow_missing_keys=True, - random_size=False, - random_center=True, - ), - ] - else: - val_crop = ( - [DivisiblePadd(keys=keys, allow_missing_keys=True, k=k)] - if val_patch_size is None - else [ - ResizeWithPadOrCropd( - keys=keys, allow_missing_keys=True, spatial_size=val_patch_size - ) - ] - ) - - final_transform = [EnsureTyped(keys=keys, dtype=output_dtype, allow_missing_keys=True)] - - if is_train: - train_transforms = Compose( - common_transform + random_transform + train_crop + final_transform - if random_aug - else common_transform + train_crop + final_transform - ) - return train_transforms - else: - val_transforms = Compose(common_transform + val_crop + final_transform) - return val_transforms - - -class VAE_Transform: - """ - A class to handle MAISI VAE transformations for different modalities. - """ - - def __init__( - self, - is_train: bool, - random_aug: bool, - k: int = 4, - patch_size: List[int] = [128, 128, 128], - val_patch_size: Optional[List[int]] = None, - output_dtype: torch.dtype = torch.float32, - spacing_type: str = "original", - spacing: Optional[List[float]] = None, - image_keys: List[str] = ["image"], - label_keys: List[str] = [], - additional_keys: List[str] = [], - select_channel: int = 0, - ): - """ - Initialize the VAE_Transform. - - Args: - is_train (bool): Whether it's for training or not. If True, the output transform will consider random_aug, the cropping will use "patch_size" for random cropping. If False, the output transform will alwasy treat "random_aug" as False, will use "val_patch_size" for central cropping. - random_aug (bool): Whether to apply random data augmentation for training. - k (int, optional): Patches should be divisible by k. Defaults to 4. - patch_size (List[int], optional): Size of the patches. Defaults to [128, 128, 128]. Will random crop patch for training. - val_patch_size (Optional[List[int]], optional): Size of validation patches. Defaults to None. If None, will use the whole volume for validation. If given, will central crop a patch for validation. - output_dtype (torch.dtype, optional): Output data type. Defaults to torch.float32. - spacing_type (str, optional): Type of spacing. Defaults to "original". Choose from ["original", "fixed", "rand_zoom"]. - spacing (Optional[List[float]], optional): Spacing values. Defaults to None. - image_keys (List[str], optional): List of image keys. Defaults to ["image"]. - label_keys (List[str], optional): List of label keys. Defaults to []. - additional_keys (List[str], optional): List of additional keys. Defaults to []. - select_channel (int, optional): Channel to select for multi-channel MRI. Defaults to 0. - """ - if spacing_type not in ["original", "fixed", "rand_zoom"]: - raise ValueError( - f"spacing_type has to be chosen from ['original', 'fixed', 'rand_zoom']. Got {spacing_type}." - ) - - self.is_train = is_train - self.transform_dict = {} - - for modality in ["ct", "mri"]: - self.transform_dict[modality] = define_vae_transform( - is_train=is_train, - modality=modality, - random_aug=random_aug, - k=k, - patch_size=patch_size, - val_patch_size=val_patch_size, - output_dtype=output_dtype, - spacing_type=spacing_type, - spacing=spacing, - image_keys=image_keys, - label_keys=label_keys, - additional_keys=additional_keys, - select_channel=select_channel, - ) - - def __call__(self, img: dict, fixed_modality: Optional[str] = None) -> dict: - """ - Apply the appropriate transform to the input image. - - Args: - img (dict): Input image dictionary. - fixed_modality (Optional[str], optional): Fixed modality to use. Defaults to None. - - Returns: - Composed Transform - - Raises: - ValueError: If the modality is not 'ct' or 'mri'. - """ - modality = fixed_modality or img["class"] - modality = modality.lower() # Normalize modality to lowercase - if modality not in ["ct", "mri"]: - warnings.warn( - f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." - ) - - transform = self.transform_dict[modality] - return transform(img) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/utils.py b/itrialspace/src/itrialspace/synthesis/scripts/utils.py deleted file mode 100644 index 8683e513b7b0aa5885cfaaf4dc51032b4501af7a..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/utils.py +++ /dev/null @@ -1,1012 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import json -import logging -import math -import os -from argparse import Namespace -from datetime import timedelta -from typing import Any, Sequence - -import numpy as np -import skimage -import torch -import torch.distributed as dist -from monai.bundle import ConfigParser -from monai.config import DtypeLike, NdarrayOrTensor -from monai.data import CacheDataset, DataLoader, partition_dataset -from monai.transforms import Compose, EnsureTyped, Lambdad, LoadImaged, Orientationd -from monai.transforms.utils_morphological_ops import dilate, erode -from monai.utils import ( - TransformBackends, - convert_data_type, - convert_to_dst_type, - get_equivalent_dtype, -) -from scipy import stats -from torch import Tensor - - -def remap_labels(mask, label_dict_remap_json): - """ - Remap labels in the mask according to the provided label dictionary. - - This function reads a JSON file containing label mapping information and applies - the mapping to the input mask. - - Args: - mask (Tensor): The input mask tensor to be remapped. - label_dict_remap_json (str): Path to the JSON file containing the label mapping dictionary. - - Returns: - Tensor: The remapped mask tensor. - """ - with open(label_dict_remap_json, "r") as f: - mapping_dict = json.load(f) - mapper = MapLabelValue( - orig_labels=[pair[0] for pair in mapping_dict.values()], - target_labels=[pair[1] for pair in mapping_dict.values()], - dtype=torch.uint8, - ) - return mapper(mask[0, ...])[None, ...].to(mask.device) - - -def get_index_arr(img): - """ - Generate an index array for the given image. - - This function creates a 3D array of indices corresponding to the dimensions of the input image. - - Args: - img (ndarray): The input image array. - - Returns: - ndarray: A 3D array containing the indices for each dimension of the input image. - """ - return np.moveaxis( - np.moveaxis( - np.stack( - np.meshgrid( - np.arange(img.shape[0]), np.arange(img.shape[1]), np.arange(img.shape[2]) - ) - ), - 0, - 3, - ), - 0, - 1, - ) - - -def supress_non_largest_components(img, target_label, default_val=0): - """ - Suppress all components except the largest one(s) for specified target labels. - - This function identifies the largest component(s) for each target label and - suppresses all other smaller components. - - Args: - img (ndarray): The input image array. - target_label (list): List of label values to process. - default_val (int, optional): Value to assign to suppressed voxels. Defaults to 0. - - Returns: - tuple: A tuple containing: - - ndarray: Modified image with non-largest components suppressed. - - int: Number of voxels that were changed. - """ - index_arr = get_index_arr(img) - img_mod = copy.deepcopy(img) - new_background = np.zeros(img.shape, dtype=np.bool_) - for label in target_label: - label_cc = skimage.measure.label(img == label, connectivity=3) - uv, uc = np.unique(label_cc, return_counts=True) - dominant_vals = uv[np.argsort(uc)[::-1][:2]] - if len(dominant_vals) >= 2: # Case: no predictions - new_background = np.logical_or( - new_background, - np.logical_not( - np.logical_or(label_cc == dominant_vals[0], label_cc == dominant_vals[1]) - ), - ) - - for voxel in index_arr[new_background]: - img_mod[tuple(voxel)] = default_val - diff = np.sum((img - img_mod) > 0) - - return img_mod, diff - - -def erode_one_img( - mask_t: Tensor, filter_size: int | Sequence[int] = 3, pad_value: float = 1.0 -) -> Tensor: - """ - Erode 2D/3D binary mask with data type as torch tensor. - - Args: - mask_t: input 2D/3D binary mask, [M,N] or [M,N,P] torch tensor. - filter_size: erosion filter size, has to be odd numbers, default to be 3. - pad_value: the filled value for padding. We need to pad the input before filtering - to keep the output with the same size as input. Usually use default value - and not changed. - - Return: - Tensor: eroded mask, same shape as input. - """ - return ( - erode( - mask_t.float() - .unsqueeze(0) - .unsqueeze( - 0, - ), - filter_size, - pad_value=pad_value, - ) - .squeeze(0) - .squeeze(0) - ) - - -def dilate_one_img( - mask_t: Tensor, filter_size: int | Sequence[int] = 3, pad_value: float = 0.0 -) -> Tensor: - """ - Dilate 2D/3D binary mask with data type as torch tensor. - - Args: - mask_t: input 2D/3D binary mask, [M,N] or [M,N,P] torch tensor. - filter_size: dilation filter size, has to be odd numbers, default to be 3. - pad_value: the filled value for padding. We need to pad the input before filtering - to keep the output with the same size as input. Usually use default value - and not changed. - - Return: - Tensor: dilated mask, same shape as input. - """ - return ( - dilate( - mask_t.float() - .unsqueeze(0) - .unsqueeze( - 0, - ), - filter_size, - pad_value=pad_value, - ) - .squeeze(0) - .squeeze(0) - ) - - -def binarize_labels(x: Tensor, bits: int = 8) -> Tensor: - """ - Convert input tensor to binary representation. - - This function takes an input tensor and converts it to a binary representation - using the specified number of bits. - - Args: - x (Tensor): Input tensor with shape (B, 1, H, W, D). - bits (int, optional): Number of bits to use for binary representation. Defaults to 8. - - Returns: - Tensor: Binary representation of the input tensor with shape (B, bits, H, W, D). - """ - mask = 2 ** torch.arange(bits).to(x.device, x.dtype) - return x.unsqueeze(-1).bitwise_and(mask).ne(0).byte().squeeze(1).permute(0, 4, 1, 2, 3) - - -def setup_ddp(rank: int, world_size: int) -> torch.device: - """ - Initialize the distributed process group. - - Args: - rank (int): rank of the current process. - world_size (int): number of processes participating in the job. - - Returns: - torch.device: device of the current process. - """ - dist.init_process_group( - backend="nccl", - init_method="env://", - timeout=timedelta(seconds=36000), - rank=rank, - world_size=world_size, - ) - dist.barrier() - device = torch.device(f"cuda:{rank}") - return device - - -def define_instance(args: Namespace, instance_def_key: str) -> Any: - """ - Define and instantiate an object based on the provided arguments and instance definition key. - - This function uses a ConfigParser to parse the arguments and instantiate an object - defined by the instance_def_key. - - Args: - args: An object containing the arguments to be parsed. - instance_def_key (str): The key used to retrieve the instance definition from the parsed content. - - Returns: - The instantiated object as defined by the instance_def_key in the parsed configuration. - """ - parser = ConfigParser(vars(args)) - parser.parse(True) - return parser.get_parsed_content(instance_def_key, instantiate=True) - - -def add_data_dir2path(list_files: list, data_dir: str, fold: int = None) -> tuple[list, list]: - """ - Read a list of data dictionary. - - Args: - list_files (list): input data to load and transform to generate dataset for model. - data_dir (str): directory of files. - fold (int, optional): fold index for cross validation. Defaults to None. - - Returns: - tuple[list, list]: A tuple of two arrays (training, validation). - """ - new_list_files = copy.deepcopy(list_files) - if fold is not None: - new_list_files_train = [] - new_list_files_val = [] - for d in new_list_files: - d["image"] = os.path.join(data_dir, d["image"]) - - if "label" in d: - d["label"] = os.path.join(data_dir, d["label"]) - - if fold is not None: - if d["fold"] == fold: - new_list_files_val.append(copy.deepcopy(d)) - else: - new_list_files_train.append(copy.deepcopy(d)) - - if fold is not None: - return new_list_files_train, new_list_files_val - else: - return new_list_files, [] - - -def prepare_maisi_controlnet_json_dataloader( - json_data_list: list | str, - data_base_dir: list | str, - batch_size: int = 1, - fold: int = 0, - cache_rate: float = 0.0, - rank: int = 0, - world_size: int = 1, -) -> tuple[DataLoader, DataLoader]: - """ - Prepare dataloaders for training and validation. - - Args: - json_data_list (list | str): the name of JSON files listing the data. - data_base_dir (list | str): directory of files. - batch_size (int, optional): how many samples per batch to load . Defaults to 1. - fold (int, optional): fold index for cross validation. Defaults to 0. - cache_rate (float, optional): percentage of cached data in total. Defaults to 0.0. - rank (int, optional): rank of the current process. Defaults to 0. - world_size (int, optional): number of processes participating in the job. Defaults to 1. - - Returns: - tuple[DataLoader, DataLoader]: A tuple of two dataloaders (training, validation). - """ - use_ddp = world_size > 1 - if isinstance(json_data_list, list): - assert isinstance(data_base_dir, list) - list_train = [] - list_valid = [] - for data_list, data_root in zip(json_data_list, data_base_dir): - with open(data_list, "r") as f: - json_data = json.load(f)["training"] - train, val = add_data_dir2path(json_data, data_root, fold) - list_train += train - list_valid += val - else: - with open(json_data_list, "r") as f: - json_data = json.load(f)["training"] - list_train, list_valid = add_data_dir2path(json_data, data_base_dir, fold) - - common_transform = [ - LoadImaged(keys=["image", "label"], image_only=True, ensure_channel_first=True), - Orientationd(keys=["label"], axcodes="RAS"), - EnsureTyped(keys=["label"], dtype=torch.uint8, track_meta=True), - Lambdad( - keys="top_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True - ), - Lambdad( - keys="bottom_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True - ), - Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), - Lambdad( - keys=["top_region_index", "bottom_region_index", "spacing"], - func=lambda x: x * 1e2, - allow_missing_keys=True, - ), - ] - train_transforms, val_transforms = Compose(common_transform), Compose(common_transform) - - train_loader = None - - if use_ddp: - list_train = partition_dataset( - data=list_train, - shuffle=True, - num_partitions=world_size, - even_divisible=True, - )[rank] - train_ds = CacheDataset( - data=list_train, transform=train_transforms, cache_rate=cache_rate, num_workers=8 - ) - train_loader = DataLoader( - train_ds, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True - ) - if use_ddp: - list_valid = partition_dataset( - data=list_valid, - shuffle=True, - num_partitions=world_size, - even_divisible=False, - )[rank] - val_ds = CacheDataset( - data=list_valid, - transform=val_transforms, - cache_rate=cache_rate, - num_workers=8, - ) - val_loader = DataLoader( - val_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False - ) - return train_loader, val_loader - - -def prepare_maisi_controlnet_infer_dataloader( - json_data_list: list | str, - data_base_dir: list | str, - batch_size: int = 1, - cache_rate: float = 0.0, - rank: int = 0, - world_size: int = 1, -) -> DataLoader: - """ - Prepare dataloader for inference (test set). - - Args: - json_data_list (list | str): the name of JSON files listing the data. - data_base_dir (list | str): directory of files. - batch_size (int, optional): how many samples per batch to load. Defaults to 1. - cache_rate (float, optional): percentage of cached data in total. Defaults to 0.0. - rank (int, optional): rank of the current process. Defaults to 0. - world_size (int, optional): number of processes participating in the job. Defaults to 1. - - Returns: - DataLoader: Dataloader for inference. - """ - use_ddp = world_size > 1 - if isinstance(json_data_list, list): - assert isinstance(data_base_dir, list) - list_infer = [] - for data_list, data_root in zip(json_data_list, data_base_dir): - with open(data_list, "r") as f: - # Use "testing" key for test set - json_data = json.load(f)["testing"] - infer, _ = add_data_dir2path(json_data, data_root, fold=None) - list_infer += infer - else: - with open(json_data_list, "r") as f: - json_data = json.load(f)["testing"] - list_infer, _ = add_data_dir2path(json_data, data_base_dir, fold=None) - - common_transform = [ - LoadImaged(keys=["image", "label"], image_only=True, ensure_channel_first=True), - Orientationd(keys=["label"], axcodes="RAS"), - EnsureTyped(keys=["label"], dtype=torch.uint8, track_meta=True), - Lambdad( - keys="top_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True - ), - Lambdad( - keys="bottom_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True - ), - Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), - Lambdad( - keys=["top_region_index", "bottom_region_index", "spacing"], - func=lambda x: x * 1e2, - allow_missing_keys=True, - ), - ] - infer_transforms = Compose(common_transform) - - if use_ddp: - list_infer = partition_dataset( - data=list_infer, - shuffle=False, - num_partitions=world_size, - even_divisible=False, - )[rank] - infer_ds = CacheDataset( - data=list_infer, transform=infer_transforms, cache_rate=cache_rate, num_workers=8 - ) - infer_loader = DataLoader( - infer_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False - ) - return infer_loader - - -def add_data_dir2path_test(list_files: list, data_dir: str, fold: int = None) -> tuple[list, list]: - """ - Read a list of data dictionary. - - Args: - list_files (list): input data to load and transform to generate dataset for model. - data_dir (str): directory of files. - fold (int, optional): fold index for cross validation. Defaults to None. - - Returns: - tuple[list, list]: A tuple of two arrays (training, validation). - """ - new_list_files = copy.deepcopy(list_files) - if fold is not None: - new_list_files_train = [] - new_list_files_val = [] - for d in new_list_files: - d["label"] = os.path.join(data_dir, d["label"]) - - if fold is not None: - if d["fold"] == fold: - new_list_files_val.append(copy.deepcopy(d)) - else: - new_list_files_train.append(copy.deepcopy(d)) - - if fold is not None: - return new_list_files_train, new_list_files_val - else: - return new_list_files, [] - - -def prepare_maisi_controlnet_test_dataloader( - json_data_list: list | str, - data_base_dir: list | str, - batch_size: int = 1, - cache_rate: float = 0.0, - rank: int = 0, - world_size: int = 1, -) -> DataLoader: - """ - Prepare dataloader for inference (test set). - - Args: - json_data_list (list | str): the name of JSON files listing the data. - data_base_dir (list | str): directory of files. - batch_size (int, optional): how many samples per batch to load. Defaults to 1. - cache_rate (float, optional): percentage of cached data in total. Defaults to 0.0. - rank (int, optional): rank of the current process. Defaults to 0. - world_size (int, optional): number of processes participating in the job. Defaults to 1. - - Returns: - DataLoader: Dataloader for inference. - """ - use_ddp = world_size > 1 - if isinstance(json_data_list, list): - assert isinstance(data_base_dir, list) - list_infer = [] - for data_list, data_root in zip(json_data_list, data_base_dir): - with open(data_list, "r") as f: - # Use "testing" key for test set - json_data = json.load(f)["testing"] - infer, _ = add_data_dir2path_test(json_data, data_root, fold=None) - list_infer += infer - else: - with open(json_data_list, "r") as f: - json_data = json.load(f)["testing"] - list_infer, _ = add_data_dir2path_test(json_data, data_base_dir, fold=None) - - common_transform = [ - LoadImaged(keys=["label"], image_only=True, ensure_channel_first=True), - Orientationd(keys=["label"], axcodes="RAS"), - EnsureTyped(keys=["label"], dtype=torch.uint8, track_meta=True), - Lambdad( - keys="top_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True - ), - Lambdad( - keys="bottom_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True - ), - Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), - Lambdad( - keys=["top_region_index", "bottom_region_index", "spacing"], - func=lambda x: x * 1e2, - allow_missing_keys=True, - ), - ] - infer_transforms = Compose(common_transform) - - if use_ddp: - list_infer = partition_dataset( - data=list_infer, - shuffle=False, - num_partitions=world_size, - even_divisible=False, - )[rank] - infer_ds = CacheDataset( - data=list_infer, transform=infer_transforms, cache_rate=cache_rate, num_workers=8 - ) - infer_loader = DataLoader( - infer_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False - ) - return infer_loader - - -def organ_fill_by_closing(data, target_label, device, close_times=2, filter_size=3, pad_value=0.0): - """ - Fill holes in an organ mask using morphological closing operations. - - This function performs a series of dilation and erosion operations to fill holes - in the organ mask identified by the target label. - - Args: - data (ndarray): The input data containing organ labels. - target_label (int): The label of the organ to be processed. - device (str): The device to perform the operations on (e.g., 'cuda:0'). - close_times (int, optional): Number of times to perform the closing operation. Defaults to 2. - filter_size (int, optional): Size of the filter for dilation and erosion. Defaults to 3. - pad_value (float, optional): Value used for padding in dilation and erosion. Defaults to 0.0. - - Returns: - ndarray: Boolean mask of the filled organ. - """ - mask = (data == target_label).astype(np.uint8) - mask = torch.from_numpy(mask).to(device) - for _ in range(close_times): - mask = dilate_one_img(mask, filter_size=filter_size, pad_value=pad_value) - mask = erode_one_img(mask, filter_size=filter_size, pad_value=pad_value) - return mask.cpu().numpy().astype(np.bool_) - - -def organ_fill_by_removed_mask(data, target_label, remove_mask, device): - """ - Fill an organ mask in regions where it was previously removed. - - Args: - data (ndarray): The input data containing organ labels. - target_label (int): The label of the organ to be processed. - remove_mask (ndarray): Boolean mask indicating regions where the organ was removed. - device (str): The device to perform the operations on (e.g., 'cuda:0'). - - Returns: - ndarray: Boolean mask of the filled organ in previously removed regions. - """ - mask = (data == target_label).astype(np.uint8) - mask = dilate_one_img(torch.from_numpy(mask).to(device), filter_size=3, pad_value=0.0) - mask = dilate_one_img(mask, filter_size=3, pad_value=0.0) - roi_oragn_mask = dilate_one_img(mask, filter_size=3, pad_value=0.0).cpu().numpy() - return (roi_oragn_mask * remove_mask).astype(np.bool_) - - -def get_body_region_index_from_mask(input_mask): - """ - Determine the top and bottom body region indices from an input mask. - - Args: - input_mask (Tensor): Input mask tensor containing body region labels. - - Returns: - tuple: Two lists representing the top and bottom region indices. - """ - region_indices = {} - # head and neck - region_indices["region_0"] = [22, 120] - # thorax - region_indices["region_1"] = [28, 29, 30, 31, 32] - # abdomen - region_indices["region_2"] = [1, 2, 3, 4, 5, 14] - # pelvis and lower - region_indices["region_3"] = [93, 94] - - nda = input_mask.cpu().numpy().squeeze() - unique_elements = np.lib.arraysetops.unique(nda) - unique_elements = list(unique_elements) - # print(f"nda: {nda.shape} {unique_elements}.") - overlap_array = np.zeros(len(region_indices), dtype=np.uint8) - for _j in range(len(region_indices)): - overlap = any(element in region_indices[f"region_{_j}"] for element in unique_elements) - overlap_array[_j] = np.uint8(overlap) - overlap_array_indices = np.nonzero(overlap_array)[0] - top_region_index = np.eye(len(region_indices), dtype=np.uint8)[ - np.amin(overlap_array_indices), ... - ] - top_region_index = list(top_region_index) - top_region_index = [int(_k) for _k in top_region_index] - bottom_region_index = np.eye(len(region_indices), dtype=np.uint8)[ - np.amax(overlap_array_indices), ... - ] - bottom_region_index = list(bottom_region_index) - bottom_region_index = [int(_k) for _k in bottom_region_index] - # print(f"{top_region_index} {bottom_region_index}") - return top_region_index, bottom_region_index - - -def general_mask_generation_post_process(volume_t, target_tumor_label=None, device="cuda:0"): - """ - Perform post-processing on a generated mask volume. - - This function applies various refinement steps to improve the quality of the generated mask, - including body mask refinement, tumor prediction refinement, and organ-specific processing. - - Args: - volume_t (ndarray): Input volume containing organ and tumor labels. - target_tumor_label (int, optional): Label of the target tumor. Defaults to None. - device (str, optional): Device to perform operations on. Defaults to "cuda:0". - - Returns: - ndarray: Post-processed volume with refined organ and tumor labels. - """ - # assume volume_t is np array with shape (H,W,D) - hepatic_vessel = volume_t == 25 - airway = volume_t == 132 - - # ------------ refine body mask pred - body_region_mask = ( - erode_one_img(torch.from_numpy((volume_t > 0)).to(device), filter_size=3, pad_value=0.0) - .cpu() - .numpy() - ) - body_region_mask, _ = supress_non_largest_components(body_region_mask, [1]) - body_region_mask = ( - dilate_one_img(torch.from_numpy(body_region_mask).to(device), filter_size=3, pad_value=0.0) - .cpu() - .numpy() - .astype(np.uint8) - ) - volume_t = volume_t * body_region_mask - - # ------------ refine tumor pred - tumor_organ_dict = {23: 28, 24: 4, 26: 1, 27: 62, 128: 200} - for t in [23, 24, 26, 27, 128]: - if t != target_tumor_label: - volume_t[volume_t == t] = tumor_organ_dict[t] - else: - volume_t[organ_fill_by_closing(volume_t, target_label=t, device=device)] = t - volume_t[organ_fill_by_closing(volume_t, target_label=t, device=device)] = t - # we only keep the largest connected componet for tumors except hepatic tumor and bone lesion - if target_tumor_label != 26 and target_tumor_label != 128: - volume_t, _ = supress_non_largest_components( - volume_t, [target_tumor_label], default_val=200 - ) - target_tumor = volume_t == target_tumor_label - - # ------------ remove undesired organ pred - # general post-process non-largest components suppression - # process 4 ROI organs + spleen + 2 kidney + 5 lung lobes + duodenum + inferior vena cava - oran_list = [1, 4, 10, 12, 3, 28, 29, 30, 31, 32, 5, 14, 13, 6, 7, 8, 9, 10] - if target_tumor_label != 128: - oran_list += list(range(33, 60)) # + list(range(63,87)) - data, _ = supress_non_largest_components( - volume_t, oran_list, default_val=200 - ) # 200 is body region - organ_remove_mask = (volume_t - data).astype(np.bool_) - # process intestinal system (stomach 12, duodenum 13, small bowel 19, colon 62) - intestinal_mask_ = ( - (data == 12).astype(np.uint8) - + (data == 13).astype(np.uint8) - + (data == 19).astype(np.uint8) - + (data == 62).astype(np.uint8) - ) - intestinal_mask, _ = supress_non_largest_components(intestinal_mask_, [1], default_val=0) - # process small bowel 19 - small_bowel_remove_mask = (data == 19).astype(np.uint8) - (data == 19).astype( - np.uint8 - ) * intestinal_mask - # process colon 62 - colon_remove_mask = (data == 62).astype(np.uint8) - (data == 62).astype( - np.uint8 - ) * intestinal_mask - intestinal_remove_mask = (small_bowel_remove_mask + colon_remove_mask).astype(np.bool_) - data[intestinal_remove_mask] = 200 - - # ------------ full correponding organ in removed regions - for organ_label in oran_list: - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - - if target_tumor_label == 23 and np.sum(target_tumor) > 0: - # speical process for cases with lung tumor - dia_lung_tumor_mask = ( - dilate_one_img(torch.from_numpy((data == 23)).to(device), filter_size=3, pad_value=0.0) - .cpu() - .numpy() - ) - tmp = ( - (data * (dia_lung_tumor_mask.astype(np.uint8) - (data == 23).astype(np.uint8))) - .astype(np.float32) - .flatten() - ) - tmp[tmp == 0] = float("nan") - mode = int(stats.mode(tmp.flatten(), nan_policy="omit")[0]) - if mode in [28, 29, 30, 31, 32]: - dia_lung_tumor_mask = ( - dilate_one_img( - torch.from_numpy(dia_lung_tumor_mask).to(device), filter_size=3, pad_value=0.0 - ) - .cpu() - .numpy() - ) - lung_remove_mask = dia_lung_tumor_mask.astype(np.uint8) - (data == 23).astype( - np.uint8 - ).astype(np.uint8) - data[ - organ_fill_by_removed_mask( - data, target_label=mode, remove_mask=lung_remove_mask, device=device - ) - ] = mode - dia_lung_tumor_mask = ( - dilate_one_img( - torch.from_numpy(dia_lung_tumor_mask).to(device), filter_size=3, pad_value=0.0 - ) - .cpu() - .numpy() - ) - data[ - organ_fill_by_removed_mask( - data, - target_label=23, - remove_mask=dia_lung_tumor_mask * organ_remove_mask, - device=device, - ) - ] = 23 - for organ_label in [28, 29, 30, 31, 32]: - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - - if target_tumor_label == 26 and np.sum(target_tumor) > 0: - # speical process for cases with hepatic tumor - # process liver 1 - data[ - organ_fill_by_removed_mask( - data, target_label=1, remove_mask=intestinal_remove_mask, device=device - ) - ] = 1 - data[ - organ_fill_by_removed_mask( - data, target_label=1, remove_mask=intestinal_remove_mask, device=device - ) - ] = 1 - # process spleen 2 - data[ - organ_fill_by_removed_mask( - data, target_label=3, remove_mask=organ_remove_mask, device=device - ) - ] = 3 - data[ - organ_fill_by_removed_mask( - data, target_label=3, remove_mask=organ_remove_mask, device=device - ) - ] = 3 - dia_tumor_mask = ( - dilate_one_img( - torch.from_numpy((data == target_tumor_label)).to(device), - filter_size=3, - pad_value=0.0, - ) - .cpu() - .numpy() - ) - dia_tumor_mask = ( - dilate_one_img( - torch.from_numpy(dia_tumor_mask).to(device), filter_size=3, pad_value=0.0 - ) - .cpu() - .numpy() - ) - data[ - organ_fill_by_removed_mask( - data, - target_label=target_tumor_label, - remove_mask=dia_tumor_mask * organ_remove_mask, - device=device, - ) - ] = target_tumor_label - # refine hepatic tumor - hepatic_tumor_vessel_liver_mask_ = ( - (data == 26).astype(np.uint8) - + (data == 25).astype(np.uint8) - + (data == 1).astype(np.uint8) - ) - hepatic_tumor_vessel_liver_mask_ = (hepatic_tumor_vessel_liver_mask_ > 1).astype(np.uint8) - hepatic_tumor_vessel_liver_mask, _ = supress_non_largest_components( - hepatic_tumor_vessel_liver_mask_, [1], default_val=0 - ) - removed_region = ( - hepatic_tumor_vessel_liver_mask_ - hepatic_tumor_vessel_liver_mask - ).astype(np.bool_) - data[removed_region] = 200 - target_tumor = (target_tumor * hepatic_tumor_vessel_liver_mask).astype(np.bool_) - # refine liver - data[organ_fill_by_closing(data, target_label=1, device=device)] = 1 - data[organ_fill_by_closing(data, target_label=1, device=device)] = 1 - data[organ_fill_by_closing(data, target_label=1, device=device)] = 1 - - if target_tumor_label == 27 and np.sum(target_tumor) > 0: - # speical process for cases with colon tumor - dia_tumor_mask = ( - dilate_one_img( - torch.from_numpy((data == target_tumor_label)).to(device), - filter_size=3, - pad_value=0.0, - ) - .cpu() - .numpy() - ) - dia_tumor_mask = ( - dilate_one_img( - torch.from_numpy(dia_tumor_mask).to(device), filter_size=3, pad_value=0.0 - ) - .cpu() - .numpy() - ) - data[ - organ_fill_by_removed_mask( - data, - target_label=target_tumor_label, - remove_mask=dia_tumor_mask * organ_remove_mask, - device=device, - ) - ] = target_tumor_label - - if target_tumor_label == 129 and np.sum(target_tumor) > 0: - # speical process for cases with kidney tumor - for organ_label in [5, 14]: - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label - # TODO: current model does not support hepatic vessel by size control. - # we treat it as liver for better visiaulization - print( - "Current model does not support hepatic vessel by size control, " - "so we treat generated hepatic vessel as part of liver for better visiaulization." - ) - data[hepatic_vessel] = 1 - data[airway] = 132 - if target_tumor_label is not None: - data[target_tumor] = target_tumor_label - - return data - - -class MapLabelValue: - """ - Utility to map label values to another set of values. - For example, map [3, 2, 1] to [0, 1, 2], [1, 2, 3] -> [0.5, 1.5, 2.5], ["label3", "label2", "label1"] -> [0, 1, 2], - [3.5, 2.5, 1.5] -> ["label0", "label1", "label2"], etc. - The label data must be numpy array or array-like data and the output data will be numpy array. - - """ - - backend = [TransformBackends.NUMPY, TransformBackends.TORCH] - - def __init__( - self, orig_labels: Sequence, target_labels: Sequence, dtype: DtypeLike = np.float32 - ) -> None: - """ - Args: - orig_labels: original labels that map to others. - target_labels: expected label values, 1: 1 map to the `orig_labels`. - dtype: convert the output data to dtype, default to float32. - if dtype is from PyTorch, the transform will use the pytorch backend, else with numpy backend. - - """ - if len(orig_labels) != len(target_labels): - raise ValueError("orig_labels and target_labels must have the same length.") - - self.orig_labels = orig_labels - self.target_labels = target_labels - self.pair = tuple((o, t) for o, t in zip(self.orig_labels, self.target_labels) if o != t) - type_dtype = type(dtype) - if getattr(type_dtype, "__module__", "") == "torch": - self.use_numpy = False - self.dtype = get_equivalent_dtype(dtype, data_type=torch.Tensor) - else: - self.use_numpy = True - self.dtype = get_equivalent_dtype(dtype, data_type=np.ndarray) - - def __call__(self, img: NdarrayOrTensor): - """ - Apply the label mapping to the input image. - - Args: - img (NdarrayOrTensor): Input image to be remapped. - - Returns: - NdarrayOrTensor: Remapped image. - """ - if self.use_numpy: - img_np, *_ = convert_data_type(img, np.ndarray) - _out_shape = img_np.shape - img_flat = img_np.flatten() - try: - out_flat = img_flat.astype(self.dtype) - except ValueError: - # can't copy unchanged labels as the expected dtype is not supported, must map all the label values - out_flat = np.zeros(shape=img_flat.shape, dtype=self.dtype) - for o, t in self.pair: - out_flat[img_flat == o] = t - out_t = out_flat.reshape(_out_shape) - else: - img_t, *_ = convert_data_type(img, torch.Tensor) - out_t = img_t.detach().clone().to(self.dtype) # type: ignore - for o, t in self.pair: - out_t[img_t == o] = t - out, *_ = convert_to_dst_type(src=out_t, dst=img, dtype=self.dtype) - return out - - -def KL_loss(z_mu, z_sigma): - """ - Compute the Kullback-Leibler (KL) divergence loss for a variational autoencoder (VAE). - - The KL divergence measures how one probability distribution diverges from a second, expected probability distribution. - In the context of VAEs, this loss term ensures that the learned latent space distribution is close to a standard normal distribution. - - Args: - z_mu (torch.Tensor): Mean of the latent variable distribution, shape [N,C,H,W,D] or [N,C,H,W]. - z_sigma (torch.Tensor): Standard deviation of the latent variable distribution, same shape as 'z_mu'. - - Returns: - torch.Tensor: The computed KL divergence loss, averaged over the batch. - """ - eps = 1e-10 - kl_loss = 0.5 * torch.sum( - z_mu.pow(2) + z_sigma.pow(2) - torch.log(z_sigma.pow(2) + eps) - 1, - dim=list(range(1, len(z_sigma.shape))), - ) - return torch.sum(kl_loss) / kl_loss.shape[0] - - -def dynamic_infer(inferer, model, images): - """ - Perform dynamic inference using a model and an inferer, typically a monai SlidingWindowInferer. - - This function determines whether to use the model directly or to use the provided inferer - (such as a sliding window inferer) based on the size of the input images. - - Args: - inferer: An inference object, typically a monai SlidingWindowInferer, which handles patch-based inference. - model (torch.nn.Module): The model used for inference. - images (torch.Tensor): The input images for inference, shape [N,C,H,W,D] or [N,C,H,W]. - - Returns: - torch.Tensor: The output from the model or the inferer, depending on the input size. - """ - if torch.numel(images[0:1, 0:1, ...]) <= math.prod(inferer.roi_size): - return model(images) - else: - # Extract the spatial dimensions from the images tensor (H, W, D) - spatial_dims = images.shape[2:] - orig_roi = inferer.roi_size - - # Check that roi has the same number of dimensions as spatial_dims - if len(orig_roi) != len(spatial_dims): - raise ValueError( - f"ROI length ({len(orig_roi)}) does not match spatial dimensions ({len(spatial_dims)})." - ) - - # Iterate and adjust each ROI dimension - adjusted_roi = [min(roi_dim, img_dim) for roi_dim, img_dim in zip(orig_roi, spatial_dims)] - inferer.roi_size = adjusted_roi - output = inferer(network=model, inputs=images) - inferer.roi_size = orig_roi - return output diff --git a/itrialspace/src/itrialspace/synthesis/scripts/utils_plot.py b/itrialspace/src/itrialspace/synthesis/scripts/utils_plot.py deleted file mode 100644 index 7cd8a0ca79be57ebbbcacad8c507296881e7215b..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/scripts/utils_plot.py +++ /dev/null @@ -1,199 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and - - -import matplotlib.pyplot as plt -import numpy as np -import torch -import torch.nn.functional as F -from monai.transforms import AsDiscrete - - -def find_label_center_loc(x): - """ - Find the center location of non-zero elements in a binary mask. - - Args: - x (torch.Tensor): Binary mask tensor. Expected shape: [H, W, D] or [C, H, W, D]. - - Returns: - list: Center locations for each dimension. Each element is either - the middle index of non-zero locations or None if no non-zero elements exist. - """ - label_loc = torch.where(x != 0) - center_loc = [] - for loc in label_loc: - unique_loc = torch.unique(loc) - if len(unique_loc) == 0: - center_loc.append(None) - else: - center_loc.append(unique_loc[len(unique_loc) // 2]) - - return center_loc - - -def normalize_label_to_uint8(colorize, label, n_label): - """ - Normalize and colorize a label tensor to a uint8 image. - - Args: - colorize (torch.Tensor): Weight tensor for colorization. Expected shape: [3, n_label, 1, 1]. - label (torch.Tensor): Input label tensor. Expected shape: [1, H, W]. - n_label (int): Number of unique labels. - - Returns: - numpy.ndarray: Normalized and colorized image as uint8 numpy array. Shape: [H, W, 3]. - """ - with torch.no_grad(): - post_label = AsDiscrete(to_onehot=n_label) - label = post_label(label).permute(1, 0, 2, 3) - label = F.conv2d(label, weight=colorize) - label = torch.clip(label, 0, 1).squeeze().permute(1, 2, 0).cpu().numpy() - - draw_img = (label * 255).astype(np.uint8) - - return draw_img - - -def visualize_one_slice_in_3d( - image, axis: int = 2, center=None, mask_bool=True, n_label=105, colorize=None -): - """ - Extract and visualize a 2D slice from a 3D image or label tensor. - - Args: - image (torch.Tensor): Input 3D image or label tensor. Expected shape: [1, H, W, D]. - axis (int, optional): Axis along which to extract the slice (0, 1, or 2). Defaults to 2. - center (int, optional): Index of the slice to extract. If None, the middle slice is used. - mask_bool (bool, optional): If True, treat the input as a label mask and normalize it. Defaults to True. - n_label (int, optional): Number of labels in the mask. Used only if mask_bool is True. Defaults to 105. - colorize (torch.Tensor, optional): Colorization weights for label normalization. - Expected shape: [3, n_label, 1, 1] if provided. - - Returns: - numpy.ndarray: 2D slice of the input. If mask_bool is True, returns a normalized uint8 array - with shape [3, H, W]. Otherwise, returns a float32 array with shape [3, H, W]. - - Raises: - ValueError: If the specified axis is not 0, 1, or 2. - """ - # draw image - if center is None: - center = image.shape[2:][axis] // 2 - if axis == 0: - draw_img = image[..., center, :, :] - elif axis == 1: - draw_img = image[..., :, center, :] - elif axis == 2: - draw_img = image[..., :, :, center] - else: - raise ValueError("axis should be in [0,1,2]") - if mask_bool: - draw_img = normalize_label_to_uint8(colorize, draw_img, n_label) - else: - draw_img = draw_img.squeeze().cpu().numpy().astype(np.float32) - draw_img = np.stack((draw_img,) * 3, axis=-1) - return draw_img - - -def show_image(image, title="mask"): - """ - Plot and display an input image. - - Args: - image (numpy.ndarray): Image to be displayed. Expected shape: [H, W] for grayscale or [H, W, 3] for RGB. - title (str, optional): Title for the plot. Defaults to "mask". - """ - plt.figure("check", (24, 12)) - plt.subplot(1, 2, 1) - plt.title(title) - plt.imshow(image) - plt.show() - - -def to_shape(a, shape): - """ - Pad an image to a desired shape. - - This function pads a 3D numpy array (image) with zeros to reach the specified shape. - The padding is added equally on both sides of each dimension, with any odd padding - added to the end. - - Args: - a (numpy.ndarray): Input 3D array to be padded. Expected shape: [X, Y, Z]. - shape (tuple): Desired output shape as (x_, y_, z_). - - Returns: - numpy.ndarray: Padded array with the desired shape [x_, y_, z_]. - - Note: - If the input shape is larger than the desired shape in any dimension, - no padding is removed; the original size is maintained for that dimension. - Padding is done using numpy's pad function with 'constant' mode (zero-padding). - """ - x_, y_, z_ = shape - x, y, z = a.shape - x_pad = x_ - x - y_pad = y_ - y - z_pad = z_ - z - return np.pad( - a, - ( - (x_pad // 2, x_pad // 2 + x_pad % 2), - (y_pad // 2, y_pad // 2 + y_pad % 2), - (z_pad // 2, z_pad // 2 + z_pad % 2), - ), - mode="constant", - ) - - -def get_xyz_plot( - image, center_loc_axis, mask_bool=True, n_label=105, colorize=None, target_class_index=0 -): - """ - Generate a concatenated XYZ plot of 2D slices from a 3D image. - - This function creates visualizations of three orthogonal slices (XY, XZ, YZ) from a 3D image - and concatenates them into a single 2D image. - - Args: - image (torch.Tensor): Input 3D image tensor. Expected shape: [1, H, W, D]. - center_loc_axis (list): List of three integers specifying the center locations for each axis. - mask_bool (bool, optional): Whether to apply masking. Defaults to True. - n_label (int, optional): Number of labels for visualization. Defaults to 105. - colorize (torch.Tensor, optional): Colorization weights. Expected shape: [3, n_label, 1, 1] if provided. - target_class_index (int, optional): Index of the target class. Defaults to 0. - - Returns: - numpy.ndarray: Concatenated 2D image of the three orthogonal slices. Shape: [max(H,W,D), 3*max(H,W,D), 3]. - - Note: - The output image is padded to ensure all slices have the same dimensions. - """ - target_shape = list(image.shape[1:]) # [1,H,W,D] - img_list = [] - - for axis in range(3): - center = center_loc_axis[axis] - - img = visualize_one_slice_in_3d( - torch.flip(image.unsqueeze(0), [-3, -2, -1]), - axis, - center=center, - mask_bool=mask_bool, - n_label=n_label, - colorize=colorize, - ) - img = img.transpose([2, 1, 0]) - - img = to_shape(img, (3, max(target_shape), max(target_shape))) - img_list.append(img) - img = np.concatenate(img_list, axis=2).transpose([1, 2, 0]) - return img diff --git a/itrialspace/src/itrialspace/synthesis/tools/INTEGRATION_PLAN.md b/itrialspace/src/itrialspace/synthesis/tools/INTEGRATION_PLAN.md deleted file mode 100644 index 1742e96162f4373b9365af0108a64876a15a73d5..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/tools/INTEGRATION_PLAN.md +++ /dev/null @@ -1,337 +0,0 @@ -# iTrialSpace -> NodMAISI Integration Pipeline -## Technical Design & Implementation Plan - -> **Historical design note.** This is the original integration design document. Some -> component names, paths, and environment recipes (e.g. `module load miniconda`, -> `monai-auto3dseg`) predate the public-release monorepo layout. For the authoritative -> package layout, install, and run instructions see the top-level `docs/` — -> `docs/architecture.md`, `docs/installation.md`, and `docs/running_the_pipeline.md`. - ---- - -## 1. Integration Architecture (High-Level) - -``` -iTrialSpace Manifest Mask Insertion Engine NodMAISI -+------------------+ +---------------------------+ +------------------+ -| CohortManifest |--->| insert_manifest() |--->| Combined masks | -| (CSV, 9 modes) | | - placement | | (label 23 = | -| | | - resample | | nodule, uint8) | -+------------------+ | - label stamping (23) | +--------+---------+ - +---------------------------+ | - v - +---------------------------+ +------------------+ - | run_itrialspace_to_ct.py |<---| audit.json | - | | +------------------+ - | Per case: | - | 1. Load mask | - | 2. Canonicalize RAS+ | - | 3. Resize to valid dims | - | 4. Write dataset JSON | - | 5. Run NodMAISI infer | - | 6. Sanity checks | - | 7. QC PNGs | - | 8. Write audit | - +------------+--------------+ - | - v - +---------------------------+ - | generated_cts/ | - | mode1_.../ | - | case_0000/ | - | synthetic_ct.nii.gz | - | input_mask.nii.gz | - | host_ct.nii.gz -> | - | nodmaisi_audit.json | - | qc/ | - | qc_slice_*.png | - | case_0001/ | - | ... | - | pipeline_summary.json | - +---------------------------+ -``` - -### Data Flow - -| Stage | Input | Output | Tool | -|-------|-------|--------|------| -| 1. Manifest planning | Raw datasets, profiles | CohortManifest CSV | iTrialSpace | -| 2. Mask insertion | Manifest + host organ segs + donor masks | Combined masks (label 23) + audit.json | itrialspace_mask_inserter | -| 3. CT synthesis | Combined masks + audit.json | Synthetic CTs + QC | run_itrialspace_to_ct.py + NodMAISI | - ---- - -## 2. NodMAISI Input Requirements (Determined from Code Analysis) - -### 2.1 What NodMAISI Expects - -The ControlNet inference script (`infer_testV2_controlnet.py`) requires: - -1. **A dataset JSON** with structure: - ```json - {"testing": [{"label": "mask.nii.gz", "dim": [512,512,256], "spacing": [0.7,0.7,1.25]}]} - ``` - -2. **A segmentation label mask** (NIfTI, uint8) — this is the ControlNet conditioning input. - - Loaded via MONAI `LoadImaged`, oriented to RAS via `Orientationd(axcodes="RAS")` - - Converted to 8-channel binary via `binarize_labels()` (bitwise decomposition) - - The 8-bit binary representation is fed as `controlnet_cond` (shape: `[B, 8, H, W, D]`) - -3. **Label 23 = lung nodule/tumor** — this is the same label used by iTrialSpace! No remapping needed. - -4. **Spacing** is multiplied by 100 before being fed to the diffusion U-Net as a conditioning tensor. - -5. **Modality** = 1 (CT) as an integer class embedding. - -### 2.2 Size Constraints (from `check_input()`) - -- `dim[0] == dim[1]` (square axial slices), must be in `{256, 384, 512}` -- `dim[2]` must be in `{128, 256, 384, 512, 640, 768}` -- `spacing[0] == spacing[1]` (isotropic in-plane) -- The latent shape is `(4, dim[0]//4, dim[1]//4, dim[2]//4)` — all dims must be divisible by 4 - -### 2.3 Output Format - -- Synthetic CT in HU range `[-1000, 1000]` -- Background (where mask == 0) is set to -1000 HU -- Saved as NIfTI via MONAI `SaveImage` with `_image` postfix - ---- - -## 3. Geometry/Orientation Handling - -### 3.1 Preprocessing (mask -> NodMAISI input) - -The driver script `run_itrialspace_to_ct.py` performs: - -1. **Load mask** via nibabel -2. **Canonicalize to RAS+** via `nib.as_closest_canonical()` -3. **Snap dimensions** to nearest valid NodMAISI size: - - XY: nearest of {256, 384, 512} - - Z: nearest of {128, 256, 384, 512, 640, 768} -4. **Resize if needed** using `scipy.ndimage.zoom(order=0)` (nearest-neighbor for labels) -5. **Adjust spacing** proportionally: `new_spacing = old_spacing * old_dim / new_dim` -6. **Write** resized mask as uint8 NIfTI with diagonal affine - -### 3.2 Post-inference Geometry Check - -After NodMAISI inference: -- Verify synthetic CT shape matches the input mask shape -- Verify spacing consistency -- Check for NaN values -- Verify HU range is within [-1000, 1000] -- All recorded in per-case audit JSON - -### 3.3 No Back-Resampling Needed - -NodMAISI outputs in the same grid as the input mask. If the mask was resized, the synthetic CT is at the resized resolution. The original dimensions are recorded in the audit for downstream consumers that may need to resample back. - ---- - -## 4. Output Directory Structure - -``` -generated_cts/ -└── mode1_controlled_prevalence/ - ├── case_0000/ - │ ├── synthetic_ct.nii.gz # Generated CT [-1000, 1000] HU - │ ├── input_mask.nii.gz # Prepared mask (RAS+, resized) - │ ├── host_ct.nii.gz # Symlink to original host CT - │ ├── nodmaisi_audit.json # Per-case audit (params, timing, checks) - │ ├── dataset.json # NodMAISI dataset JSON (intermediate) - │ ├── _tmp_env.json # NodMAISI env config (intermediate) - │ └── qc/ - │ ├── qc_slice_00_z0118.png # Axial slice through nodule - │ ├── qc_slice_01_z0125.png - │ └── qc_slice_02_z0132.png - ├── case_0001/ - │ └── ... - └── pipeline_summary.json # Global run summary -``` - ---- - -## 5. File Naming Conventions - -| File | Convention | Source | -|------|-----------|--------| -| Case directory | `case_{case_id:04d}` | iTrialSpace case_id, zero-padded | -| Synthetic CT | `synthetic_ct.nii.gz` | Fixed name in config | -| Input mask | `input_mask.nii.gz` | Preprocessed copy of inserted mask | -| Host CT link | `host_ct.nii.gz` | Symlink to original | -| QC slices | `qc_slice_{idx:02d}_z{slice:04d}.png` | Axial slice index | -| Per-case audit | `nodmaisi_audit.json` | Fixed name in config | - ---- - -## 6. QC Outputs - -For each case, when QC is enabled: - -### PNG Montages -- 3 axial slices (configurable) through the nodule region -- Each PNG shows side-by-side panels: - - **Host CT** (if available) at the same slice - - **Synthetic CT + Mask overlay** (nodule label 23 in red) - - **Synthetic CT** alone -- Window: center=-600, width=1500 (lung window) - -### Audit JSON (per-case) -```json -{ - "case_id": "0042", - "status": "success", - "timestamp": "2026-03-06T14:32:15", - "input_mask_path": "/scratch/.../inserted_masks/.../mask.nii.gz", - "synthetic_ct_path": "/scratch/.../generated_cts/.../synthetic_ct.nii.gz", - "geometry": { - "original_dim": [412, 412, 262], - "original_spacing": [0.703, 0.703, 1.25], - "nodmaisi_dim": [384, 384, 256], - "nodmaisi_spacing": [0.754, 0.754, 1.28], - "resized": true - }, - "nodmaisi_params": { - "num_inference_steps": 30, - "noise_factor": 1.0, - "modality": 1, - "seed": 42 - }, - "timing": { - "prep_sec": 2.3, - "inference_sec": 185.7, - "qc_sec": 1.2, - "total_sec": 189.2 - }, - "sanity_checks": { - "shape_match": true, - "has_nodule_label": true, - "ct_min_hu": -1000.0, - "ct_max_hu": 812.3, - "has_nan": false - } -} -``` - ---- - -## 7. Runnable Commands - -### 7.1 Local Test — Single Case - -```bash -cd /home/ft42/NoMAISI -module load miniconda/py39_4.12.0 -source activate monai-auto3dseg -export MONAI_DATA_DIRECTORY=/home/ft42/NoMAISI/ -export PYTHONPATH=/home/ft42/NoMAISI:$PYTHONPATH - -# Dry run first (no GPU needed) -python tools/run_itrialspace_to_ct.py \ - --audit /scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json \ - --config tools/integration_config.yaml \ - --outdir /tmp/test_nodmaisi \ - --case-ids 0 \ - --dry-run -vv - -# Real inference (requires GPU) -python tools/run_itrialspace_to_ct.py \ - --audit /scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json \ - --config tools/integration_config.yaml \ - --outdir /scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/generated_cts/mode1_test \ - --case-ids 0 \ - -v -``` - -### 7.2 SLURM — All 9 Modes (sequential per mode) - -```bash -cd /home/ft42/NoMAISI/slurm_nodmaisi -mkdir -p logs - -# Dry run all modes -./submit_all_nodmaisi.sh --dry-run - -# Submit all modes -./submit_all_nodmaisi.sh - -# Submit selected modes -./submit_all_nodmaisi.sh 1 8 -``` - -### 7.3 SLURM — Array Job (one case per GPU task) - -```bash -cd /home/ft42/NoMAISI/slurm_nodmaisi - -# Step 1: Generate case list from audit -AUDIT=/scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json -python3 -c " -import json -audit = json.load(open('${AUDIT}')) -cases = sorted(set(str(r['case_id']) for r in audit['records'] if r['status']=='success')) -open('/tmp/mode1_controlled_prevalence_cases.txt','w').write('\n'.join(cases)) -print(f'{len(cases)} cases') -" - -# Step 2: Submit array job -N_CASES=$(wc -l < /tmp/mode1_controlled_prevalence_cases.txt) -sbatch --array=0-$((N_CASES - 1))%10 mode1_nodmaisi_array.sub -# ^^ max 10 concurrent GPU tasks -``` - -### 7.4 From Mask Directory (no audit) - -```bash -python tools/run_itrialspace_to_ct.py \ - --mask-root /scratch/.../inserted_masks/mode1_controlled_prevalence \ - --config tools/integration_config.yaml \ - --outdir /scratch/.../generated_cts/mode1 \ - -v -``` - ---- - -## 8. End-to-End Validation Checklist - -### Pre-flight -- [ ] NodMAISI model checkpoints exist at configured paths -- [ ] `monai-auto3dseg` conda environment is activated -- [ ] `MONAI_DATA_DIRECTORY` is set -- [ ] iTrialSpace mask insertion has completed (audit.json exists) -- [ ] GPU is available (`nvidia-smi` shows free VRAM) - -### Per-case Validation -- [ ] `input_mask.nii.gz` is RAS+ oriented, uint8 -- [ ] Mask dimensions match a valid NodMAISI size -- [ ] `dataset.json` is well-formed -- [ ] NodMAISI inference completes without error -- [ ] `synthetic_ct.nii.gz` exists and is non-empty -- [ ] Synthetic CT shape matches input mask shape -- [ ] CT intensity range is within [-1000, 1000] HU -- [ ] No NaN values in synthetic CT -- [ ] Mask contains label 23 (nodule voxels) -- [ ] QC PNGs show anatomically plausible CT with visible nodule -- [ ] `nodmaisi_audit.json` has all expected fields - -### Post-run -- [ ] `pipeline_summary.json` reports n_success > 0 -- [ ] Failed cases have clear error messages -- [ ] QC PNGs can be visually inspected for artifacts -- [ ] Synthetic CT can be loaded in ITK-SNAP or 3D Slicer - ---- - -## 9. Key Design Decisions - -1. **Subprocess invocation** — NodMAISI is called via `subprocess.run()` rather than Python import, to avoid namespace pollution, ensure clean GPU state between cases, and match the existing SLURM workflow. - -2. **Per-case dataset JSON** — Each case gets its own temporary `dataset.json` and `_tmp_env.json` to avoid modifying any shared NodMAISI config files. - -3. **Nearest-neighbor resize** — When mask dimensions don't match NodMAISI's valid sizes, we resize using order=0 (nearest) to preserve integer label values. Spacing is adjusted proportionally. - -4. **No changes to NodMAISI core** — All integration logic lives in `tools/` and `slurm_nodmaisi/`. The existing NodMAISI scripts and configs are untouched. - -5. **Label 23 alignment** — iTrialSpace's default nodule label (23) matches NodMAISI's lung tumor label (23). No label remapping is needed. This is the critical compatibility point. - -6. **Defensive processing** — Cases that fail are logged and skipped; processing continues. The summary report lists all failures. diff --git a/itrialspace/src/itrialspace/synthesis/tools/__init__.py b/itrialspace/src/itrialspace/synthesis/tools/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/synthesis/tools/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/tools/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 672f6aa17a0854239c13cb4f05aa8d0b0601982c..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/tools/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/tools/__pycache__/run_itrialspace_to_ct.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/tools/__pycache__/run_itrialspace_to_ct.cpython-310.pyc deleted file mode 100644 index 87e8a67d85251143bac84d009fead17fa9913954..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/synthesis/tools/__pycache__/run_itrialspace_to_ct.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml b/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml deleted file mode 100644 index 4613a38f94a484b31b23aa0c1b4cc61d41b1a063..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml +++ /dev/null @@ -1,76 +0,0 @@ -# ============================================================================ -# iTrialSpace -> NodMAISI Integration Pipeline — Configuration -# ============================================================================ - -# -- Paths to NodMAISI model components ----------------------------------- -# Paths use ${VAR} placeholders expanded by itrialspace.config.settings. -# Model weights are NOT bundled — set NODMAISI_MODELS_DIR to the directory holding -# autoencoder.pt / diffusion_unet.pt / controlnet *.pt (see docs/installation.md). -nodmaisi: - project_dir: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis - model_config: configs/config_maisi3d-rflow.json - controlnet_config: configs/infr_config_NoMAISI_controlnet.json - env_config: configs/infr_env_NoMAISI_DLCSD24_demo.json - # Model checkpoints (absolute via NODMAISI_MODELS_DIR, or relative to project_dir) - autoencoder_path: ${NODMAISI_MODELS_DIR}/autoencoder.pt - diffusion_unet_path: ${NODMAISI_MODELS_DIR}/diffusion_unet.pt - controlnet_path: ${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt - -# -- Inference parameters ------------------------------------------------- -inference: - num_inference_steps: 30 - autoencoder_sliding_window_infer_size: [80, 80, 64] - autoencoder_sliding_window_infer_overlap: 0.25 - noise_factor: 1.0 - modality: 1 # 1 = CT - seed: 42 - device: "cuda:0" - -# -- iTrialSpace mask parameters ------------------------------------------ -itrialspace: - nodule_label_value: 23 # Label value used by iTrialSpace for inserted nodules - # Base directory for resolving relative paths in iTrialSpace manifests/audits - base_dir: ${ITRIALSPACE_DATA_DIR} - # Root of iTrialSpace trial manifests (JSON/CSV with host_ct_path per case) - manifest_root: ${ITRIALSPACE_DATA_DIR}/manifests - -# -- Output structure ----------------------------------------------------- -output: - # Root for generated CTs. {trial_name} is substituted at runtime. - root: ${ITRIALSPACE_OUTPUT_DIR}/generated_cts - # Per-case subdirectory template - case_dir_template: "case_{case_id}" - # Filenames inside each case directory - synthetic_ct_name: synthetic_ct.nii.gz - input_mask_name: input_mask.nii.gz - host_ct_link_name: host_ct.nii.gz - qc_dir_name: qc - audit_name: nodmaisi_audit.json - -# -- QC settings ---------------------------------------------------------- -qc: - enabled: true - # Number of axial slices to render (evenly spaced through the nodule region) - num_slices: 3 - # Window level / width for CT display (HU) - window_center: -600 - window_width: 1500 - # PNG DPI - dpi: 150 - -# -- Geometry constraints (from NodMAISI check_input) --------------------- -geometry: - # Valid XY sizes for NodMAISI (first two dims must be equal) - valid_xy_sizes: [256, 384, 512] - # Valid Z sizes - valid_z_sizes: [128, 256, 384, 512, 640, 768] - # Target spacing for resampling if needed (null = use mask's native spacing) - target_spacing: null - # If true, resample mask to nearest valid size; if false, skip cases that don't fit - auto_resize: true - -# -- Conda / environment (for SLURM scripts) ----------------------------- -environment: - conda_module: "" - conda_env: ${ITRIALSPACE_CONDA_ENV} - monai_data_directory: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis diff --git a/itrialspace/src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py b/itrialspace/src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py deleted file mode 100644 index 128fca63a73d2f028e1c94856448c9a8b0acbfc5..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py +++ /dev/null @@ -1,1347 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -run_itrialspace_to_ct.py — Integration pipeline: iTrialSpace masks -> NodMAISI -> synthetic CTs. - -Reads an iTrialSpace CohortManifest (CSV/JSON) or a directory of inserted masks, -prepares NodMAISI-compatible inputs, runs ControlNet-conditioned CT synthesis, -and produces synthetic CTs with QC outputs. - -Usage: - # From manifest (reads host_ct_path, host_organ_seg_path, inserted mask from audit) - python tools/run_itrialspace_to_ct.py \\ - --manifest /path/to/manifest.csv \\ - --audit /path/to/audit.json \\ - --config tools/integration_config.yaml \\ - --outdir $ITRIALSPACE_DATA_DIR/.../generated_cts/mode1 \\ - --jobs 1 - - # From a directory of inserted masks - python tools/run_itrialspace_to_ct.py \\ - --mask-root $ITRIALSPACE_DATA_DIR/.../inserted_masks/mode1_controlled_prevalence \\ - --config tools/integration_config.yaml \\ - --outdir $ITRIALSPACE_DATA_DIR/.../generated_cts/mode1 - - # Dry-run (validate inputs, skip inference) - python tools/run_itrialspace_to_ct.py \\ - --audit /path/to/audit.json \\ - --config tools/integration_config.yaml \\ - --outdir /tmp/test --dry-run -""" -from __future__ import annotations - -import argparse -import gc -import json -import logging -import os -import sys -import time -from dataclasses import dataclass, field -from datetime import datetime - -import nibabel as nib -import numpy as np - -logger = logging.getLogger("itrialspace_to_ct") - -# --------------------------------------------------------------------------- -# Data structures -# --------------------------------------------------------------------------- - - -@dataclass -class CaseSpec: - """Specification for a single case to synthesize.""" - - case_id: str - mask_path: str # path to combined inserted mask (label map) - host_ct_path: str = "" # optional: for QC overlay / linking - dim: tuple = (512, 512, 256) # (X, Y, Z) volume dimensions - spacing: tuple = (0.7, 0.7, 1.25) # voxel spacing in mm - subdir: str = "" # subdirectory bucket (e.g., size_curve_10-15mm) - host_patient_id: str = "" - host_dataset: str = "" - donor_annotation_id: str = "" - trial_name: str = "" - - -@dataclass -class CaseResult: - """Result record for a single case.""" - - case_id: str = "" - status: str = "pending" # success | failed | skipped | dry_run - reason: str = "" - # Paths - input_mask_path: str = "" - host_ct_path: str = "" - synthetic_ct_path: str = "" - qc_png_paths: list = field(default_factory=list) - # Geometry - original_dim: tuple = () - original_spacing: tuple = () - nodmaisi_dim: tuple = () - nodmaisi_spacing: tuple = () - resized: bool = False - # Timing - prep_sec: float = 0.0 - inference_sec: float = 0.0 - qc_sec: float = 0.0 - total_sec: float = 0.0 - # Sanity checks - shape_match: bool = False - has_nodule_label: bool = False - ct_min_hu: float = 0.0 - ct_max_hu: float = 0.0 - has_nan: bool = False - - -# --------------------------------------------------------------------------- -# Configuration loader -# --------------------------------------------------------------------------- - - -def load_config(config_path: str) -> dict: - """Load YAML integration config, expanding ${VAR} placeholders portably.""" - from itrialspace.config import settings - - return settings.load_yaml(config_path) - - -# --------------------------------------------------------------------------- -# Case discovery -# --------------------------------------------------------------------------- - - -def _mask_stem(path: str) -> str: - """Derive a case ID from a mask filename. - - Strips ``_mask.nii.gz`` or ``.nii.gz`` suffix to produce a - human-readable, globally unique identifier. - """ - name = os.path.basename(path) - for suffix in ("_mask.nii.gz", ".nii.gz"): - if name.endswith(suffix): - return name[: -len(suffix)] - return name - - -def _build_host_ct_index(manifest_root: str) -> tuple[dict[str, str], dict[str, str]]: - """Build host CT lookup indices from manifest JSON/CSVs. - - Returns two dicts: - - **pid_index**: ``host_patient_id → host_ct_path`` - - **case_index**: ``"/" → host_ct_path`` - - The *pid_index* handles most datasets. The *case_index* is a fallback - for LUNA16 whose mask filenames use truncated hashes that don't match - the full DICOM UID stored as ``host_patient_id`` in the manifest. - """ - import glob as _glob - - pid_index: dict[str, str] = {} - case_index: dict[str, str] = {} - - def _ingest(records: list, trial_name: str): - for rec in records: - pid = str(rec.get("host_patient_id", "")) - hcp = str(rec.get("host_ct_path", "")) - cid = rec.get("case_id") - if not hcp: - continue - if pid: - pid_index[pid] = hcp - if trial_name and cid is not None: - case_index[f"{trial_name}/{int(cid)}"] = hcp - - # JSON manifests (structured, fast) - for jp in sorted(_glob.glob(os.path.join(manifest_root, "**", "*.json"), recursive=True)): - try: - with open(jp) as f: - data = json.load(f) - cases = data.get("cases") or data.get("records") or [] - tname = data.get("trial_name", "") - # If no trial_name field, infer from filename stem - if not tname: - tname = os.path.basename(jp).replace(".json", "") - _ingest(cases, tname) - except Exception: - continue - - # CSV manifests (supplement) - for cp in sorted(_glob.glob(os.path.join(manifest_root, "**", "*.csv"), recursive=True)): - try: - import pandas as pd - - df = pd.read_csv(cp) - tname = "" - if "trial_name" in df.columns: - tname = str(df["trial_name"].iloc[0]) - if not tname: - tname = os.path.basename(cp).replace(".csv", "") - for _, row in df.iterrows(): - rec = row.to_dict() - rec = {k: (str(v) if pd.notna(v) else "") for k, v in rec.items()} - pid = rec.get("host_patient_id", "") - hcp = rec.get("host_ct_path", "") - cid = rec.get("case_id") - if not hcp: - continue - if pid and pid not in pid_index: - pid_index[pid] = hcp - if tname and cid: - key = f"{tname}/{int(float(cid))}" - if key not in case_index: - case_index[key] = hcp - except Exception: - continue - - logger.info( - "Host-CT index: %d by patient-id, %d by trial/case from %s", - len(pid_index), - len(case_index), - manifest_root, - ) - return pid_index, case_index - - -def _parse_host_id(mask_stem: str) -> str: - """Extract the host patient ID from an iTrialSpace mask filename stem. - - Expects the ``--host---`` convention, e.g. - ``iTS--size_curve_10-15mm--C0000--host-DLCS_1092--src-DLCS24--nod-…`` - returns ``"DLCS_1092"``. Returns ``""`` if the pattern isn't found. - """ - import re - - m = re.search(r"--host-(.+?)--", mask_stem) - return m.group(1) if m else "" - - -def _parse_trial_case(mask_stem: str) -> tuple[str, str]: - """Extract (trial_name, integer_case_id) from an iTrialSpace mask filename. - - ``iTS--size_curve_10-15mm--C0036--host-…`` → ``("size_curve_10-15mm", "36")``. - Returns ``("", "")`` if either field isn't found. - """ - import re - - parts = mask_stem.split("--") - # parts: ["iTS", "size_curve_10-15mm", "C0036", "host-…", …] - trial = parts[1] if len(parts) > 1 else "" - cid_match = re.search(r"--C(\d+)--", mask_stem) - cid = str(int(cid_match.group(1))) if cid_match else "" - return trial, cid - - -def cases_from_audit(audit_path: str, cfg: dict) -> list[CaseSpec]: - """Build CaseSpecs from an iTrialSpace audit.json. - - If *audit_path* is a file, reads it directly. - If *audit_path* does not exist but its parent directory contains - sub-directory audit.json files, merge them all. - - Each case_id is the mask filename stem (without ``_mask.nii.gz``), - which is globally unique and self-documenting. - """ - audit_files: list[str] = [] - root_dir: str = "" - - if os.path.isfile(audit_path): - audit_files.append(audit_path) - root_dir = os.path.dirname(audit_path) - else: - # Try to discover audit.json files in subdirectories - parent = os.path.dirname(audit_path) - if os.path.isdir(parent): - import glob as _glob - - audit_files = sorted( - _glob.glob(os.path.join(parent, "**", "audit.json"), recursive=True) - ) - root_dir = parent - - if not audit_files: - logger.error("No audit.json found at %s or in subdirectories", audit_path) - return [] - - seen: dict[str, CaseSpec] = {} - for af in audit_files: - with open(af) as f: - audit = json.load(f) - - # Derive subdirectory name from the audit file's parent - af_dir = os.path.dirname(af) - subdir = os.path.basename(af_dir) if af_dir != root_dir else "" - - records = audit.get("records", []) - for rec in records: - if rec.get("status") != "success": - continue - - combined_path = rec.get("output_combined_path", "") - if not combined_path or not os.path.isfile(combined_path): - logger.warning( - "Case %s: combined mask not found at %s", rec.get("case_id"), combined_path - ) - continue - - cid = _mask_stem(combined_path) - if cid in seen: - continue - - try: - img = nib.load(combined_path) - img_can = nib.as_closest_canonical(img) - dim = tuple(int(d) for d in img_can.shape[:3]) - spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) - except Exception as e: - logger.warning("Case %s: cannot read mask header: %s", cid, e) - continue - - seen[cid] = CaseSpec( - case_id=cid, - mask_path=combined_path, - host_ct_path=rec.get("host_ct_path", ""), - dim=dim, - spacing=spacing, - subdir=subdir, - host_patient_id=rec.get("host_patient_id", ""), - host_dataset=rec.get("host_dataset", ""), - donor_annotation_id=rec.get("donor_annotation_id", ""), - trial_name=audit.get("trial_name", ""), - ) - - cases = list(seen.values()) - src = ( - audit_path if len(audit_files) == 1 else f"{len(audit_files)} audit files under {root_dir}" - ) - logger.info("Discovered %d cases from %s", len(cases), src) - return cases - - -def cases_from_mask_root(mask_root: str, cfg: dict) -> list[CaseSpec]: - """Build CaseSpecs by scanning a directory of inserted mask NIfTIs. - - Searches recursively so subdirectory layouts (per-bucket, per-lobe, etc.) - are handled automatically. Each case_id is the mask filename stem - (without ``_mask.nii.gz``), which is globally unique. - - Host CT paths are resolved from the iTrialSpace manifest JSON / CSV - files (``itrialspace.manifest_root`` in config). These manifests already - record ``host_ct_path`` for every case: - - 1. Look up by ``host_patient_id`` (parsed from ``--host---``). - 2. Fallback: look up by ``trial_name/case_id_int`` (parsed from - ``----C--``). Handles LUNA16 whose mask filenames - use truncated hashes instead of the full DICOM UID. - """ - import glob - - # Build host-CT lookup from manifests (JSON + CSV) - manifest_root = cfg.get("itrialspace", {}).get("manifest_root", "") - pid_index: dict[str, str] = {} - case_index: dict[str, str] = {} - if manifest_root and os.path.isdir(manifest_root): - pid_index, case_index = _build_host_ct_index(manifest_root) - - # Recursive search: finds masks in root *and* subdirectories - masks = sorted(glob.glob(os.path.join(mask_root, "**", "*.nii.gz"), recursive=True)) - - cases = [] - n_host_found = 0 - for mp in masks: - case_id = _mask_stem(mp) - # Derive subdir from relative path (empty if mask is at root) - mp_dir = os.path.dirname(mp) - subdir = os.path.basename(mp_dir) if mp_dir != mask_root else "" - - # Resolve host CT via manifest lookup - host_ct = "" - # Strategy 1: by host_patient_id - host_id = _parse_host_id(case_id) - if host_id and host_id in pid_index: - host_ct = pid_index[host_id] - # Strategy 2: by trial_name / integer case_id (handles LUNA16 hash IDs) - if not host_ct: - trial, cid_int = _parse_trial_case(case_id) - key = f"{trial}/{cid_int}" - if key in case_index: - host_ct = case_index[key] - if host_ct: - n_host_found += 1 - - try: - img = nib.load(mp) - img_can = nib.as_closest_canonical(img) - dim = tuple(int(d) for d in img_can.shape[:3]) - spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) - except Exception as e: - logger.warning("Skipping %s: %s", mp, e) - continue - - cases.append( - CaseSpec( - case_id=case_id, - mask_path=mp, - host_ct_path=host_ct, - dim=dim, - spacing=spacing, - subdir=subdir, - ) - ) - - logger.info( - "Discovered %d masks from %s (host CT resolved: %d/%d)", - len(cases), - mask_root, - n_host_found, - len(cases), - ) - return cases - - -def cases_from_manifest(manifest_path: str, mask_root: str, cfg: dict) -> list[CaseSpec]: - """Build CaseSpecs from an iTrialSpace CSV manifest + mask directory.""" - import pandas as pd - - df = pd.read_csv(manifest_path) - if "case_id" not in df.columns: - raise ValueError("Manifest must have a 'case_id' column") - - # Group by case_id, take first row per case - grouped = df.groupby("case_id", sort=False).first().reset_index() - cases = [] - for _, row in grouped.iterrows(): - cid = str(row["case_id"]) - # Try to find the combined mask in mask_root by pattern - import glob - - pattern = os.path.join(mask_root, f"*C{cid.zfill(4)}*_mask.nii.gz") - matches = glob.glob(pattern) - if not matches: - pattern2 = os.path.join(mask_root, f"*case{cid.zfill(4)}*") - matches = glob.glob(pattern2) - if not matches: - logger.warning("Case %s: no mask found in %s", cid, mask_root) - continue - mp = matches[0] - - try: - img = nib.load(mp) - img_can = nib.as_closest_canonical(img) - dim = tuple(int(d) for d in img_can.shape[:3]) - spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) - except Exception as e: - logger.warning("Case %s: cannot read %s: %s", cid, mp, e) - continue - - cases.append( - CaseSpec( - case_id=cid, - mask_path=mp, - host_ct_path=str(row.get("host_ct_path", "")), - dim=dim, - spacing=spacing, - host_patient_id=str(row.get("host_patient_id", "")), - host_dataset=str(row.get("host_dataset", "")), - donor_annotation_id=str(row.get("donor_annotation_id", "")), - trial_name=str(row.get("trial_name", "")), - ) - ) - logger.info("Discovered %d cases from manifest %s", len(cases), manifest_path) - return cases - - -# --------------------------------------------------------------------------- -# Geometry validation / adjustment -# --------------------------------------------------------------------------- - - -def snap_to_valid_size(dim: tuple, geom_cfg: dict, spacing: tuple | None = None) -> tuple: - """Snap volume dimensions to nearest valid NodMAISI size. - - If *spacing* is provided and the physical FOV in XY - (spacing[0] * dim[0]) is below the NodMAISI minimum (256 mm), - the smallest valid XY size whose grid alone meets the threshold - is chosen. This allows ``prepare_mask_for_nodmaisi`` to clamp - the spacing to the minimum FOV / snapped_dim, satisfying the - ``check_input`` guard. - """ - valid_xy = sorted(geom_cfg.get("valid_xy_sizes", [256, 384, 512])) - valid_z = sorted(geom_cfg.get("valid_z_sizes", [128, 256, 384, 512, 640, 768])) - min_fov_xy = geom_cfg.get("min_fov_xy_mm", 256) - - def _nearest(val, choices): - return min(choices, key=lambda c: abs(c - val)) - - xy = _nearest(dim[0], valid_xy) # NodMAISI requires dim[0] == dim[1] - - # If the original physical FOV is below the minimum, pick the - # smallest valid XY size so floor-spacing = min_fov / xy stays - # reasonable (closer to original spacing). - if spacing is not None and spacing[0] * dim[0] < min_fov_xy: - # Choose largest valid xy to keep adjusted spacing close to original - xy = valid_xy[-1] # 512 — safest bet for borderline CTs - - z = _nearest(dim[2], valid_z) - return (xy, xy, z) - - -def prepare_mask_for_nodmaisi( - case: CaseSpec, output_dir: str, geom_cfg: dict, nodule_label: int = 23 -) -> dict: - """Load mask, ensure RAS+ orientation, resize if needed, write dataset JSON. - - Returns dict with keys: label_path, dim, spacing, resized, original_dim. - """ - img = nib.load(case.mask_path) - img_can = nib.as_closest_canonical(img) - data = np.asarray(img_can.dataobj) - spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) - original_dim = data.shape[:3] - - target_dim = snap_to_valid_size(original_dim, geom_cfg, spacing=spacing) - resized = target_dim != original_dim - - if resized: - from scipy.ndimage import zoom as ndimage_zoom - - # NodMAISI requires isotropic XY spacing (spacing[0] == spacing[1]). - # When the original volume has non-square XY (dim_x != dim_y) and - # target_dim forces square XY, a naive resize creates anisotropic - # spacing. Fix: pad the shorter XY axis to match the longer one - # *before* resizing, so the zoom factor is identical for X and Y. - dx, dy, dz = data.shape[:3] - if dx != dy and target_dim[0] == target_dim[1]: - pad_dim = max(dx, dy) - pad_x = pad_dim - dx - pad_y = pad_dim - dy - # Symmetric padding (centered content) - px_before, px_after = pad_x // 2, pad_x - pad_x // 2 - py_before, py_after = pad_y // 2, pad_y - pad_y // 2 - data = np.pad( - data, - ((px_before, px_after), (py_before, py_after), (0, 0)), - mode="constant", - constant_values=0, - ) - logger.info( - "Padded non-square XY (%d,%d) -> (%d,%d) before resize " - "to preserve isotropic spacing.", - dx, - dy, - pad_dim, - pad_dim, - ) - original_dim = data.shape[:3] # update for zoom calculation - - zoom_factors = tuple(t / o for t, o in zip(target_dim, original_dim)) - # Use nearest-neighbor for label maps to preserve integer values - data_resized = ndimage_zoom(data.astype(np.float32), zoom_factors, order=0) - data = np.round(data_resized).astype(np.uint8) - # Adjust spacing proportionally - spacing = tuple(s * o / t for s, o, t in zip(spacing, original_dim, target_dim)) - - # NodMAISI requires spacing[0] == spacing[1] (exact equality). - # Source NIfTI headers sometimes store pixdim with float32 rounding, - # producing sp_x ≈ sp_y but not exactly equal. Force equality when - # the target grid is square. - if target_dim[0] == target_dim[1] and spacing[0] != spacing[1]: - avg_sp = (spacing[0] + spacing[1]) / 2.0 - spacing = (avg_sp, avg_sp, spacing[2]) - - # Ensure FOV meets NodMAISI's minimum (256 mm in XY). - # If the physical extent is still below the threshold after snapping - # (because the original CT was physically small), clamp spacing up so - # that target_dim[0] * spacing[0] >= min_fov. - min_fov_xy = geom_cfg.get("min_fov_xy_mm", 256) - fov_xy = target_dim[0] * spacing[0] - if fov_xy < min_fov_xy: - floor_sp = min_fov_xy / target_dim[0] - logger.warning( - "FOV too small (%.1f mm < %d mm). Clamping XY spacing " - "from %.4f to %.4f mm to satisfy NodMAISI constraint.", - fov_xy, - min_fov_xy, - spacing[0], - floor_sp, - ) - spacing = (floor_sp, floor_sp, spacing[2]) - - # Clamp Z spacing to NodMAISI's valid range [0.5, 5.0] mm. - # Ultra-thin-slice CTs (e.g. 0.27 mm) can produce z-spacing below - # the minimum after resizing to 256 slices. - sp_z = spacing[2] - if sp_z < 0.5: - logger.warning( - "Z spacing %.4f mm below minimum 0.5 mm; clamping to 0.5 mm.", - sp_z, - ) - spacing = (spacing[0], spacing[1], 0.5) - elif sp_z > 5.0: - logger.warning( - "Z spacing %.4f mm above maximum 5.0 mm; clamping to 5.0 mm.", - sp_z, - ) - spacing = (spacing[0], spacing[1], 5.0) - - # Save the prepared mask to the case output directory - os.makedirs(output_dir, exist_ok=True) - label_path = os.path.join(output_dir, "input_mask.nii.gz") - # Build a new affine with the (possibly adjusted) spacing - affine = np.diag(list(spacing) + [1.0]) - nib.save(nib.Nifti1Image(data.astype(np.uint8), affine), label_path) - - return { - "label_path": label_path, - "dim": list(target_dim), - "spacing": list(spacing), - "resized": resized, - "original_dim": list(original_dim), - } - - -def write_dataset_json(label_path: str, dim: list, spacing: list, output_dir: str) -> str: - """Write a NodMAISI-compatible dataset JSON for a single case.""" - # NodMAISI expects label path relative to data_base_dir - dataset = { - "name": "itrialspace_case", - "numTest": 1, - "testing": [ - { - "label": os.path.basename(label_path), - "fold": 0, - "dim": dim, - "spacing": spacing, - } - ], - } - json_path = os.path.join(output_dir, "dataset.json") - with open(json_path, "w") as f: - json.dump(dataset, f, indent=2) - return json_path - - -# --------------------------------------------------------------------------- -# NodMAISI inference wrapper -# --------------------------------------------------------------------------- - -# Default and fallback sliding-window sizes for autoencoder inference. -# If the first attempt OOMs or produces no output, retry with the smaller size. -_DEFAULT_AE_WINDOW = [80, 80, 64] -_FALLBACK_AE_WINDOW = [64, 64, 48] - - -def validate_condition_mask(label_path: str, cfg: dict) -> dict: - """Pre-NodMAISI QC gate — validate the prepared condition mask. - - Checks: - 1. File exists and is readable. - 2. Mask has the expected nodule label (default 23). - 3. Dimensions match a valid NodMAISI size. - 4. No NaN/Inf values. - 5. Nodule label occupies a physically plausible volume. - - Returns a dict: ``{"ok": bool, "reason": str, "details": dict}``. - """ - nodule_label = cfg.get("itrialspace", {}).get("nodule_label_value", 23) - geom_cfg = cfg.get("geometry", {}) - valid_xy = set(geom_cfg.get("valid_xy_sizes", [256, 384, 512])) - valid_z = set(geom_cfg.get("valid_z_sizes", [128, 256, 384, 512, 640, 768])) - - details: dict = {} - try: - img = nib.load(label_path) - data = np.asarray(img.dataobj) - details["shape"] = list(data.shape[:3]) - details["dtype"] = str(data.dtype) - except Exception as e: - return {"ok": False, "reason": f"Cannot read mask: {e}", "details": details} - - # 1) NaN / Inf check - if np.any(np.isnan(data)) or np.any(np.isinf(data)): - return {"ok": False, "reason": "Mask contains NaN or Inf values", "details": details} - - # 2) Dimension validity - dim = data.shape[:3] - if dim[0] != dim[1]: - return { - "ok": False, - "reason": f"X/Y dimensions differ ({dim[0]} vs {dim[1]}); NodMAISI requires square XY", - "details": details, - } - if dim[0] not in valid_xy: - return { - "ok": False, - "reason": f"XY size {dim[0]} not in valid set {sorted(valid_xy)}", - "details": details, - } - if dim[2] not in valid_z: - return { - "ok": False, - "reason": f"Z size {dim[2]} not in valid set {sorted(valid_z)}", - "details": details, - } - - # 3) Nodule label presence - n_nodule_vox = int(np.sum(data == nodule_label)) - details["n_nodule_voxels"] = n_nodule_vox - if n_nodule_vox == 0: - return { - "ok": False, - "reason": f"Mask contains no voxels with nodule label {nodule_label}", - "details": details, - } - - # 4) Plausibility: nodule should be < 10% of total volume - total_voxels = int(np.prod(dim)) - ratio = n_nodule_vox / total_voxels if total_voxels > 0 else 1.0 - details["nodule_volume_ratio"] = round(ratio, 6) - if ratio > 0.10: - return { - "ok": False, - "reason": f"Nodule label occupies {ratio:.1%} of volume (>10%); likely corrupt mask", - "details": details, - } - - return {"ok": True, "reason": "", "details": details} - - -def run_nodmaisi_inference( - case_dir: str, - dataset_json: str, - cfg: dict, - dry_run: bool = False, - ae_window: list | None = None, -) -> str | None: - """Run NodMAISI inference for a single case via subprocess. - - Parameters - ---------- - ae_window : list, optional - Override autoencoder_sliding_window_infer_size for this run. - Used by the retry path to reduce memory pressure. - - Returns the path to the generated synthetic CT, or None on failure. - """ - nodmaisi_cfg = cfg["nodmaisi"] - infer_cfg = cfg["inference"] - project_dir = nodmaisi_cfg["project_dir"] - - # Build a temporary environment config that points to this case's data - env_override = { - "model_dir": os.path.join(project_dir, "models") + "/", - "output_dir": case_dir, - "tfevent_path": os.path.join(case_dir, "tfevent"), - "trained_autoencoder_path": _resolve_path(nodmaisi_cfg["autoencoder_path"], project_dir), - "trained_diffusion_path": _resolve_path(nodmaisi_cfg["diffusion_unet_path"], project_dir), - "trained_controlnet_path": _resolve_path(nodmaisi_cfg["controlnet_path"], project_dir), - "exp_name": "iTS_case", - "data_base_dir": [case_dir], - "json_data_list": [dataset_json], - } - - # Apply sliding-window override for retry / reduced-memory runs - effective_window = ae_window or infer_cfg.get( - "autoencoder_sliding_window_infer_size", _DEFAULT_AE_WINDOW - ) - env_override["autoencoder_sliding_window_infer_size"] = effective_window - - # Write temporary env config - tmp_env_path = os.path.join(case_dir, "_tmp_env.json") - with open(tmp_env_path, "w") as f: - json.dump(env_override, f, indent=2) - - model_config = _resolve_path(nodmaisi_cfg["model_config"], project_dir) - controlnet_config = _resolve_path(nodmaisi_cfg["controlnet_config"], project_dir) - - if dry_run: - logger.info("[DRY RUN] Would run NodMAISI with env=%s", tmp_env_path) - return None - - import subprocess - - cmd = [ - sys.executable, - "-m", - "scripts.infer_testV2_controlnet", - "-c", - model_config, - "-e", - tmp_env_path, - "-t", - controlnet_config, - ] - - env = os.environ.copy() - env["MONAI_DATA_DIRECTORY"] = project_dir - - logger.info("Running NodMAISI: %s", " ".join(cmd)) - result = subprocess.run( - cmd, - capture_output=True, - text=True, - cwd=project_dir, - env=env, - timeout=3600, - ) - - if result.returncode != 0: - logger.error( - "NodMAISI failed (rc=%d):\nSTDOUT: %s\nSTDERR: %s", - result.returncode, - result.stdout[-2000:], - result.stderr[-2000:], - ) - # Persist stderr for structured failure diagnostics - stderr_path = os.path.join(case_dir, "_last_stderr.txt") - with open(stderr_path, "w") as f: - f.write(result.stderr[-4000:] if result.stderr else "") - return None - - # Find the generated image in case_dir (MONAI SaveImage appends _image suffix) - import glob - - candidates = glob.glob(os.path.join(case_dir, "*_image.nii.gz")) - if not candidates: - candidates = glob.glob(os.path.join(case_dir, "*.nii.gz")) - candidates = [ - c - for c in candidates - if "input_mask" not in c and "dataset" not in c and "_label" not in c - ] - - if candidates: - # Rename to standard name - out_cfg = cfg.get("output", {}) - final_name = out_cfg.get("synthetic_ct_name", "synthetic_ct.nii.gz") - final_path = os.path.join(case_dir, final_name) - os.rename(candidates[0], final_path) - return final_path - - logger.error("No synthetic CT found in %s after inference", case_dir) - # Persist stderr even on rc=0 for diagnostic purposes - stderr_path = os.path.join(case_dir, "_last_stderr.txt") - with open(stderr_path, "w") as f: - f.write(result.stderr[-4000:] if result.stderr else "") - return None - - -def _resolve_path(p: str, base: str) -> str: - """Resolve a possibly relative path against a base directory.""" - if os.path.isabs(p): - return p - return os.path.join(base, p) - - -# --------------------------------------------------------------------------- -# QC: PNG generation -# --------------------------------------------------------------------------- - - -def generate_qc( - case_dir: str, - synthetic_ct_path: str, - mask_path: str, - host_ct_path: str, - cfg: dict, - nodule_label: int = 23, -) -> list[str]: - """Generate QC PNG montages showing host CT, mask overlay, and synthetic CT.""" - qc_cfg = cfg.get("qc", {}) - if not qc_cfg.get("enabled", True): - return [] - - try: - import matplotlib - - matplotlib.use("Agg") - import matplotlib.pyplot as plt - - except ImportError: - logger.warning("matplotlib not available; skipping QC PNGs") - return [] - - num_slices = qc_cfg.get("num_slices", 3) - wc = qc_cfg.get("window_center", -600) - ww = qc_cfg.get("window_width", 1500) - dpi = qc_cfg.get("dpi", 150) - vmin, vmax = wc - ww / 2, wc + ww / 2 - - qc_dir = os.path.join(case_dir, cfg.get("output", {}).get("qc_dir_name", "qc")) - os.makedirs(qc_dir, exist_ok=True) - - # Load volumes - synth_data = np.asarray(nib.as_closest_canonical(nib.load(synthetic_ct_path)).dataobj) - mask_data = np.asarray(nib.as_closest_canonical(nib.load(mask_path)).dataobj) - - has_host = host_ct_path and os.path.isfile(host_ct_path) - if has_host: - try: - host_data = np.asarray(nib.as_closest_canonical(nib.load(host_ct_path)).dataobj) - except Exception: - has_host = False - host_data = None - else: - host_data = None - - # Find axial slices that contain nodule label - nodule_slices = np.where(np.any(mask_data == nodule_label, axis=(0, 1)))[0] - if len(nodule_slices) == 0: - # Fallback: evenly spaced slices through the volume - nodule_slices = np.linspace(0, synth_data.shape[2] - 1, num_slices + 2, dtype=int)[1:-1] - else: - # Pick evenly spaced slices through the nodule Z-range - indices = np.linspace(0, len(nodule_slices) - 1, num_slices, dtype=int) - nodule_slices = nodule_slices[indices] - - png_paths = [] - for si, k in enumerate(nodule_slices): - ncols = 3 if has_host else 2 - fig, axes = plt.subplots(1, ncols, figsize=(5 * ncols, 5)) - - col = 0 - if has_host: - axes[col].imshow( - host_data[:, :, k].T, - cmap="gray", - vmin=vmin, - vmax=vmax, - origin="lower", - aspect="equal", - ) - axes[col].set_title(f"Host CT (z={k})") - axes[col].axis("off") - col += 1 - - # Mask overlay on synthetic CT - axes[col].imshow( - synth_data[:, :, k].T, cmap="gray", vmin=vmin, vmax=vmax, origin="lower", aspect="equal" - ) - nodule_overlay = np.ma.masked_where(mask_data[:, :, k] != nodule_label, mask_data[:, :, k]) - axes[col].imshow(nodule_overlay.T, cmap="autumn", alpha=0.5, origin="lower", aspect="equal") - axes[col].set_title(f"Synth CT + Mask (z={k})") - axes[col].axis("off") - col += 1 - - # Synthetic CT alone - axes[col].imshow( - synth_data[:, :, k].T, cmap="gray", vmin=vmin, vmax=vmax, origin="lower", aspect="equal" - ) - axes[col].set_title(f"Synthetic CT (z={k})") - axes[col].axis("off") - - png_name = f"qc_slice_{si:02d}_z{k:04d}.png" - png_path = os.path.join(qc_dir, png_name) - fig.tight_layout() - fig.savefig(png_path, dpi=dpi, bbox_inches="tight") - plt.close(fig) - png_paths.append(png_path) - - return png_paths - - -# --------------------------------------------------------------------------- -# Sanity checks -# --------------------------------------------------------------------------- - - -def sanity_check(synthetic_ct_path: str, mask_path: str, nodule_label: int = 23) -> dict: - """Run sanity checks on the synthetic CT.""" - checks = { - "shape_match": False, - "has_nodule_label": False, - "ct_min_hu": 0.0, - "ct_max_hu": 0.0, - "has_nan": False, - } - try: - ct_img = nib.load(synthetic_ct_path) - ct_data = np.asarray(ct_img.dataobj) - mask_img = nib.load(mask_path) - mask_data = np.asarray(mask_img.dataobj) - - checks["shape_match"] = ct_data.shape[:3] == mask_data.shape[:3] - checks["has_nodule_label"] = bool(np.any(mask_data == nodule_label)) - checks["ct_min_hu"] = float(np.nanmin(ct_data)) - checks["ct_max_hu"] = float(np.nanmax(ct_data)) - checks["has_nan"] = bool(np.any(np.isnan(ct_data))) - except Exception as e: - logger.error("Sanity check failed: %s", e) - return checks - - -# --------------------------------------------------------------------------- -# Per-case orchestrator -# --------------------------------------------------------------------------- - - -def process_one_case(case: CaseSpec, cfg: dict, outdir: str, dry_run: bool = False) -> CaseResult: - """Full pipeline for a single case: prepare -> infer -> QC -> audit.""" - t0 = time.time() - result = CaseResult( - case_id=case.case_id, input_mask_path=case.mask_path, host_ct_path=case.host_ct_path - ) - - out_cfg = cfg.get("output", {}) - # Mirror input subdirectory structure: subdir/case_id - if case.subdir: - case_dir = os.path.join(outdir, case.subdir, case.case_id) - else: - case_dir = os.path.join(outdir, case.case_id) - os.makedirs(case_dir, exist_ok=True) - - geom_cfg = cfg.get("geometry", {}) - nodule_label = cfg.get("itrialspace", {}).get("nodule_label_value", 23) - - # --- Step 1: Prepare mask --- - t_prep = time.time() - try: - prep = prepare_mask_for_nodmaisi(case, case_dir, geom_cfg, nodule_label) - except Exception as e: - result.status = "failed" - result.reason = f"Mask preparation failed: {e}" - result.total_sec = time.time() - t0 - return result - - result.original_dim = tuple(prep["original_dim"]) - result.original_spacing = tuple(case.spacing) - result.nodmaisi_dim = tuple(prep["dim"]) - result.nodmaisi_spacing = tuple(prep["spacing"]) - result.resized = prep["resized"] - - dataset_json = write_dataset_json(prep["label_path"], prep["dim"], prep["spacing"], case_dir) - result.prep_sec = time.time() - t_prep - - # --- Step 1b: Pre-NodMAISI QC gate (validate condition mask) --- - qc_gate = validate_condition_mask(prep["label_path"], cfg) - if not qc_gate["ok"]: - result.status = "failed" - result.reason = f"Pre-NodMAISI QC gate rejected mask: {qc_gate['reason']}" - result.total_sec = time.time() - t0 - return result - - # --- Step 2: Symlink host CT (optional) --- - if case.host_ct_path and os.path.isfile(case.host_ct_path): - link_name = out_cfg.get("host_ct_link_name", "host_ct.nii.gz") - link_path = os.path.join(case_dir, link_name) - if not os.path.exists(link_path): - try: - os.symlink(case.host_ct_path, link_path) - except OSError: - pass # skip if symlinking not supported - - # --- Step 3: Run NodMAISI inference --- - if dry_run: - result.status = "dry_run" - result.reason = "Dry run — inference skipped" - result.total_sec = time.time() - t0 - return result - - t_infer = time.time() - synthetic_ct_path = run_nodmaisi_inference(case_dir, dataset_json, cfg) - result.inference_sec = time.time() - t_infer - - # Retry with smaller sliding window if first attempt produced no output - if synthetic_ct_path is None: - infer_cfg = cfg.get("inference", {}) - current_window = infer_cfg.get("autoencoder_sliding_window_infer_size", _DEFAULT_AE_WINDOW) - if current_window != _FALLBACK_AE_WINDOW: - logger.warning( - "Case %s: first attempt produced no output, retrying with " - "reduced sliding window %s → %s", - case.case_id, - current_window, - _FALLBACK_AE_WINDOW, - ) - t_retry = time.time() - synthetic_ct_path = run_nodmaisi_inference( - case_dir, - dataset_json, - cfg, - ae_window=_FALLBACK_AE_WINDOW, - ) - retry_sec = time.time() - t_retry - result.inference_sec += retry_sec - if synthetic_ct_path is not None: - logger.info( - "Case %s: retry succeeded with reduced window (%.1fs)", - case.case_id, - retry_sec, - ) - - if synthetic_ct_path is None: - # Collect structured diagnostics for the failure - diag: dict = {"case_id": case.case_id} - try: - diag["mask_dim"] = list(result.nodmaisi_dim) - diag["mask_spacing"] = list(result.nodmaisi_spacing) - diag["mask_resized"] = result.resized - # Check for GPU memory info - try: - import torch - - if torch.cuda.is_available(): - diag["gpu_mem_allocated_MB"] = round(torch.cuda.memory_allocated() / 1e6, 1) - diag["gpu_mem_reserved_MB"] = round(torch.cuda.memory_reserved() / 1e6, 1) - diag["gpu_name"] = torch.cuda.get_device_name(0) - except Exception: - pass - # Log stderr tail from last subprocess run - last_stderr_path = os.path.join(case_dir, "_last_stderr.txt") - if os.path.isfile(last_stderr_path): - with open(last_stderr_path) as f: - diag["stderr_tail"] = f.read()[-2000:] - except Exception: - pass - - # Write structured failure log - fail_log_path = os.path.join(case_dir, "nodmaisi_failure.json") - with open(fail_log_path, "w") as f: - json.dump(diag, f, indent=2, default=str) - - result.status = "failed" - result.reason = ( - f"NodMAISI inference produced no output " - f"(dim={list(result.nodmaisi_dim)}, retried={current_window != _FALLBACK_AE_WINDOW})" - ) - result.total_sec = time.time() - t0 - return result - - result.synthetic_ct_path = synthetic_ct_path - - # --- Step 4: Sanity checks --- - checks = sanity_check(synthetic_ct_path, prep["label_path"], nodule_label) - result.shape_match = checks["shape_match"] - result.has_nodule_label = checks["has_nodule_label"] - result.ct_min_hu = checks["ct_min_hu"] - result.ct_max_hu = checks["ct_max_hu"] - result.has_nan = checks["has_nan"] - - # --- Step 5: QC PNGs --- - t_qc = time.time() - try: - result.qc_png_paths = generate_qc( - case_dir, synthetic_ct_path, prep["label_path"], case.host_ct_path, cfg, nodule_label - ) - except Exception as e: - logger.warning("QC generation failed for case %s: %s", case.case_id, e) - result.qc_sec = time.time() - t_qc - - result.status = "success" - result.total_sec = time.time() - t0 - return result - - -# --------------------------------------------------------------------------- -# Write per-case audit JSON -# --------------------------------------------------------------------------- - - -def write_case_audit(result: CaseResult, case_dir: str, cfg: dict): - """Write a per-case NodMAISI audit JSON.""" - audit = { - "case_id": result.case_id, - "status": result.status, - "reason": result.reason, - "timestamp": datetime.now().isoformat(), - "input_mask_path": result.input_mask_path, - "host_ct_path": result.host_ct_path, - "synthetic_ct_path": result.synthetic_ct_path, - "geometry": { - "original_dim": result.original_dim, - "original_spacing": result.original_spacing, - "nodmaisi_dim": result.nodmaisi_dim, - "nodmaisi_spacing": result.nodmaisi_spacing, - "resized": result.resized, - }, - "nodmaisi_params": { - "num_inference_steps": cfg.get("inference", {}).get("num_inference_steps", 30), - "noise_factor": cfg.get("inference", {}).get("noise_factor", 1.0), - "modality": cfg.get("inference", {}).get("modality", 1), - "seed": cfg.get("inference", {}).get("seed", 42), - "autoencoder_sliding_window_infer_size": cfg.get("inference", {}).get( - "autoencoder_sliding_window_infer_size", [80, 80, 64] - ), - }, - "timing": { - "prep_sec": round(result.prep_sec, 2), - "inference_sec": round(result.inference_sec, 2), - "qc_sec": round(result.qc_sec, 2), - "total_sec": round(result.total_sec, 2), - }, - "sanity_checks": { - "shape_match": result.shape_match, - "has_nodule_label": result.has_nodule_label, - "ct_min_hu": round(result.ct_min_hu, 1), - "ct_max_hu": round(result.ct_max_hu, 1), - "has_nan": result.has_nan, - }, - "qc_pngs": result.qc_png_paths, - } - audit_name = cfg.get("output", {}).get("audit_name", "nodmaisi_audit.json") - audit_path = os.path.join(case_dir, audit_name) - with open(audit_path, "w") as f: - json.dump(audit, f, indent=2, default=str) - - -# --------------------------------------------------------------------------- -# Main -# --------------------------------------------------------------------------- - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - prog="run_itrialspace_to_ct", - description="iTrialSpace masks -> NodMAISI -> synthetic CTs", - ) - parser.add_argument("--manifest", "-m", help="iTrialSpace manifest CSV") - parser.add_argument("--audit", "-a", help="iTrialSpace audit.json (preferred)") - parser.add_argument("--mask-root", help="Directory of inserted mask NIfTIs") - parser.add_argument("--config", "-c", required=True, help="Integration config YAML") - parser.add_argument("--outdir", "-o", required=True, help="Output directory") - parser.add_argument("--jobs", "-j", type=int, default=1, help="Parallelism (future)") - parser.add_argument("--dry-run", action="store_true", help="Validate only, no inference") - parser.add_argument("--verbose", "-v", action="count", default=0) - parser.add_argument("--case-ids", nargs="*", help="Process only these case IDs") - - args = parser.parse_args(argv) - - # Logging - level = logging.WARNING - if args.verbose == 1: - level = logging.INFO - elif args.verbose >= 2: - level = logging.DEBUG - logging.basicConfig( - level=level, - format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", - datefmt="%H:%M:%S", - ) - - cfg = load_config(args.config) - - # --- Discover cases --- - if args.audit: - cases = cases_from_audit(args.audit, cfg) - elif args.mask_root: - cases = cases_from_mask_root(args.mask_root, cfg) - elif args.manifest and args.mask_root: - cases = cases_from_manifest(args.manifest, args.mask_root, cfg) - elif args.manifest: - # Need mask_root too if not using audit - parser.error("--manifest requires --mask-root to locate combined masks") - return 1 - else: - parser.error("Provide --audit, --mask-root, or --manifest + --mask-root") - return 1 - - # Filter by case IDs if specified - if args.case_ids: - id_set = set(args.case_ids) - cases = [c for c in cases if c.case_id in id_set] - - if not cases: - logger.error("No cases found. Check input paths.") - return 1 - - os.makedirs(args.outdir, exist_ok=True) - - # --- Process cases --- - results = [] - t_total = time.time() - for i, case in enumerate(cases): - logger.info("=== Case %d/%d: %s ===", i + 1, len(cases), case.case_id) - result = process_one_case(case, cfg, args.outdir, dry_run=args.dry_run) - results.append(result) - - # Write per-case audit - if case.subdir: - case_dir = os.path.join(args.outdir, case.subdir, case.case_id) - else: - case_dir = os.path.join(args.outdir, case.case_id) - write_case_audit(result, case_dir, cfg) - - logger.info(" Status: %s Time: %.1fs", result.status, result.total_sec) - - # Free GPU memory between cases - gc.collect() - try: - import torch - - torch.cuda.empty_cache() - except Exception: - pass - - # --- Summary report --- - elapsed = time.time() - t_total - n_ok = sum(1 for r in results if r.status == "success") - n_fail = sum(1 for r in results if r.status == "failed") - n_dry = sum(1 for r in results if r.status == "dry_run") - - print(f"\n{'=' * 60}") - print(f" iTrialSpace -> NodMAISI Pipeline {'DRY RUN' if args.dry_run else 'COMPLETE'}") - print(f"{'=' * 60}") - print(f" Total cases: {len(results)}") - print(f" Success: {n_ok}") - print(f" Failed: {n_fail}") - if n_dry: - print(f" Dry-run: {n_dry}") - print(f" Elapsed: {elapsed:.1f}s") - print(f" Output dir: {args.outdir}") - - if n_fail > 0: - print("\nFailed cases:") - for r in results: - if r.status == "failed": - print(f" case {r.case_id}: {r.reason}") - - # Write summary — use per-case path for single-case (array job) runs - # to avoid race conditions when many tasks write to the same outdir. - summary = { - "pipeline": "itrialspace_to_nodmaisi", - "timestamp": datetime.now().isoformat(), - "total_cases": len(results), - "n_success": n_ok, - "n_failed": n_fail, - "n_dry_run": n_dry, - "elapsed_sec": round(elapsed, 1), - "config": args.config, - "cases": [ - { - "case_id": r.case_id, - "status": r.status, - "reason": r.reason, - "synthetic_ct": r.synthetic_ct_path, - "total_sec": round(r.total_sec, 2), - } - for r in results - ], - } - if len(results) == 1: - # Array-job mode: write per-case summary inside the case output dir - # Check flat layout first, then sub-bin layout - case_dir = os.path.join(args.outdir, results[0].case_id) - if not os.path.isdir(case_dir): - # Search sub-directories for the case (sub-bin layout) - for entry in os.listdir(args.outdir) if os.path.isdir(args.outdir) else []: - candidate = os.path.join(args.outdir, entry, results[0].case_id) - if os.path.isdir(candidate): - case_dir = candidate - break - if os.path.isdir(case_dir): - summary_path = os.path.join(case_dir, "pipeline_summary.json") - else: - summary_path = os.path.join(args.outdir, "pipeline_summary.json") - else: - summary_path = os.path.join(args.outdir, "pipeline_summary.json") - with open(summary_path, "w") as f: - json.dump(summary, f, indent=2, default=str) - - return 1 if n_fail > 0 and n_ok == 0 else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/itrialspace/src/itrialspace/trials/__init__.py b/itrialspace/src/itrialspace/trials/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/trials/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/trials/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 7f4df1770ffe6cf69d39e8ff75c24b175c1f01b9..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/trials/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/trials/__pycache__/run_trial.cpython-310.pyc b/itrialspace/src/itrialspace/trials/__pycache__/run_trial.cpython-310.pyc deleted file mode 100644 index c0391dfb36bcdd5d7b1f1762fdcf9b6d64e3d48a..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/trials/__pycache__/run_trial.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/src/itrialspace/trials/run_trial.py b/itrialspace/src/itrialspace/trials/run_trial.py deleted file mode 100644 index 0a37747f45b77420f413a219b664942fe0ef3209..0000000000000000000000000000000000000000 --- a/itrialspace/src/itrialspace/trials/run_trial.py +++ /dev/null @@ -1,669 +0,0 @@ -#!/usr/bin/env python3 -""" -iTrialSpace Trial Runner — builds a cohort manifest from a trial mode. - -Usage: - python run_trial.py --mode [OPTIONS] - -Modes: - 1 controlled_prevalence Fixed malignancy prevalence - 2 size_detection_curve One cohort per size bucket (FROC) - 3 location_sensitivity One cohort per lobe - 4 demographic_strat Cohorts by demographic strata - 5 counterfactual Same cohort, one parameter varied - 6 cross_dataset One cohort per dataset as sole donor - 7 bootstrap_confidence N bootstrap replicates of a base cohort - 8 algorithm_comparison Single standardised cohort for comparing models - 9 screening_simulation Multi-round screening protocol - 10 multi_nodule Single vs multi-nodule sub-cohorts - 11 digital_twin_isolation Per-nodule isolation within host anatomy - 12 digital_twin_complete Full multi-nodule digital twin per CT scan - 13 digital_twin_cross Cross-patient host anatomy + donor nodules - -All manifests are written to --output-dir (default: ./output/). -""" -from __future__ import annotations - -import argparse -import json -import os -import sys -import time - -# Add itrialspace to path -ITRIALSPACE_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -sys.path.insert(0, ITRIALSPACE_ROOT) - - -def load_index(): - """Load the full NoduleIndex from the dataset registry. - - The dataset registry config is discovered via ``itrialspace.config.settings`` - (configs/datasets.yaml → datasets.example.yaml → bundled default), with paths - resolved from ``$ITRIALSPACE_DATA_DIR``. - """ - from itrialspace import DatasetRegistry, NoduleIndex - - registry = DatasetRegistry.from_yaml() - print("Loading index from configured dataset registry ...") - idx = NoduleIndex.from_registry(registry, verbose=True) - print(f"Loaded {len(idx.df):,} nodules from {idx.df['dataset'].nunique()} datasets") - return idx - - -def build_and_save(builder, specs, output_dir, verify_paths=True, args=None): - """Build manifests from specs and save to output_dir.""" - os.makedirs(output_dir, exist_ok=True) - - if not isinstance(specs, list): - specs = [specs] - - for i, spec in enumerate(specs): - print(f"\n{'='*60}") - print(f"Building: {spec.trial_name} ({i+1}/{len(specs)})") - print(f" n_cases={spec.n_cases}, mode={spec.cohort_mode}, seed={spec.seed}") - if spec.malignancy_prevalence is not None: - print(f" target prevalence={spec.malignancy_prevalence:.3f}") - print(f"{'='*60}") - - t0 = time.time() - - if spec.n_bootstrap > 1: - manifests = builder.build_all(spec, verbose=True) - for j, m in enumerate(manifests): - name = f"{spec.trial_name}_boot{j:03d}" - csv_path = os.path.join(output_dir, f"{name}.csv") - m.to_csv(csv_path) - print(f" Bootstrap {j}: {len(m)} cases → {csv_path}") - manifest = manifests[0] # use first for summary - else: - manifest = builder.build(spec, verbose=True) - csv_path = os.path.join(output_dir, f"{spec.trial_name}.csv") - json_path = os.path.join(output_dir, f"{spec.trial_name}.json") - manifest.to_csv(csv_path) - manifest.to_json(json_path) - print(f" Saved CSV: {csv_path}") - print(f" Saved JSON: {json_path}") - - elapsed = time.time() - t0 - print(f"\n Built in {elapsed:.1f}s") - - # Summary - summary = manifest.summary() - print(f" Cases: {summary['n_cases']}") - if "n_malignant" in summary: - print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") - if "malignancy_rate" in summary: - print(f" Actual prevalence: {summary['malignancy_rate']:.4f}") - if "donor_datasets" in summary: - print(f" Donor datasets: {summary['donor_datasets']}") - - # Audit - audit = manifest.audit() - if len(audit) > 0: - print("\n Audit:") - for _, row in audit.iterrows(): - print( - f" {row['metric']}: target={row['target']}, actual={row['actual']}, dev={row['deviation']}" - ) - - # Path verification - if verify_paths: - missing = manifest.verify_paths() - n_total = len(manifest) * 4 - n_found = n_total - len(missing) - print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") - if len(missing) > 0: - by_type = missing["path_type"].value_counts().to_dict() - print(f" Missing by type: {by_type}") - - # Save run config - config_path = os.path.join(output_dir, "_run_config.json") - with open(config_path, "w") as f: - json.dump( - { - "mode": args.mode, - "n_specs": len(specs), - "trial_names": [s.trial_name for s in specs], - "args": vars(args), - }, - f, - indent=2, - default=str, - ) - print(f"\nRun config saved to {config_path}") - - -def run(args): - from itrialspace.site.cohort_builder import CohortBuilder - from itrialspace.site.path_resolver import PathResolver - - idx = load_index() - builder = CohortBuilder(idx, PathResolver()) - - mode = args.mode - - # ── Mode 1: Controlled Prevalence ──────────────────────────────────── - if mode == "controlled_prevalence": - from itrialspace.site.trial_modes import controlled_prevalence_study - - spec = controlled_prevalence_study( - n_cases=args.n_cases, - prevalence=args.prevalence, - template=args.template, - seed=args.seed, - ) - build_and_save(builder, spec, args.output_dir, args.verify_paths, args) - - # ── Mode 2: Size Detection Curve ───────────────────────────────────── - elif mode == "size_detection_curve": - from itrialspace.site.trial_modes import size_detection_curve - - specs = size_detection_curve( - n_per_bucket=args.n_per_bucket, - label=args.label, - template=args.template, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 3: Location Sensitivity ───────────────────────────────────── - elif mode == "location_sensitivity": - from itrialspace.site.trial_modes import location_sensitivity - - specs = location_sensitivity( - n_per_lobe=args.n_per_lobe, - label=args.label, - diameter_range=(args.diam_min, args.diam_max), - template=args.template, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 4: Demographic Stratification ─────────────────────────────── - elif mode == "demographic_strat": - from itrialspace.site.trial_modes import demographic_stratification - - specs = demographic_stratification( - n_per_stratum=args.n_per_stratum, - template=args.template, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 5: Counterfactual Cohort ──────────────────────────────────── - elif mode == "counterfactual": - from itrialspace.site.trial_modes import counterfactual_cohort - - values = [float(v) for v in args.values.split(",")] if args.values else None - specs = counterfactual_cohort( - n_cases=args.n_cases, - template=args.template, - vary_param=args.vary_param, - values=values, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 6: Cross-Dataset Generalization ───────────────────────────── - elif mode == "cross_dataset": - from itrialspace.site.trial_modes import cross_dataset_generalization - - datasets = args.datasets.split(",") if args.datasets else None - specs = cross_dataset_generalization( - n_cases=args.n_cases, - datasets=datasets, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 7: Bootstrap Confidence ───────────────────────────────────── - elif mode == "bootstrap_confidence": - from itrialspace.site.trial_modes import bootstrap_confidence, controlled_prevalence_study - - base = controlled_prevalence_study( - n_cases=args.n_cases, - prevalence=args.prevalence, - template=args.template, - seed=args.seed, - ) - spec = bootstrap_confidence(base, n_bootstrap=args.n_bootstrap) - build_and_save(builder, spec, args.output_dir, args.verify_paths, args) - - # ── Mode 8: Algorithm Comparison ───────────────────────────────────── - elif mode == "algorithm_comparison": - from itrialspace.site.trial_modes import algorithm_comparison - - spec = algorithm_comparison( - n_cases=args.n_cases, - template=args.template, - seed=args.seed, - ) - build_and_save(builder, spec, args.output_dir, args.verify_paths, args) - - # ── Mode 9: Screening Protocol Simulation ──────────────────────────── - elif mode == "screening_simulation": - from itrialspace.site.trial_modes import screening_protocol_simulation - - specs = screening_protocol_simulation( - template=args.template, - n_rounds=args.n_rounds, - n_cases_per_round=args.n_cases_per_round, - prevalence_decay=args.prevalence_decay, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 10: Multi-Nodule Realism Study ────────────────────────────── - elif mode == "multi_nodule": - from itrialspace.site.trial_modes import multi_nodule_realism_study - - specs = multi_nodule_realism_study( - n_cases=args.n_cases, - multi_nodule_fraction=args.multi_nodule_fraction, - companion_strategy=args.companion_strategy, - template=args.template, - seed=args.seed, - ) - build_and_save(builder, specs, args.output_dir, args.verify_paths, args) - - # ── Mode 11: Digital Twin Isolation ──────────────────────────────── - elif mode == "digital_twin_isolation": - from itrialspace.site.trial_modes import digital_twin_isolation - - if not args.dataset: - print("ERROR: --dataset is required for digital_twin_isolation mode") - sys.exit(1) - - iso_spec = digital_twin_isolation( - dataset=args.dataset, - max_patients=args.max_patients, - all_patients=args.all_patients, - max_nodules_per_patient=args.max_nodules_per_patient, - label=args.iso_label, - diameter_min=args.diameter_min, - diameter_max=args.diameter_max, - seed=args.seed, - ) - - print(f"\n{'='*60}") - print(f"Building: {iso_spec.trial_name}") - print(f" dataset={iso_spec.dataset}, seed={iso_spec.seed}") - if iso_spec.max_patients: - print(f" max_patients={iso_spec.max_patients}") - else: - print(" all_patients=True") - print(f"{'='*60}") - - t0 = time.time() - manifest = builder.build_digital_twin_isolation(iso_spec, verbose=True) - elapsed = time.time() - t0 - - output_dir = args.output_dir - os.makedirs(output_dir, exist_ok=True) - csv_path = os.path.join(output_dir, f"{iso_spec.trial_name}.csv") - json_path = os.path.join(output_dir, f"{iso_spec.trial_name}.json") - manifest.to_csv(csv_path) - manifest.to_json(json_path) - - print(f"\n Built in {elapsed:.1f}s") - print(f" Saved CSV: {csv_path}") - print(f" Saved JSON: {json_path}") - - summary = manifest.summary() - print(f" Cases: {summary['n_cases']}") - if "n_malignant" in summary: - print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") - - if args.verify_paths: - missing = manifest.verify_paths() - n_total = len(manifest) * 4 - n_found = n_total - len(missing) - print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") - if len(missing) > 0: - by_type = missing["path_type"].value_counts().to_dict() - print(f" Missing by type: {by_type}") - - # Save run config - config_path = os.path.join(output_dir, "_run_config.json") - with open(config_path, "w") as f: - json.dump( - { - "mode": mode, - "dataset": iso_spec.dataset, - "trial_name": iso_spec.trial_name, - "args": vars(args), - }, - f, - indent=2, - default=str, - ) - print(f"\nRun config saved to {config_path}") - - # ── Mode 12: Digital Twin Complete ───────────────────────────────── - elif mode == "digital_twin_complete": - from itrialspace.site.trial_modes import digital_twin_complete - - if not args.dataset: - print("ERROR: --dataset is required for digital_twin_complete mode") - sys.exit(1) - - complete_spec = digital_twin_complete( - dataset=args.dataset, - max_patients=args.max_patients, - all_patients=args.all_patients, - label=args.iso_label, - diameter_min=args.diameter_min, - diameter_max=args.diameter_max, - seed=args.seed, - ) - - print(f"\n{'='*60}") - print(f"Building: {complete_spec.trial_name}") - print(f" dataset={complete_spec.dataset}, seed={complete_spec.seed}") - if complete_spec.max_patients: - print(f" max_patients={complete_spec.max_patients}") - else: - print(" all_patients=True") - print(f"{'='*60}") - - t0 = time.time() - manifest = builder.build_digital_twin_complete(complete_spec, verbose=True) - elapsed = time.time() - t0 - - output_dir = args.output_dir - os.makedirs(output_dir, exist_ok=True) - csv_path = os.path.join(output_dir, f"{complete_spec.trial_name}.csv") - json_path = os.path.join(output_dir, f"{complete_spec.trial_name}.json") - manifest.to_csv(csv_path) - manifest.to_json(json_path) - - print(f"\n Built in {elapsed:.1f}s") - print(f" Saved CSV: {csv_path}") - print(f" Saved JSON: {json_path}") - - summary = manifest.summary() - print(f" Cases: {summary['n_cases']}") - if "n_malignant" in summary: - print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") - - if args.verify_paths: - missing = manifest.verify_paths() - n_total = len(manifest) * 4 - n_found = n_total - len(missing) - print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") - if len(missing) > 0: - by_type = missing["path_type"].value_counts().to_dict() - print(f" Missing by type: {by_type}") - - # Save run config - config_path = os.path.join(output_dir, "_run_config.json") - with open(config_path, "w") as f: - json.dump( - { - "mode": mode, - "dataset": complete_spec.dataset, - "trial_name": complete_spec.trial_name, - "args": vars(args), - }, - f, - indent=2, - default=str, - ) - print(f"\nRun config saved to {config_path}") - - # ── Mode 13: Digital Twin Cross ──────────────────────────────────── - elif mode == "digital_twin_cross": - from itrialspace.site.trial_modes import digital_twin_cross - - if not args.host_dataset: - print("ERROR: --host-dataset is required for digital_twin_cross mode") - sys.exit(1) - if not args.donor_dataset: - print("ERROR: --donor-dataset is required for digital_twin_cross mode") - sys.exit(1) - - cross_spec = digital_twin_cross( - host_dataset=args.host_dataset, - donor_dataset=args.donor_dataset, - max_host_patients=args.max_host_patients, - all_host_patients=args.all_host_patients, - max_donor_patients=args.max_donor_patients, - all_donor_patients=args.all_donor_patients, - max_donor_nodules=args.max_donor_nodules, - donor_transfer_mode=args.donor_transfer_mode, - pairing_policy=args.pairing_policy, - n_hosts_per_donor=args.n_hosts_per_donor, - placement_strategy=args.placement_strategy, - label=args.iso_label, - diameter_min=args.diameter_min, - diameter_max=args.diameter_max, - seed=args.seed, - ) - - print(f"\n{'='*60}") - print(f"Building: {cross_spec.trial_name}") - print(f" host_dataset={cross_spec.host_dataset}, donor_dataset={cross_spec.donor_dataset}") - print(f" donor_transfer_mode={cross_spec.donor_transfer_mode}") - print(f" pairing_policy={cross_spec.pairing_policy}") - print(f" placement_strategy={cross_spec.placement_strategy}") - print(f" seed={cross_spec.seed}") - print(f"{'='*60}") - - t0 = time.time() - manifest = builder.build_digital_twin_cross(cross_spec, verbose=True) - elapsed = time.time() - t0 - - output_dir = args.output_dir - os.makedirs(output_dir, exist_ok=True) - csv_path = os.path.join(output_dir, f"{cross_spec.trial_name}.csv") - json_path = os.path.join(output_dir, f"{cross_spec.trial_name}.json") - manifest.to_csv(csv_path) - manifest.to_json(json_path) - - print(f"\n Built in {elapsed:.1f}s") - print(f" Saved CSV: {csv_path}") - print(f" Saved JSON: {json_path}") - - summary = manifest.summary() - print(f" Cases: {summary['n_cases']}") - if "n_malignant" in summary: - print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") - - if args.verify_paths: - missing = manifest.verify_paths() - n_total = len(manifest) * 4 - n_found = n_total - len(missing) - print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") - if len(missing) > 0: - by_type = missing["path_type"].value_counts().to_dict() - print(f" Missing by type: {by_type}") - - # Save run config - config_path = os.path.join(output_dir, "_run_config.json") - with open(config_path, "w") as f: - json.dump( - { - "mode": mode, - "host_dataset": cross_spec.host_dataset, - "donor_dataset": cross_spec.donor_dataset, - "trial_name": cross_spec.trial_name, - "args": vars(args), - }, - f, - indent=2, - default=str, - ) - print(f"\nRun config saved to {config_path}") - - else: - print(f"Unknown mode: {mode}") - print( - "Available modes: controlled_prevalence, size_detection_curve, " - "location_sensitivity, demographic_strat, counterfactual, " - "cross_dataset, bootstrap_confidence, algorithm_comparison, " - "screening_simulation, multi_nodule, digital_twin_isolation, " - "digital_twin_complete, digital_twin_cross" - ) - sys.exit(1) - - print("\nDone!") - - -def build_parser(): - parser = argparse.ArgumentParser( - description="iTrialSpace Trial Runner — build cohort manifests from trial modes", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=__doc__, - ) - parser.add_argument("--mode", required=True, help="Trial mode name") - parser.add_argument( - "--output-dir", default="./output", help="Output directory (default: ./output)" - ) - parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)") - parser.add_argument("--template", default="NLST", help="Trial template (default: NLST)") - parser.add_argument( - "--verify-paths", - action="store_true", - default=True, - help="Verify file paths exist (default: True)", - ) - parser.add_argument("--no-verify-paths", dest="verify_paths", action="store_false") - - # Mode-specific arguments - parser.add_argument("--n-cases", type=int, default=500, help="Number of cases") - parser.add_argument("--prevalence", type=float, default=0.05, help="Malignancy prevalence") - parser.add_argument("--label", type=int, default=1, help="Label filter (0=benign, 1=malignant)") - parser.add_argument( - "--n-per-bucket", type=int, default=100, help="Cases per size bucket (mode 2)" - ) - parser.add_argument("--n-per-lobe", type=int, default=100, help="Cases per lobe (mode 3)") - parser.add_argument("--n-per-stratum", type=int, default=200, help="Cases per stratum (mode 4)") - parser.add_argument("--diam-min", type=float, default=6.0, help="Min diameter mm (mode 3)") - parser.add_argument("--diam-max", type=float, default=15.0, help="Max diameter mm (mode 3)") - parser.add_argument( - "--vary-param", default="malignancy_prevalence", help="Parameter to vary (mode 5)" - ) - parser.add_argument("--values", default=None, help="Comma-separated values to vary (mode 5)") - parser.add_argument("--datasets", default=None, help="Comma-separated dataset names (mode 6)") - parser.add_argument( - "--n-bootstrap", type=int, default=100, help="Bootstrap replicates (mode 7)" - ) - parser.add_argument("--n-rounds", type=int, default=3, help="Screening rounds (mode 9)") - parser.add_argument( - "--n-cases-per-round", type=int, default=500, help="Cases per round (mode 9)" - ) - parser.add_argument( - "--prevalence-decay", type=float, default=0.7, help="Prevalence decay (mode 9)" - ) - parser.add_argument( - "--multi-nodule-fraction", - type=float, - default=0.25, - help="Fraction of multi-nodule cases (mode 10, default: 0.25)", - ) - parser.add_argument( - "--companion-strategy", - default="all_companions", - help="Companion strategy (mode 10, default: all_companions)", - ) - - # Mode 11/12: Digital twin arguments - parser.add_argument( - "--dataset", default=None, help="Source dataset name (mode 11/12, e.g. DLCS24)" - ) - iso_group = parser.add_mutually_exclusive_group() - iso_group.add_argument( - "--max-patients", type=int, default=None, help="Max host patients to select (mode 11/12)" - ) - iso_group.add_argument( - "--all-patients", - action="store_true", - default=False, - help="Use all eligible patients (mode 11/12)", - ) - parser.add_argument( - "--max-nodules-per-patient", - type=int, - default=None, - help="Cap isolation cases per patient (mode 11)", - ) - parser.add_argument( - "--iso-label", - type=int, - default=None, - help="Filter nodules by label (mode 11/12/13, 0=benign, 1=malignant, None=any)", - ) - parser.add_argument( - "--diameter-min", type=float, default=None, help="Min nodule diameter mm (mode 11/12/13)" - ) - parser.add_argument( - "--diameter-max", type=float, default=None, help="Max nodule diameter mm (mode 11/12/13)" - ) - - # Mode 13: Digital twin cross arguments - parser.add_argument( - "--host-dataset", default=None, help="Host anatomy dataset (mode 13, e.g. DLCS24)" - ) - parser.add_argument( - "--donor-dataset", default=None, help="Donor nodule dataset (mode 13, e.g. LUNA25)" - ) - cross_host_group = parser.add_mutually_exclusive_group() - cross_host_group.add_argument( - "--max-host-patients", type=int, default=None, help="Max host patients (mode 13)" - ) - cross_host_group.add_argument( - "--all-host-patients", - action="store_true", - default=False, - help="Use all eligible host patients (mode 13)", - ) - cross_donor_group = parser.add_mutually_exclusive_group() - cross_donor_group.add_argument( - "--max-donor-patients", type=int, default=None, help="Max donor patients (mode 13)" - ) - cross_donor_group.add_argument( - "--all-donor-patients", - action="store_true", - default=False, - help="Use all eligible donor patients (mode 13)", - ) - parser.add_argument( - "--max-donor-nodules", type=int, default=None, help="Max total donor nodules (mode 13)" - ) - parser.add_argument( - "--donor-transfer-mode", - default="single", - choices=["single", "complete"], - help="Donor transfer mode (mode 13, default: single)", - ) - parser.add_argument( - "--pairing-policy", - default="one_to_one", - choices=["one_to_one", "one_to_many_hosts", "donor_patient_complete"], - help="Pairing policy (mode 13, default: one_to_one)", - ) - parser.add_argument( - "--n-hosts-per-donor", - type=int, - default=3, - help="Hosts per donor for one_to_many_hosts (mode 13, default: 3)", - ) - parser.add_argument( - "--placement-strategy", - default="profile_faithful_transfer", - choices=["profile_faithful_transfer", "host_constrained_transfer"], - help="Placement strategy (mode 13, default: profile_faithful_transfer)", - ) - return parser - - -def main(argv=None): - """Console-script entry point (``its-trials``).""" - parser = build_parser() - args = parser.parse_args(argv) - run(args) - - -if __name__ == "__main__": - main() diff --git a/itrialspace/src/itrialspace/utils/__init__.py b/itrialspace/src/itrialspace/utils/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/itrialspace/src/itrialspace/utils/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/utils/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 0640416f91fbd01d4f0cbc586e54bd3bdacd0d39..0000000000000000000000000000000000000000 Binary files a/itrialspace/src/itrialspace/utils/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/itrialspace/tools/check_portability.py b/itrialspace/tools/check_portability.py deleted file mode 100644 index 3434110a19b8a7c3756564a3e15733079e65e794..0000000000000000000000000000000000000000 --- a/itrialspace/tools/check_portability.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python3 -"""Portability guard: fail if any tracked file hardcodes a machine-specific path. - -Run by pre-commit and CI. Mirrors the spirit of the project's existing dataset-purge -guard: a single scan that keeps the repo copy-and-run portable on any machine. - -A finding is any occurrence of a forbidden absolute-path/env token outside the -explicitly allowed locations (docs, example configs, this checker itself). - -Usage: - python tools/check_portability.py # scan repo, exit 1 on findings - python tools/check_portability.py --list # also print every match -""" -from __future__ import annotations - -import argparse -import re -import subprocess -import sys -from pathlib import Path - -# Tokens that must never appear in shipped code/config/scripts. -FORBIDDEN = [ - r"/home/ft42", - r"/scratch/railabs", - r"/scratch/[A-Za-z0-9_]+/VLST", - r"monai-auto3dseg", # old hardcoded conda env name -] - -# Paths where these tokens are allowed (documentation, history). -ALLOWED_PREFIXES = ( - "docs/", - "CHANGELOG.md", - "tools/check_portability.py", -) -ALLOWED_SUFFIXES = ( - ".example.yaml", - ".example.yml", - ".md", # prose/docs may reference original paths illustratively -) - -# Only scan these kinds of files. -SCAN_SUFFIXES = (".py", ".yaml", ".yml", ".json", ".sh", ".sub", ".cfg", ".toml", ".txt") - -PATTERN = re.compile("|".join(FORBIDDEN)) - - -def tracked_files(root: Path) -> list[Path]: - """Prefer git-tracked files; fall back to a filesystem walk.""" - try: - out = subprocess.check_output( - ["git", "ls-files"], cwd=root, text=True, stderr=subprocess.DEVNULL - ) - files = [root / line for line in out.splitlines() if line.strip()] - if files: - return files - except (subprocess.CalledProcessError, FileNotFoundError): - pass - return [p for p in root.rglob("*") if p.is_file()] - - -def is_allowed(rel: str) -> bool: - if rel.startswith(ALLOWED_PREFIXES): - return True - return rel.endswith(ALLOWED_SUFFIXES) - - -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("--list", action="store_true", help="print every matching line") - ap.add_argument("--root", default=None, help="repo root (default: auto)") - args = ap.parse_args() - - root = Path(args.root) if args.root else Path(__file__).resolve().parents[1] - findings: list[tuple[str, int, str]] = [] - - for path in tracked_files(root): - if path.suffix not in SCAN_SUFFIXES: - continue - rel = str(path.relative_to(root)) - if is_allowed(rel): - continue - try: - text = path.read_text(encoding="utf-8", errors="ignore") - except OSError: - continue - for i, line in enumerate(text.splitlines(), 1): - if PATTERN.search(line): - findings.append((rel, i, line.strip())) - - if findings: - print(f"✗ portability check FAILED — {len(findings)} hardcoded path(s):\n") - for rel, ln, line in findings: - print(f" {rel}:{ln}: {line[:120]}") - print( - "\nResolve paths via itrialspace.config.settings or env vars " - "(see docs/configuration.md)." - ) - return 1 - - print("✓ portability check passed — no hardcoded machine-specific paths.") - return 0 - - -if __name__ == "__main__": - sys.exit(main())