Subir archivos a "/"
This commit is contained in:
@@ -1,119 +1,149 @@
|
||||
# Deep Learning in Mass Spectrometry Imaging: A Hybrid Julia-Python Workflow
|
||||
# msi-julia-python-cnn — Julia–Python Hybrid Deep Learning Workflow for Mass Spectrometry Imaging
|
||||
|
||||
This repository contains the computational pipeline for the automated anatomical mapping of *Datura innoxia* (toloache) using Mass Spectrometry Imaging (MSI). The workflow addresses the "two-language problem" by leveraging **Julia** for high-performance data preprocessing and **Python** for self-supervised representation learning.
|
||||
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.
|
||||
|
||||
## Key Features
|
||||
- **High-Performance Preprocessing**: Rapid `.imzML` ingestion and TrIQ normalization using Julia.
|
||||
- **Self-Supervised Learning**: Contrastive learning (SimCLR) with an EfficientNet-B0 backbone implemented in PyTorch.
|
||||
- **Reproducibility**: Integrated Docker environment and fixed random seeds for consistent results.
|
||||
- **Performance Benchmarking**: Real-time monitoring of execution time and RAM usage across the hybrid pipeline.
|
||||
- **CUDA/GPU Support**: Optimized for NVIDIA hardware for accelerated training and inference.
|
||||
- **Hybrid Bridge**: Automated data transfer between Julia and Python ecosystems via standardized intermediate files.
|
||||
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.
|
||||
|
||||
## Project Structure
|
||||
- `scripts_julia/`: Julia scripts for mass slice extraction and TrIQ normalization.
|
||||
- `scripts_python/`: Python scripts for SimCLR training, feature extraction, and clustering.
|
||||
- `models/`: Contains the pre-trained weights (`msi_encoder_trained.pth`).
|
||||
- `environment/`: Dependency files (`requirements.txt`, `Project.toml`).
|
||||
- `figures/`: Generated plots and cluster galleries.
|
||||
- `data/`: (User-provided) Location for `.imzML` and mask files.
|
||||
> 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.
|
||||
|
||||
## Reproducibility & Docker (Recommended)
|
||||
To ensure identical environments for both Julia and Python, we provide a unified Docker setup. This setup includes the **JuliaMSI** framework.
|
||||
## Contents
|
||||
|
||||
### Building the Container
|
||||
Before building, ensure the `JuliaMSI` repository is present in the root directory (it was cloned from `https://git.nube-gran.de/Julian/JuliaMSI`).
|
||||
```bash
|
||||
docker build -t msi-hybrid-workflow .
|
||||
```
|
||||
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
|
||||
├── Figure-*.png / Figure4.png / … # manuscript figures (7 total, 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
|
||||
├── .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
|
||||
```
|
||||
|
||||
### Running the Container (CPU Mode)
|
||||
## 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) |
|
||||
|
||||
## Run
|
||||
|
||||
### Native (venv + system Julia)
|
||||
|
||||
```bash
|
||||
docker run -it --rm -v $(pwd):/app msi-hybrid-workflow
|
||||
# one-time setup: Python environment with pinned deps
|
||||
python3 -m venv venv && venv/bin/pip install -r environment/requirements.txt
|
||||
|
||||
# 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
|
||||
```
|
||||
|
||||
### Running the Container (GPU/CUDA Mode)
|
||||
`run_pipeline_wrapper.sh` automatically activates a local `venv/` if present.
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow
|
||||
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=)
|
||||
```
|
||||
|
||||
## Usage Workflow
|
||||
### Add a custom dataset
|
||||
|
||||
### 1. Preprocessing (Julia)
|
||||
Leverage Julia's performance and the **JuliaMSI** framework.
|
||||
|
||||
**Run this clean runtime instantiation command one time to sync everything down to your local directory:**
|
||||
```bash
|
||||
docker run -it --rm -v $(pwd):/app msi-hybrid-workflow \
|
||||
julia --project=/app/environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
|
||||
bash scripts/setup_datasets.sh /path/to/your_data.imzML my_dataset
|
||||
```
|
||||
|
||||
**Run the MSI Bridge (Normalization & PNG Export):**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
julia --threads auto --project=/app/environment /app/scripts_julia/julia_msi_bridge.jl
|
||||
## 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).
|
||||
|
||||
## 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).
|
||||
|
||||
## Manuscript figures
|
||||
|
||||
The manuscript (`MSI_julia-python_mapping.md`, biblatex bibliography `zotero.bib`)
|
||||
|
||||
```
|
||||
Figure-workflow.png # pipeline overview (Fig. \ref{fig:workflow})
|
||||
cross_language_comparison.png# Julia vs Cardinal vs MALDIquant benchmark (Fig. \ref{fig:benchmark})
|
||||
Fig-clustering.png # K-sweep metrics (Fig. \ref{fig:clustering})
|
||||
Figure4.png # leaf t-SNE + representative ion images (Fig. \ref{fig:tsne_clusters})
|
||||
Figure-carpet.png # leaf ion carpet, 1,596 ions at 256×256 (Fig. \ref{fig:carpet})
|
||||
Figure-root-tsne.png # root t-SNE (Fig. \ref{fig:root_tsne})
|
||||
Figure-carpet-root.png # root ion carpet, 858 ions at 256×256 (Fig. \ref{fig:carpet_root})
|
||||
```
|
||||
|
||||
**Optional: Plot Cluster Spectra:**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
julia --threads auto --project=/app/environment scripts_julia/graph_cluster_spectra.jl
|
||||
```
|
||||
|
||||
### 2. Representation Learning (Python)
|
||||
Train the SimCLR encoder to extract morphological features using CUDA.
|
||||
|
||||
**Run CNN Training (SimCLR):**
|
||||
```bash
|
||||
docker run -it --rm \
|
||||
--shm-size=2gb \
|
||||
--gpus all \
|
||||
-v $(pwd):/app \
|
||||
-v msi_torch_cache:/root/.cache/torch \
|
||||
msi-hybrid-workflow \
|
||||
python3 scripts_python/CNN_proof_1.py
|
||||
```
|
||||
*Note: The script automatically detects CUDA and logs per-epoch RAM usage.*
|
||||
|
||||
### 3. Clustering & Validation
|
||||
Determine optimal clusters and perform quantitative validation.
|
||||
|
||||
**Generate Clusters:**
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/cluster_msi_direct.py
|
||||
```
|
||||
|
||||
**Evaluate Clustering:**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/evaluate_clustering.py
|
||||
```
|
||||
|
||||
**Quantitative Validation:**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/quantitative_validation.py
|
||||
```
|
||||
|
||||
### 4. Visualization
|
||||
Generate the final galleries and t-SNE maps.
|
||||
|
||||
**Generate t-SNE Maps:**
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/graficar_tsne_msi.py
|
||||
```
|
||||
|
||||
**Create Cluster Galleries:**
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/visualize_clusters.py
|
||||
```
|
||||
|
||||
## Citation & Acknowledgments
|
||||
This implementation is based on the methodology proposed by:
|
||||
> Hu, H., Bindu, J. P., & Laskin, J. (2022). Self-supervised clustering of mass spectrometry imaging data using contrastive learning. *Chemical Science*, 13(1), 90-98. DOI: [10.1039/d1sc04077d](https://doi.org/10.1039/d1sc04077d)
|
||||
|
||||
## License
|
||||
This project is licensed under the **MIT License**.
|
||||
The two carpet figures were rendered with `make_ion_carpet.py` from the Stage-1 viridis
|
||||
corpus; re-run the script after any preprocessing change to regenerate them from your
|
||||
own run.
|
||||
Reference in New Issue
Block a user