Files

15 KiB
Raw Permalink Blame History

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 is self-contained: it ships the pinned environments, the full seven-stage pipeline, and a vendored copy of the JuliaMSI engine (src/, MIT). Raw MSI datasets are supplied by the user (see Datasets).

Repository layout

.
├── README.md
├── 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 (figure panels)
│   └── build_figure_panels.py        # composite figure panels
├── ai_data/                          # 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
# 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.
#    ai_data/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 ai_data/
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:

docker build -t msi-pipeline-gpu .

# CPU (no GPU flags):
docker run --rm --shm-size=2g -it \
  -v "$PWD/ai_data:/app/ai_data" \
  -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 ai_data/
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)

# 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):

julia --threads auto --project=environment scripts_julia/julia_msi_bridge.jl ai_data/<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> ai_data/<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 a fixed set of datasets.

Each dataset must live in its own subfolder of ai_data/. The folder name is the dataset name, and it becomes the outputs/<name>/ directory. Files placed directly in ai_data/ — not inside a subfolder — are ignored by run_full_pipeline.sh, so a dataset dropped loose at the root will not be detected.

ai_data/
├── 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.

JuliaMSI engine (src/)

The Julia core used by Stages 1 and 7 is vendored into src/ from the MIT-licensed JuliaMSI project (© LabABI, Cinvestav Irapuato, Mexico), pinned at commit 6aa76fc (2026-08-25). Mirrors / GUI:

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 ai_data 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.

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:

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
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):

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:

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

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:

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:

# 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().

Data availability

TODO — add accession DOI/URL per dataset.

The seven reference 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).

Related dataset DOIs:

Trained models

models.zip (pending link) contains the trained SimCLR encoders for the seven reference 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.

License

MIT — see LICENSE. The vendored src/ retains its own MIT license (src/LICENSE).

Citation

Once the article/DOI is published...