formated readme for first run build, standarized docker and pipeline

This commit is contained in:
Pixelguy14
2026-10-08 14:30:56 -06:00
parent b09bc47c62
commit 19fdd8af16
28 changed files with 13543 additions and 118 deletions
+169 -104
View File
@@ -6,142 +6,207 @@ normalization, and per-ion PNG export in a single pass; a **Python SimCLR** enco
learns a 128-dimensional latent space from the exported ion corpus and clusters the ions
into spatially coherent metabolic domains.
This repository is the self-contained, reproducible home of the manuscript
*"A scalable deep learning workflow for mass spectrometry imaging"* — the manuscript
(`MSI_julia-python_mapping.md`), all of its figures, the pinned environment, and the
pipeline that produces every result are here. It ships the **renderable manuscript and its
figures**, plus all seven pipeline stages.
This repository accompanies the manuscript *"A scalable deep learning workflow for mass
spectrometry imaging"* (`MSI_julia-python_mapping.md`). It is self-contained: it ships the
manuscript and figures, the pinned environments, the full seven-stage pipeline, and a
**vendored copy of the JuliaMSI engine** (`src/`, MIT) so no external Julia project is
required. Raw MSI datasets are supplied by the user (see [Datasets](#datasets)).
> This clone is a **standalone repository**: the raw MSI datasets are supplied by the user
> (see [Datasets](#datasets)); everything else is self-contained. The earlier "functional
> copy / symlink into the canonical workspace" layout has been replaced by the standalone
> setup described below.
## Contents
## Repository layout
```
msi-julia-python-cnn/
├── README.md # this document
├── LICENSE # MIT
├── MSI_julia-python_mapping.md # manuscript (pandoc/biblatex, references zotero.bib)
├── zotero.bib # manuscript bibliography
├── figure1.png / figure2.png / figure3.png # manuscript figures, Pandoc style, 16 cm, 400 dpi (see below)
├── run_full_pipeline.sh # single entry point: 7-stage pipeline (one or many datasets)
├── run_pipeline.sh # legacy per-stage driver (native)
├── run_pipeline_wrapper.sh # activates a repo-local venv, then calls run_full_pipeline.sh
├── Makefile # build/run + step1..step7 targets (Docker)
├── Dockerfile # GPU image (CUDA 12.4 + Julia 1.12 + Python/SimCLR)
├── Dockerfile.cpu # CPU image (Ubuntu 22.04 + Julia + Python/SimCLR)
├── docker-compose.yml # msi-pipeline-gpu / msi-pipeline-cpu services
.
├── README.md
├── MSI_julia-python_mapping.md # manuscript (pandoc/biblatex, references zotero.bib)
├── zotero.bib # manuscript bibliography
├── documentation.md # technical rationale, hyperparameters, validation
├── figure1.png figure2.png figure3.png figure4.png
├── Dockerfile # GPU image (CUDA 12.4 + Julia + Python/SimCLR)
├── Dockerfile.cpu # CPU image (Ubuntu 22.04 + Julia + Python/SimCLR)
├── docker-compose.yml # msi-pipeline-gpu / msi-pipeline-cpu services
├── .dockerignore
├── .gitignore
├── environment/ # pinned dependencies
│ ├── Project.toml # Julia package set (incl. julia_mzML_imzML engine)
│ ├── Manifest.toml # locked Julia environment (julia 1.12.6)
│ └── requirements.txt # Python deps (torch, sklearn, Pillow, …)
├── src/
│ └── MSI_src.jl # core Julia engine module (memory-mapped imzML, TrIQ, slices)
├── scripts/
│ ├── setup_datasets.sh # add a new imzML dataset via symlinks
│ ├── julia/
│ │ ├── julia_msi_bridge.jl # Stage 1: preprocess + PNG export (grayscale + viridis)
│ │ ├── plot_mass_spectra.jl # Stage 7: mean + per-cluster spectra
│ │ └── graph_cluster_spectra.jl # spectrum figure with cluster mapping
│ └── python/
│ ├── msi_preprocess_python.py # Stage 1 Python fallback (vendor imzML)
│ ├── CNN_proof_1.py # Stage 2: SimCLR contrastive training
│ ├── evaluate_clustering.py # Stage 3: K sweep (2..20, 3 metrics)
│ ├── graph_tsne_msi.py # Stage 4: t-SNE + K-Means (*_k5 variants for k=5 runs)
│ ├── quantitative_validation.py# Stage 5: isotope colocalization, PCA baseline, ARI
│ ├── visualize_clusters.py # Stage 6: per-cluster galleries
│ ├── plot_mass_spectra_python.py # Stage 7 Python fallback
│ ├── make_ion_carpet.py # standalone ion-carpet exporter (manuscript figures)
│ └── (test_grouping, verify_coherence, guided_vascular) # dev/analysis helpers
├── datasets/ # user-provided data (see Datasets below)
│ ├── datasets.csv # registry of the 7 manuscript datasets (+ mask flags)
│ ├── Datura_leaf/ Datura_root/ San_pedro/
│ └── Mouse_bladder/ Mouse_Liver/ Mouse_Stomach/ Human_colon/
└── outputs/ # generated (git-ignored): ion images, models, figures
├── Makefile # build/run + step1..step7 targets (Docker)
├── run_full_pipeline.sh # single entry point: 7 stages (one or many datasets)
├── environment/ # pinned dependencies
│ ├── Project.toml # Julia package set
│ ├── Manifest.toml # locked Julia environment (julia 1.11.3)
│ └── requirements.txt # Python deps (torch, sklearn, Pillow, …)
├── src/ # vendored JuliaMSI engine (MIT) — see below
│ └── MSI_src.jl + 14 modules # memory-mapped imzML, TrIQ, slicing, masks
├── scripts_julia/
│ ├── julia_msi_bridge.jl # Stage 1: preprocess + PNG export (grayscale + viridis)
│ ├── plot_mass_spectra.jl # Stage 7: mean + per-cluster spectra
│ └── graph_cluster_spectra.jl # dev helper (spectrum figure with cluster mapping)
├── scripts_python/
│ ├── CNN_proof_1.py # Stage 2: SimCLR contrastive training
│ ├── evaluate_clustering.py # Stage 3: K sweep (2..20, 3 metrics)
│ ├── graph_tsne_msi.py # Stage 4: t-SNE + K-Means
│ ├── quantitative_validation.py # Stage 5: isotope co-localization, PCA baseline, ARI
│ ├── visualize_clusters.py # Stage 6: per-cluster galleries
│ ├── plot_mass_spectra_python.py # Stage 7 Python fallback
│ ├── msi_preprocess_python.py # Stage 1 Python fallback (vendor imzML)
│ ├── make_ion_carpet.py # standalone ion-carpet mosaics (manuscript figures)
│ └── build_manuscript_figures.py # composite figure panels
├── datos_para_ai/ # user-provided datasets (git-ignored)
└── outputs/ # generated (git-ignored): ion images, models, figures
```
## The seven pipeline stages
| Stage | Script | Input → Output |
|-------|--------|----------------|
| 1 | `scripts/julia/julia_msi_bridge.jl` (Python fallback: `msi_preprocess_python.py`) | imzML/ibd → avg spectrum, 2%-peak pick, per-ion extraction, TrIQ, zero-pad 256×256, PNG export (grayscale for DL + viridis corpus) |
| 2 | `scripts/python/CNN_proof_1.py` | grayscale PNGs → SimCLR 4-layer GroupNorm encoder → 128-dim latents (`outputs/models/<ds>/`) |
| 3 | `scripts/python/evaluate_clustering.py` | latents → K sweep k=2..20 (Silhouette, Davies-Bouldin, Calinski-Harabasz) → best K |
| 4 | `scripts/python/graph_tsne_msi.py <ds> <K>` | latents → t-SNE colored by K-Means (best K) |
| 5 | `scripts/python/quantitative_validation.py <ds> <K>` | latents → isotope co-localization, PCA baseline, ARI stability |
| 6 | `scripts/python/visualize_clusters.py <ds>` | clusters → representative ion-image galleries per cluster |
| 7 | `scripts/julia/plot_mass_spectra.jl <ds>` (Python fallback) | spectra → mean spectrum + per-cluster annotated spectra |
| — | `scripts/python/make_ion_carpet.py <ds> [--clusters]` (standalone) | Stage-1 viridis corpus → full-dataset & per-cluster ion-carpet mosaics (manuscript Fig. carpet / carpet-root) |
| 1 | `scripts_julia/julia_msi_bridge.jl` (fallback: `msi_preprocess_python.py`) | imzML/ibd → avg spectrum, 2%-peak pick, per-ion extraction, TrIQ, resize to ≤256 px, PNG export (grayscale for DL + viridis corpus) |
| 2 | `scripts_python/CNN_proof_1.py` | grayscale PNGs → SimCLR 4-layer GroupNorm encoder → 128-dim latents (`outputs/models/<ds>/`) |
| 3 | `scripts_python/evaluate_clustering.py` | latents → K sweep k=2..20 (Silhouette, Davies-Bouldin, Calinski-Harabasz) → best K (`outputs/<ds>/best_k_results.csv`) |
| 4 | `scripts_python/graph_tsne_msi.py <ds> <K>` | latents → t-SNE colored by K-Means |
| 5 | `scripts_python/quantitative_validation.py <ds> <K>` | latents → isotope co-localization, PCA baseline, ARI stability |
| 6 | `scripts_python/visualize_clusters.py <ds>` | clusters → representative ion-image galleries per cluster |
| 7 | `scripts_julia/plot_mass_spectra.jl <ds> [data_dir]` (fallback: `plot_mass_spectra_python.py`) | spectra → mean + per-cluster annotated spectra |
| — | `scripts_python/make_ion_carpet.py <ds> [--clusters]` (standalone) | Stage-1 viridis corpus → full-dataset & per-cluster ion-carpet mosaics |
## Run
### Native (venv + system Julia)
## Quick start (Docker, recommended)
```bash
# one-time setup: Python environment with pinned deps
# 1) build the GPU image (use `make build-cpu` for the CPU image)
make build
# 2) put each dataset in its own folder, e.g.
# datos_para_ai/Datura_leaf/<name>.imzML (+ <name>.ibd, optional ROI .png)
# 3) run
make run # every dataset under datos_para_ai/
make run-dataset D=Datura_leaf # a single dataset
```
Equivalent raw Docker, if you prefer not to use `make`:
```bash
docker build -t msi-pipeline-gpu .
docker run --gpus all --shm-size=2g -it \
-v "$PWD/datos_para_ai:/app/datos_para_ai" \
-v "$PWD/outputs:/app/outputs" \
msi-pipeline-gpu bash
# then, inside the container:
bash run_full_pipeline.sh # all datasets under datos_para_ai/
bash run_full_pipeline.sh Datura_leaf # a single dataset
```
For CPU-only machines, build `Dockerfile.cpu` (`make build-cpu`) and drop `--gpus all`.
In VS Code the bundled `.devcontainer/` builds the GPU image with the right flags.
## Native run (venv + system Julia)
```bash
# one-time setup
python3 -m venv venv && venv/bin/pip install -r environment/requirements.txt
julia --project=environment -e 'using Pkg; Pkg.instantiate()'
# run everything (or a single dataset)
bash run_full_pipeline.sh # all 7 manuscript datasets
bash run_full_pipeline.sh Datura_leaf # single dataset
# optional: regenerate the ion-carpet mosaics after Stage 1
venv/bin/python scripts/python/make_ion_carpet.py Datura_leaf --clusters
# run everything, or a single dataset
bash run_full_pipeline.sh
bash run_full_pipeline.sh Datura_leaf
```
`run_pipeline_wrapper.sh` automatically activates a local `venv/` if present.
Requires **Julia 1.11.x** (matching `environment/Manifest.toml`) and **Python 3.10+**.
`run_full_pipeline.sh` automatically uses a repo-local `venv/` when present.
### Docker
## Running individual stages
`run_full_pipeline.sh` chains the stages below. To re-run a single one (native form):
```bash
make build # GPU image (NVIDIA Container Toolkit required to run)
make build-cpu # CPU-only image
make run # full pipeline on all datasets
make run-dataset D=Datura_leaf
make step1..step7 D=... # re-run a single stage (steps 4–5 need K=)
julia --threads auto --project=environment scripts_julia/julia_msi_bridge.jl datos_para_ai/<ds> <ds>
python scripts_python/CNN_proof_1.py <ds>
python scripts_python/evaluate_clustering.py <ds> # writes outputs/<ds>/best_k_results.csv
python scripts_python/graph_tsne_msi.py <ds> <K>
python scripts_python/quantitative_validation.py <ds> <K>
python scripts_python/visualize_clusters.py <ds>
julia --project=environment scripts_julia/plot_mass_spectra.jl <ds> datos_para_ai/<ds>
```
### Add a custom dataset
```bash
bash scripts/setup_datasets.sh /path/to/your_data.imzML my_dataset
```
Docker equivalents: `make step1 D=<ds>` … `make step7 D=<ds>`, with
`make step4 D=<ds> K=5` and `make step5 D=<ds> K=5`. Stages 4–5 need the cluster
count `K`; Stage 3 prints and stores the best value (Silhouette optimum by default).
## Datasets
All seven benchmark datasets are **public** and listed in `datasets/datasets.csv`
(LD-LTP *Datura* leaf and root, MALDI San Pedro cactus, MALDI mouse liver and stomach,
AP-SMALDI mouse bladder, DESI human colon; 0.07–4.4 GB, centroid and profile). Access
instructions: **TODO — add accession DOI/URL per dataset**. Download each raw
imzML/ibd pair and place it (or symlink it) into `datasets/<name>/`, matching the
`imzml_file` column. ROI masks (`region_of_interest.png` / `region_of_interest_<tissue>.png`)
are already expected there for the masked datasets (all except San Pedro).
The pipeline reads **any valid imzML** (profile or centroid) — it is **not** restricted to
the manuscript datasets. For each dataset create `datos_para_ai/<name>/` containing:
- exactly one `.imzML` file, and
- its sibling `.ibd` binary (the imzML references the `.ibd` by basename, so both must sit
in the same folder).
The folder name becomes the dataset name used throughout `outputs/`.
**ROI masks are optional.** If present in the same folder, the first match wins:
`region_of_interest.png`, otherwise any `*.png` whose filename contains `roi`, `mask`, or
`region` (case-insensitive) — e.g. `region.png`, `MyData_mask.png`. Masks are resized to the
dataset dimensions; without one the full image is used.
The seven manuscript datasets are all **public**: LD-LTP *Datura* leaf and root, MALDI San
Pedro cactus, MALDI mouse liver and stomach, AP-SMALDI mouse bladder, DESI human colon
(0.07–4.4 GB, centroid and profile). Access instructions: **TODO — add accession DOI/URL
per dataset**. Related dataset DOIs are listed in `DOIs.md` (e.g. San Pedro cactus
<https://doi.org/10.5281/zenodo.3625054>; general imzML test data
<https://doi.org/10.5281/zenodo.10084132>).
`models.zip` contains the trained SimCLR encoders for the seven manuscript datasets.
Unzip it into `outputs/` (`unzip models.zip -d outputs/`) to reuse
`outputs/models/<ds>/msi_encoder_trained.pth` and skip Stage 2 for those datasets.
## JuliaMSI engine (`src/`)
The Julia core used by Stages 1 and 7 is **vendored** into `src/` from the MIT-licensed
[JuliaMSI](https://codeberg.org/LabABI/JuliaMSI) project (© LabABI, Cinvestav Irapuato,
Mexico), pinned at commit `6aa76fc` (2026-08-25). Mirrors / GUI:
- <https://codeberg.org/LabABI/JuliaMSI> (upstream)
- <https://codeberg.org/pixelguy14/JuliaMSI>
- <https://github.com/Pixelguy14/Julia_msi_GUI>
- <https://git.nube-gran.de/Julian/MSI_Julia_CNN>
It is vendored (≈400 KB) so the pipeline is reproducible and does not break when upstream
APIs change. To update the engine, replace the contents of `src/` from a newer upstream
commit and re-run Stage 1. The MIT license of the vendored code is in `src/LICENSE`.
## Configuration knobs
`run_full_pipeline.sh` and the scripts honour these environment variables:
| Variable | Default | Meaning |
|----------|---------|---------|
| `MSI_PEAK_FRAC` | `0.02` | peak-pick threshold as a fraction of the base peak |
| `MSI_PEAK_MIN_MZ_GAP` | `0` | minimum m/z separation between picked ions (0 disables) |
| `MSI_BIN_AVG` | unset | average-spectrum bin width in Da (needed for high-resolution ToF data) |
| `MSI_MEM_MAX` | unset | cgroup memory ceiling |
| `MSI_DATA_ROOT` | `datos_para_ai` | override the dataset root directory |
| `MSI_K` | auto | force a cluster count instead of the Stage-3 Silhouette choice |
## Prerequisites
- **Julia 1.12.x** (instantiate against `environment/`; first run resolves the depot)
- **Python 3.10+** (`environment/requirements.txt`; torch builds for your GPU/CPU)
- Optional: **Docker 24+** with NVIDIA Container Toolkit for the GPU image
Pipeline configuration knobs (see `run_full_pipeline.sh`): `MSI_PEAK_FRAC`,
`MSI_PEAK_MIN_MZ_GAP`, `MSI_BIN_AVG`, `MSI_MEM_MAX` (cgroup memory ceiling).
- **Julia 1.11.x** — instantiate against `environment/Manifest.toml`.
- **Python 3.10+** — `environment/requirements.txt` (torch builds for your GPU/CPU).
- Optional: **Docker 24+** with NVIDIA Container Toolkit (GPU image) and Compose v2 (`make`).
- Disk: datasets are 0.07–4.4 GB; outputs/models add a few GB. RAM: ~8 GB+ for larger sets.
## Manuscript figures
The manuscript (`MSI_julia-python_mapping.md`, biblatex bibliography `zotero.bib`)
The manuscript (`MSI_julia-python_mapping.md`, biblatex bibliography `zotero.bib`) is
accompanied by composite panels:
```
figure1.png # JuliaMSI vs Cardinal vs MALDIquant: slice throughput + peak load RAM, red X on failed MALDIquant runs (Fig. \ref{fig:benchmark})
figure2.png # K-sweep clustering validation for the Datura leaf + root demonstration datasets (Fig. \ref{fig:clustering})
figure3.png # t-SNE + biologically interpretable ion galleries, mouse bladder over human colon (Fig. \ref{fig:tsne_clusters})
figure1.png # JuliaMSI vs Cardinal vs MALDIquant: throughput + RAM (Fig. benchmark)
figure2.png # K-sweep clustering validation for the Datura leaf + root datasets
figure3.png # t-SNE + biologically interpretable ion galleries
figure4.png # additional composite panel
```
The three manuscript figures are composite panels assembled by
`scripts/python/build_manuscript_figures.py` from the per-dataset outputs of the pipeline
(`outputs/<ds>/msi_tsne_plot.png`, `outputs/<ds>/figures/cluster_validation_detailed_plot.png`,
`outputs/<ds>/galleries/`, and the benchmark CSV under `Benchmark_recommendation/results/`).
Re-run that script after any pipeline or benchmark change to regenerate them.
They are assembled by `scripts_python/build_manuscript_figures.py` from per-dataset
outputs (`outputs/<ds>/msi_tsne_plot.png`,
`outputs/<ds>/figures/cluster_validation_detailed_plot.png`, `outputs/<ds>/galleries/`).
Re-run that script after any pipeline change to regenerate them.
## License
MIT — see `LICENSE`. The vendored `src/` retains its own MIT license (`src/LICENSE`).