11 KiB
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).
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.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 (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)
# 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:
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)
# 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 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. For each dataset create datos_para_ai/<name>/ containing:
- exactly one
.imzMLfile, and - its sibling
.ibdbinary (the imzML references the.ibdby 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 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.
License
MIT — see LICENSE. The vendored src/ retains its own MIT license (src/LICENSE).