354 lines
17 KiB
Markdown
354 lines
17 KiB
Markdown
# msi-julia-python-cnn — Julia–Python Hybrid Deep Learning Workflow for Mass Spectrometry Imaging
|
||
|
||
A deep learning workflow for mass spectrometry imaging (MSI): a **Julia** preprocessing
|
||
engine performs memory-mapped imzML parsing, peak picking, ion-image extraction, TrIQ
|
||
normalization, and per-ion PNG export in a single pass; a **Python SimCLR** encoder then
|
||
learns a 128-dimensional latent space from the exported ion corpus and clusters the ions
|
||
into spatially coherent metabolic domains.
|
||
|
||
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)).
|
||
|
||
## Repository layout
|
||
|
||
```
|
||
.
|
||
├── 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
|
||
├── 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.7)
|
||
│ └── 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` (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 |
|
||
|
||
## Quick start (Docker, recommended)
|
||
|
||
```bash
|
||
# 1) build (GPU image; `make build-cpu` for the smaller CPU-only 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 — works on CPU out of the box (torch falls back when there is no GPU)
|
||
make run # every dataset under datos_para_ai/
|
||
make run-dataset D=Datura_leaf # a single dataset
|
||
|
||
# with an NVIDIA GPU (needs the Container Toolkit / a CDI spec — see Troubleshooting):
|
||
make run-gpu
|
||
make run-dataset-gpu D=Datura_leaf
|
||
```
|
||
|
||
Equivalent raw container, if you prefer not to use `make`:
|
||
|
||
```bash
|
||
docker build -t msi-pipeline-gpu .
|
||
|
||
# CPU (no GPU flags):
|
||
docker run --rm --shm-size=2g -it \
|
||
-v "$PWD/datos_para_ai:/app/datos_para_ai" \
|
||
-v "$PWD/outputs:/app/outputs" \
|
||
msi-pipeline-gpu bash
|
||
# add `--gpus all` (Docker) or `--device nvidia.com/gpu=all` (Podman + CDI) for a GPU.
|
||
|
||
# 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
|
||
```
|
||
|
||
The pipeline runs fine **without a GPU** (SimCLR trains on CPU, just slower). The pure
|
||
`Dockerfile.cpu` image (`make build-cpu`, `make run-cpu`) is smaller if you never need CUDA.
|
||
In VS Code the bundled `.devcontainer/` requests a GPU.
|
||
|
||
## 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
|
||
bash run_full_pipeline.sh Datura_leaf
|
||
```
|
||
|
||
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.
|
||
|
||
## Running individual stages
|
||
|
||
`run_full_pipeline.sh` chains the stages below. To re-run a single one (native form):
|
||
|
||
```bash
|
||
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>
|
||
```
|
||
|
||
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
|
||
|
||
The pipeline reads **any valid imzML** (profile or centroid) — it is **not** restricted to
|
||
the manuscript datasets.
|
||
|
||
**Each dataset must live in its own subfolder of `datos_para_ai/`.** The folder name *is*
|
||
the dataset name, and it becomes the `outputs/<name>/` directory. Files placed directly in
|
||
`datos_para_ai/` — **not inside a subfolder — are ignored** by `run_full_pipeline.sh`, so a
|
||
dataset dropped loose at the root will not be detected.
|
||
|
||
```
|
||
datos_para_ai/
|
||
├── Mouse_bladder/ # folder name = dataset name
|
||
│ ├── HR2MSImouseurinarybladderS096.imzML # exactly one .imzML
|
||
│ ├── HR2MSImouseurinarybladderS096.ibd # its sibling .ibd (matching basename)
|
||
│ └── region_of_interest.png # optional ROI mask
|
||
└── Datura_leaf/
|
||
├── Leaf.imzML
|
||
└── Leaf.ibd
|
||
```
|
||
|
||
Rules for each dataset folder:
|
||
|
||
- exactly one `.imzML` file, and
|
||
- its sibling `.ibd` binary — the imzML references the `.ibd` by basename, so both must sit
|
||
in the same folder with matching basenames.
|
||
|
||
**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.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`) is
|
||
accompanied by composite panels:
|
||
|
||
```
|
||
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
|
||
```
|
||
|
||
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.
|
||
|
||
## Troubleshooting
|
||
|
||
### `? Please select an image:` at `STEP 1/15` (Podman / Buildah)
|
||
|
||
When a `FROM` uses a short image name (e.g. `nvidia/cuda:12.4.1-runtime-ubuntu22.04`),
|
||
Docker resolves it against Docker Hub automatically, but **Podman/Buildah enforces
|
||
short-name resolution**: if more than one registry is configured it stops and asks which
|
||
one to pull from. A typical prompt (the list depends on your registry configuration):
|
||
|
||
```
|
||
? Please select an image:
|
||
▸ registry.fedoraproject.org/nvidia/cuda:12.4.1-runtime-ubuntu22.04
|
||
registry.access.redhat.com/nvidia/cuda:12.4.1-runtime-ubuntu22.04
|
||
docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04
|
||
```
|
||
|
||
**Choose `docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04`** — NVIDIA publishes these
|
||
images on Docker Hub.
|
||
|
||
To avoid the prompt entirely (recommended, works on every OS): use the **fully-qualified**
|
||
name. This repository's Dockerfiles already do this, so no prompt should appear:
|
||
|
||
```dockerfile
|
||
FROM docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04 # Dockerfile (GPU)
|
||
FROM docker.io/library/ubuntu:22.04 # Dockerfile.cpu (CPU)
|
||
```
|
||
|
||
If you maintain a fork with short names and cannot change the Dockerfile, you can allow
|
||
short names globally instead. Edit the Containers registry config:
|
||
|
||
- Linux/macOS (rootless): `~/.config/containers/registries.conf`
|
||
- Linux (root): `/etc/containers/registries.conf`
|
||
- Windows: `%APPDATA%\containers\registries.conf`
|
||
|
||
```toml
|
||
unqualified-search-registries = ["docker.io"]
|
||
short-name-mode = "permissive"
|
||
```
|
||
|
||
- **Docker Desktop (Windows/macOS) and Docker Engine (Linux):** no prompt — `nvidia/cuda`
|
||
resolves to Docker Hub by default.
|
||
- **Podman (Linux/macOS/Windows):** prompted unless the name is fully qualified or the
|
||
config above is set.
|
||
|
||
### Clean rebuild / remove a failed build
|
||
|
||
A **failed build usually leaves no tagged project image** — only intermediary layers and
|
||
build cache. Clearing the cache is therefore the important step; there is often nothing to
|
||
`rmi`.
|
||
|
||
Docker (Linux/Windows/macOS):
|
||
|
||
```bash
|
||
docker compose down --rmi all --volumes --remove-orphans # project-scoped reset
|
||
docker rmi -f msi-pipeline-gpu msi-pipeline-cpu 2>/dev/null || true
|
||
docker builder prune -af # clear BuildKit cache
|
||
docker image prune -f # drop dangling <none> images
|
||
docker compose build --no-cache msi-pipeline-gpu # rebuild from scratch
|
||
```
|
||
|
||
Podman / `podman-compose`:
|
||
|
||
```bash
|
||
podman-compose down --rmi all -v
|
||
podman rmi -f $(podman images --format '{{.ID}} {{.Repository}}' \
|
||
| awk 'tolower($0) ~ /msi-pipeline/ {print $1}') 2>/dev/null || true
|
||
podman builder prune -af
|
||
podman-compose build --no-cache msi-pipeline-gpu
|
||
```
|
||
|
||
Global reset (**careful — removes all unused images/cache, not just this project**):
|
||
|
||
```bash
|
||
docker system prune -a --volumes -f # Docker (same as `make clean-all`)
|
||
podman system prune -a --volumes -f # Podman
|
||
```
|
||
|
||
Notes:
|
||
- `docker builder prune -af` / `podman builder prune -af` affect this project's cache
|
||
safely; the `system prune -a` commands are host-wide.
|
||
- A normal `make build` reuses cached `apt`/Julia/pip layers. For a genuine
|
||
reproducibility test, clear the cache (`builder prune -af`) or build with `--no-cache`.
|
||
|
||
### `make run` fails with `unresolvable CDI devices nvidia.com/gpu=all`
|
||
|
||
The base `docker-compose.yml` does **not** request a GPU, so `make run` / `make run-dataset`
|
||
work on CPU-only machines. Requesting a GPU is opt-in via `docker-compose.gpu.yml`:
|
||
|
||
```bash
|
||
make run-gpu
|
||
make run-dataset-gpu D=Datura_leaf
|
||
```
|
||
|
||
On **Podman**, a GPU reservation becomes the CDI device `nvidia.com/gpu=all`, which must
|
||
exist first:
|
||
|
||
```bash
|
||
# one-time, on the host (needs the NVIDIA driver + nvidia-container-toolkit):
|
||
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
|
||
nvidia-ctk cdi list # should show nvidia.com/gpu=all
|
||
```
|
||
|
||
Docker Desktop / Docker Engine handle the `deploy` GPU reservation without a manual CDI
|
||
spec. If you have no NVIDIA GPU, ignore `*-gpu` targets entirely — the CPU fallback works.
|
||
|
||
### If the Julia step of the build fails
|
||
|
||
- The images install Julia strictly from the committed `environment/Manifest.toml` and run
|
||
`Pkg.instantiate()` only (no `resolve()`). If you see
|
||
`… is a direct dependency, but does not appear in the manifest`, the lock is out of sync
|
||
with `Project.toml` — run `julia --project=environment -e 'using Pkg; Pkg.resolve()'`
|
||
locally and commit the regenerated `Manifest.toml`.
|
||
- `GLMakie` fails to precompile in a headless build
|
||
(`GLFWError … X11: The DISPLAY environment variable is missing`). This is expected and
|
||
**non-fatal**: GLMakie is a GUI-only dependency and the pipeline never loads it. The
|
||
images intentionally do not run an explicit `Pkg.precompile()`.
|
||
|
||
## License
|
||
|
||
MIT — see `LICENSE`. The vendored `src/` retains its own MIT license (`src/LICENSE`).
|