first commit, migrated repository to contain the scripts only

This commit is contained in:
Pixelguy14
2026-10-14 18:15:57 -06:00
parent bab8f4d2a9
commit 6ea14dfb61
54 changed files with 155 additions and 63664 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
.git
.gitignore
.dockerignore
datos_para_ai
ai_data
outputs
models.zip
figures
+1 -1
View File
@@ -3,7 +3,7 @@ data/Leaf.ibd
data/Leaf.imzML.cache
JuliaMSI/
# environment/Manifest.toml is intentionally tracked (reproducible Julia lock)
datos_para_ai/*
ai_data/*
outputs/
venv/
.ipynb_checkpoints/
-31
View File
@@ -1,31 +0,0 @@
# Digital Object Identifiers (DOIs) of Cited Articles
- MALDI imaging mass spectrometry: statistical data analysis and current computational challenges (2012) — <https://doi.org/10.1186/1471-2105-13-S16-S11>
- Cardinal: an R package for statistical analysis of mass spectrometry-based imaging experiments (2015) — <https://doi.org/10.1093/bioinformatics/btv146>
- Identification of Plant Compounds with Mass Spectrometry Imaging (MSI) (2024) — <https://doi.org/10.3390/metabo14080419>
- MALDIquant: a versatile R package for the analysis of mass spectrometry data (2012) — <https://doi.org/10.1093/bioinformatics/bts447>
- Balancing sufficiency and impact in reporting standards for mass spectrometry imaging experiments (2018) — <https://doi.org/10.1093/gigascience/giy102>
- Low-Temperature Plasma Probe for Ambient Desorption Ionization (2008) — <https://doi.org/10.1021/ac801641a>
- Spherical k-Means Clustering (2012) — <https://doi.org/10.18637/jss.v050.i10>
- DeepION: A Deep Learning-Based Framework for Mass Spectrometry Imaging Data Analysis (2021) — <https://doi.org/10.48550/ARXIV.2106.01582>
- Gradient Accumulation for Large Batch Training (2025) — <https://huggingface.co/docs/transformers/training#gradient-accumulation>
- REFORMS: Consensus-based Recommendations for Machine-learning-based Science (2024) — <https://doi.org/10.1126/sciadv.adk3452>
- Low-temperature plasma (LTP) jets for mass spectrometry (MS): Ion processes, instrumental set-ups, and application examples (2017) — <https://doi.org/10.1016/j.trac.2017.01.013>
- Visualizing structure and transitions in high-dimensional biological data (2019) — <https://doi.org/10.1038/s41587-019-0336-3>
- Elucidating the Distribution of Plant Metabolites from Native Tissues with Laser Desorption Low-Temperature Plasma Mass Spectrometry Imaging (2019) — <https://doi.org/10.1021/acs.analchem.8b04406>
- Benchmark datasets for 3D MALDI- and DESI-imaging mass spectrometry (2015) — <https://doi.org/10.1186/s13742-015-0059-4>
- PyTorch: An Imperative Style, High-Performance Deep Learning Library (2019) — <https://doi.org/10.48550/ARXIV.1912.01703>
- Laser Desorption Low-Temperature Plasma Mass Spectrometry Imaging (LD-LTP MSI) of San Pedro cactus (2020) — <https://doi.org/10.5281/zenodo.3625054>
- Histology by Mass Spectrometry: Label-Free Tissue Characterization Obtained from High-Accuracy Bioanalytical Imaging (2010) — <https://doi.org/10.1002/anie.200905559>
- ProteomeXchange Dataset PXD001283 (2014) — <http://proteomecentral.proteomexchange.org/cgi/GetDataset?ID=PXD001283>
- Contrast optimization of mass spectrometry imaging (MSI) data visualization by threshold intensity quantization (TrIQ) (2021) — <https://doi.org/10.7717/peerj-cs.585>
- Open LabBot and RmsiGUI: Community development kit for sampling automation and ambient imaging (2020) — <https://doi.org/10.1016/j.microc.2019.104343>
- Technical Note: mzML and imzML Libraries for Processing Mass Spectrometry Data with the High-Performance Programming Language Julia (2024) — <https://doi.org/10.1021/acs.analchem.3c05853>
- Tropane alkaloid biosynthesis in Datura innoxia Mill. roots and their differential transport to shoots (2021) — <https://doi.org/10.1016/j.phytol.2021.04.012>
- imzML — A common data format for the flexible exchange and processing of mass spectrometry imaging data (2012) — <https://doi.org/10.1016/j.jprot.2012.07.026>
- MSInet: A Self-Supervised CNN Framework Integrating Global and Local Context for Robust Mass Spectrometry Imaging Segmentation (2025) — <https://doi.org/10.1021/acs.analchem.5c04885>
- JuliaMSI: A high-performance graphical platform for mass spectrometry imaging data analysis (2025) — <https://doi.org/10.1016/j.aca.2025.344613>
- EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (2019) — <https://doi.org/10.48550/ARXIV.1905.11946>
- SMART: A data reporting standard for mass spectrometry imaging (2023) — <https://doi.org/10.1002/jms.4904>
- Alkaloid Biosynthesis: Metabolism and Trafficking (2008) — <https://doi.org/10.1146/annurev.arplant.59.032607.092730>
- Exploring the Aβ Plaque Microenvironment in Alzheimer's Disease Model Mice by Multimodal Lipid-Protein-Histology Imaging on a Benchtop Mass Spectrometer (2025) — Pharmaceuticals 18(2):252 — <https://doi.org/10.3390/ph18020252>
-188
View File
@@ -1,188 +0,0 @@
---
title: "A scalable deep learning workflow for mass spectrometry imaging: benchmarking Julia-Python hybrid processing across multi-instrument datasets"
bibliography: zotero.bib
abstract: |
Mass spectrometry imaging (MSI) generates terabyte-scale datasets whose analysis is increasingly bottlenecked by software rather than instrumentation. Most MSI processing pipelines are written in interpreted languages whose memory and speed limits scale poorly with next-generation instruments, and the deep learning ecosystem needed for modern unsupervised analysis lives almost entirely in Python. We present an open-source hybrid Julia-Python workflow that resolves this: a Julia engine performs all high-throughput preprocessing (memory-mapped imzML parsing, peak picking, ion image extraction, TrIQ normalization, and PNG export of every ion map in a single pass) and hands a clean, file-based corpus to a Python self-supervised (SimCLR) convolutional encoder for representation learning and clustering. We benchmark the Julia preprocessing stage on an equalized per-stage workload (imzML load and one ion slice generation at each dataset's reference *m/z*) against Cardinal (R/Bioconductor) and MALDIquant (R) on seven public datasets spanning 0.61–4.4 GB (LD-LTP, AP-SMALDI, MALDI, DESI), covering both centroid and profile acquisitions. Under this equalized workload, the Julia engine generates an ion slice up to two orders of magnitude faster than Cardinal on every dataset and materially faster than MALDIquant, while its memory-mapped loader keeps peak load RAM at only 7–84 MB (lower than Cardinal's lazy loader on all seven datasets) and it completes the additional normalization and export steps within the same memory envelope, all orchestrated by a single reproducible entry point. The Python layer learns a 128-dimensional latent space from the exported ion corpus and clusters the ions into spatially coherent metabolic domains; we detail the algorithmic choices (Group Normalization, gradient accumulation for consumer GPUs, chemical-noise augmentation, and spherical K-Means) that make the deep learning stage tractable on big, zero-padded MSI data. The complete environment is containerized with Docker and released under a permissive license, so the entire analysis (from raw imzML to trained embeddings) is fully reproducible on any hardware. As a demonstration of the workflow's biological utility, we apply it to *Datura innoxia* leaves and roots (2.0 GB and 2.5 GB): self-supervised segmentation recovers spatially coherent metabolic domains that resolve the tropane alkaloid biosynthetic and transport architecture of the tissue.
keywords: mass spectrometry imaging, Julia, Python, SimCLR, hybrid pipeline
---
# Introduction
Mass spectrometry imaging (MSI) produces spatially resolved molecular maps of biological tissue, and advances in ionization sources and mass analyzers have made it possible to record these maps routinely at increasingly fine spatial resolution and mass range. The consequence is a software bottleneck: a single high-resolution acquisition can generate datasets of tens to thousands of gigabytes, and next-generation instruments push the burden of analysis onto the compute stack rather than the instrumentation itself [@alexandrov_maldi_2012]. Most established MSI tooling (both commercial and academic) is written in interpreted languages whose parsing speed, peak RAM consumption, and scalability degrade as file sizes grow into the multi-gigabyte range [@rosas-roman_technical_2024]. Meanwhile, the deep learning ecosystem needed for modern unsupervised analysis of ion images lives almost entirely in Python. At the heart of current MSI software engineering lies the problem: no single ecosystem offers both the throughput required for high-performance binary ingestion and the machine learning maturity required for representation learning.
We address this problem with an open-source hybrid Julia-Python workflow. Julia combines execution speeds comparable to compiled languages with a scientific computing environment [@rosas-roman_open_2020], making it well suited to the memory-mapped parsing and high-throughput ion image extraction that dominate MSI preprocessing; Python contributes the mature artificial intelligence stack (PyTorch) that the representation learning stage requires [@paszke_pytorch_2019]. The two layers are separated by a clean, file-based interface: Julia ingests the raw imzML [@schramm_imzml_2012] binary files, extracts and normalizes every ion image, and exports a deep-learning-ready corpus, which Python consumes for self-supervised learning and clustering. Because the entire pipeline is containerized and released under a permissive license, the full analysis (from raw binary data to trained embeddings) is reproducible on any hardware with the container image alone, which pins every package version and removes manual installation and dependency resolution.
The central objective of this paper is to show how this architecture scales with the two dimensions that dominate modern MSI data: file size and ion count. To evaluate the design honestly, we benchmark the Julia preprocessing stage against Cardinal 3.14.0 [@bemis_cardinal_2015], the standard R/Bioconductor MSI package, and MALDIquant [@gibb_maldiquant:_2012], a widely used R package for MALDI spectra processing, across seven public datasets spanning 0.61–4.4 GB from multiple ionization platforms (LD-LTP, AP-SMALDI, MALDI, DESI) and biological matrices, in both centroid and profile acquisition modes. All three tools run the identical per-stage workload (load, average spectrum, peak detection, ion extraction) on the same hardware, and we report memory and wall-clock transparently, including where the R-based tools are superior. We then describe the algorithmic core of the deep learning stage in detail (the contrastive (SimCLR) objective, the Group-Normalized fully convolutional encoder, gradient accumulation for consumer GPUs, chemical-noise augmentation, and spherical K-Means) and explain how these choices keep a big-data representation-learning workload tractable in RAM and on consumer hardware. As a demonstration of the workflow's biological utility, we apply it to a leaf and root of *Datura innoxia*, a medicinal plant rich in tropane alkaloids [@schlesinger_tropane_2021], and interpret the recovered metabolic domains in terms of alkaloid biosynthesis and transport [@ziegler_alkaloid_2008; @garcia-rojas_identification_2024]. The remainder of this paper details the acquisition parameters, the hybrid implementation, the multi-dataset benchmark, the deep learning workflow, and the unsupervised segmentation of the demonstration datasets.
# Materials and Methods
## Multi-Dataset Benchmarking
To evaluate the scalability and robustness of the Julia-Python preprocessing pipeline, we assembled a diverse collection of seven publicly available MSI datasets covering a range of file sizes (0.61–4.4 GB), ionization sources, mass analyzers, and biological matrices (Table 1). The datasets comprise both centroid and profile acquisitions; all were processed using the same pipeline configuration described in the section "High-Performance Processing and Data Normalization (Julia)". ROI masks derived from the optical image were applied wherever a tissue reference was available (the *Datura* leaf and root, the human colon, and the three mouse tissues) restricting peak picking to pixels inside the tissue; only San Pedro, which lacks an optical reference and was processed without a mask, is an LD-LTP MSI dataset from *Echinopsis pachanoi* cactus stem cross-section (Moreno-Pedraza et al., 2019, Anal. Chem. 10.1021/acs.analchem.8b04406). Peaks were then filtered using the default intensity threshold of 2\% of the base peak.
**Table 1.** Benchmark datasets used in this study.
| Dataset | Ionization | Mass Analyzer | Organism | File Size | Pixels | Polarity | Spatial Res. (µm) | Spectrum Type |
|---------|------------|---------------|----------|-----------|--------|----------|-------------------|---------------|
| Datura Leaf | LD-LTP | Ion Trap (LCQ-Fleet) | *D. innoxia* | 2.0 GB | 17,066 | Positive | 100 | Profile |
| Datura Root | LD-LTP | Ion Trap (LCQ-Fleet) | *D. innoxia* | 2.5 GB | 21,060 | Positive | 100 | Profile |
| San Pedro | LD-LTP | Ion Trap (LCQ-Fleet) | *E. pachanoi* | 1.1 GB | 19,072 | Positive | 300 | Profile |
| Mouse bladder | AP-SMALDI | Orbitrap | *M. musculus* | 833 MB | 34,860 | Positive | 10 | Centroid |
| Human colon | DESI | Orbitrap | *H. sapiens* | 610 MB | 4,288 | Negative | 100 | Centroid |
| Mouse liver | MALDI (neoFlex) | TOF | *M. musculus* | 2.2 GB | 28,587 | Positive | 20 | Profile |
| Mouse stomach | MALDI (neoFlex) | TOF | *M. musculus* | 4.4 GB | 54,245 | Positive | 20 | Profile |
## Computational Environment and Reproducibility
All computational analyses (the high-performance data extraction in Julia, the cross-language benchmark, and the deep-learning representation learning and clustering in Python) were executed on a single workstation with the following specifications: Processor: Intel(R) Core(TM) i5-9400F CPU @ 2.90 GHz (6 cores, 6 threads), Memory: 22 GB DDR4 RAM, Graphics: NVIDIA GeForce RTX 2060 (used for CUDA-accelerated neural network training), and Operating System: Ubuntu 24.04. Both the preprocessing and the machine learning stages therefore ran on identical hardware, so the reported memory and wall-clock measurements are directly comparable.
Reproducibility is a first-class design requirement of the workflow. The entire environment (Julia package set, Python virtual environment with pinned dependencies, R/Bioconductor stack, and system tools) is codified in a Docker image. Because MSI software stacks are notoriously version-sensitive (a change in a peak-picking or normalization library can silently alter every downstream result), the container pins all package versions and orchestrates the seven pipeline stages (see the section "Complete Hybrid Pipeline: From imzML to Metabolic Domains") with a single entry point, so the analysis can be reproduced bit-for-bit on any machine with Docker, independent of the host operating system or pre-installed software. This containerized approach follows the reproducibility recommendations of the SMART protocol [@xi_smart_2023] and the MIAMSIE guidelines for metabolomics data and metadata [@gustafsson_balancing_2018]; we additionally adopt the REFORMS checklist for reporting machine learning in the life sciences [@kapoor_reforms_2024], disclosing model architecture, hyperparameters, data processing, and all evaluation metrics in this manuscript and the repository. The workflow is released as open source under the MIT License, in keeping with the open-science philosophy that reproducible computational methods should be re-usable and auditable by the community.
## High-Performance Processing and Data Normalization (Julia)
We conducted the preprocessing stage using the JuliaMSI framework [@sierra-alvarez_juliamsi_2025], a platform specifically engineered to address the computational bottlenecks found in other programming languages. By leveraging Julia's just-in-time (JIT) compilation and efficient memory-mapping capabilities, we facilitated the rapid ingestion and manipulation of massive imzML binary files. As demonstrated in previous benchmarks [@sierra-alvarez_juliamsi_2025], this architecture provides a significant performance advantage over interpreted environments such as Python or R [@rosas-roman_open_2020], enabling the high-throughput extraction of mass slices without compromising spectral precision.
Previous benchmarks support this choice: Julia-based MSI architectures have been reported up to 5.2-fold faster than R implementations such as RmsiGUI on Linux, and Julia's native parsing of binary spectral data up to 214 times faster than equivalent R code [@sierra-alvarez_juliamsi_2025; @rosas-roman_technical_2024]. This efficiency is what makes the high-throughput bridge to the Python deep learning ecosystem practical at scale.
**Memory-mapped lazy loading.** The core of the Julia engine is a memory-mapped (via the native `Mmap` API) and lazy imzML parser that reads spectra on demand from the on-disk `.ibd` binary file, never materializing the full acquisition in RAM. Spectra are pulled per-pixel as the pipeline walks the pixel grid, and buffer pooling reuses the small working set. This design is what keeps peak resident memory in the tens of megabytes regardless of the on-disk file size (see the section "Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)"), directly addressing the RAM bottleneck that gates MSI analysis on commodity workstations.
**Ion extraction and filtering.** Mass slices are extracted within a user-defined *m/z* range (e.g., 50.0–700.0 for LD-LTP acquisitions), where the upper limit is determined by the instrument's mass range and the absence of significant signals beyond that threshold. To ensure inclusion of only chemically relevant signals and exclude background noise, a Region of Interest (ROI) mask derived from the optical image is applied when available. The average spectrum is computed exclusively from pixels within the tissue mask, and peaks are filtered using an intensity threshold of 2% relative to the base peak. Owing to the spectral binning inherent to the instrument's data acquisition, a single molecular species may be distributed across adjacent *m/z* channels with a characteristic bin spacing (e.g., $\sim0.08$–$0.09$ *m/z* per channel for ion trap instruments). The monoisotopic peak of a target analyte $[M+H]^+$ is detected at its corresponding binned channel, which is independently produced by the centroid-based peak-picking engine and corresponds to the same precursor selected for MS/MS structural confirmation. Adjacent bins capture the isotopic envelope and neighboring noise, illustrating that spectral discretization must be considered when comparing imaging clusters with tandem mass spectrometry identifications.
**TrIQ normalization (Threshold Intensity Quantization).** To mitigate the impact of "hotspots" (stochastic pixels with disproportionately high intensities that obscure lower-abundance metabolic distributions) we applied the dynamic Threshold Intensity Quantization (TrIQ) algorithm [@rosas-roman_contrast_2021]. For each ion map, TrIQ sets a signal threshold at the 98th percentile of its non-zero finite intensities (falling back to the maximum observed intensity when this percentile is zero) and clamps every pixel's intensity to the unit interval $[0, 1]$. This ensures that 98% of the chemical signal is represented within a standardized dynamic range, enhancing the contrast of parenchymal and vascular structures and preventing the neural network from over-fitting to instrumental artifacts.
**Spatial standardization (pristine coordinate mapping).** To ensure compatibility with the deep learning backbone, each normalized ion map was spatially embedded into a standardized 256 $\times$ 256 pixel matrix using strict Zero-Padding, completely avoiding any sub-pixel interpolation. In MSI, the physical laser ablation grid (the native pixel dimensions, e.g., $161 \times 106$ for the *Datura* leaf or $351 \times 60$ for the root) serves as an absolute spatial ground truth. Standard computational interpolation (such as bilinear resizing) forces anisotropic stretching (disproportionately warping the tissue morphology) and introduces artificial floating-point values at the sharp boundaries of the tissue mask. By mapping the raw pixel coordinates directly into the center of a zero-matrix, we preserved the true, undistorted anatomical geometry of each sample while achieving the uniform dimensionality required by the convolutional layers.
## Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)
To contextualize the performance of our Julia-based preprocessing within the current MSI software landscape, we conducted a controlled, three-way benchmark against Cardinal 3.14.0, the standard R/Bioconductor package for MSI analysis [@bemis_cardinal_2015], and against MALDIquant [@gibb_maldiquant:_2012], the standard R package for MALDI spectral processing. All three tools processed the same seven datasets (Table 1) on identical hardware (Intel i5-9400F, 22 GB RAM, Ubuntu 24.04). We designed a strictly equalized per-stage workload restricted to the steps that all three tools perform: (1) imzML file loading, and (2) in-memory extraction of a single target ion image at each dataset's canonical reference *m/z* (a biologically informative ion per sample: 304.17 for the *Datura* leaf and root, 885.5 for the human colon, 716.05 for the mouse bladder, 796.18 for the mouse liver, 804.3 for the mouse stomach, and 212.14 for San Pedro (mescaline [M+H]⁺, LD-LTP reference ion [@moreno-pedraza_elucidating_2019]); tolerance 0.1 Da), plus the average spectrum and peak detection used to select the slice. The Julia engine runs the JuliaMSI `MSI_src` implementation, whose memory-mapped (`Mmap`) lazy loader and buffer pooling read spectra on demand from the on-disk `.ibd` file; for Cardinal, which stores centroid-mode spectra per-pixel as a list, the average spectrum was computed by binning pixel-wise m/z values onto a common 0.01 Da grid and the target ion image was extracted with the native 3.x API (`bin()` + `sliceImage()`); for MALDIquant, spectra were read into `MassSpectrum` objects and processed with `reduceIntensity`/`detectPeaks`, and the ion image was recovered from the aligned spectrum objects. Load memory (VmRSS delta) and wall-clock time were measured per stage via `/proc/self/status`, with each tool run in isolation. This apples-to-apples design deliberately excludes Julia-only steps (TrIQ normalization and PNG export) so that the comparison reflects identical computational work.
## Complete Hybrid Pipeline: From imzML to Metabolic Domains
The full workflow is orchestrated by a single entry point, `run_full_pipeline.sh`, which chains seven stages that consume only the raw imzML/ibd file pair and produce the final metabolic segmentation. This end-to-end integration—from binary ingestion to trained convolutional embeddings—is the central differentiation of the framework. In Stage 1, the imzML file is memory-mapped and parsed by the Julia engine, which computes the average spectrum across all pixels (restricted to the ROI mask when available), selects peaks above a 2% threshold of the base peak, extracts an ion image for every detected peak within a 0.05 Da tolerance, applies TrIQ normalization per ion map, spatially standardizes each map to a 256×256 grid by strict zero-padding, and exports each normalized ion image twice: a grayscale PNG reserved exclusively for the deep learning stage, and a viridis-colored PNG for visualization. For imzML variants that the Julia parser rejects, the stage transparently falls back to an equivalent Python preprocessor, guaranteeing robustness across instrument formats. Because each ion image is exported as a small PNG, the file-based interface between Julia and Python is also a natural memory bound: neither layer ever needs to hold the whole acquisition in RAM simultaneously. In Stage 2, the exported ion images form the training corpus of a custom 4-layer Group-Normalized fully convolutional encoder trained with the NT-Xent contrastive loss (SimCLR), projecting each ion map into a 128-dimensional latent space. Stage 3 selects the optimal number of metabolic clusters via a multi-metric sweep (Silhouette, Davies-Bouldin, Calinski-Harabasz) over k = 2,…,20, computed per dataset from the learned latent space. Stage 4 projects latent embeddings to two dimensions via t-SNE for visualization. Stage 5 validates the clustering by testing spatial co-localization of isotopologue pairs against random ion pairs (Welch's t-test) and against a PCA baseline, including stability analysis via Adjusted Rand Index across seeds. Stage 6 assembles representative ion images per cluster to visually confirm anatomical domains, and Stage 7 plots mean spectra per cluster and the full average spectrum for biological interpretation. In summary, the Julia layer performs all high-throughput binary parsing and image export, while the Python layer performs representation learning and statistical validation. The design eliminates the traditional "two-language problem" by keeping the expensive preprocessing in a compiled language and the machine learning in the ecosystem where the AI tooling is mature, with a clean, file-based interface (normalized PNG images) between them.
## Self-Supervised Representation Learning (Python)
We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorch_2019], adapting the framework to the unique properties of mass spectrometry imaging. This section details the algorithm and the specific hardware- and data-related problems each design choice solves.
**Problem 1: zero-padded background biases normalization statistics.** A custom Fully Convolutional Contrastive Network was engineered to replace standard heavy computer vision backbones. Crucially, all standard batch normalization blocks were replaced with Group Normalization (GroupNorm) layers (8 groups per layer). In datasets characterized by massive empty, zero-padded backgrounds, standard Batch Normalization calculates running statistics that become overwhelmingly biased by the blank space, leading to gradient instability and the artificial clustering of the background mask. Group Normalization computes statistics per individual image slice, mathematically neutralizing the static background and forcing the network to optimize strictly on the high-variance internal biological structures. The network concludes with an Adaptive Average Pooling layer and a 2-layer MLP to project the spatial features into a 128-dimensional latent space (Table 2).
**Problem 2: consumer GPU memory is insufficient for large batches.** To enable training on consumer-grade hardware (NVIDIA RTX 2060 / RTX 3050 Mobile, 4–6 GB VRAM), a gradient accumulation strategy was employed. Rather than fitting an effective batch of 32 images simultaneously into GPU memory (which would trigger a CUDA out-of-memory error), the engine processes 8 images physically per step and accumulates gradients over 4 consecutive forward passes before executing a single optimizer update, as described in the Hugging Face documentation [@huggingface_gradient_2025]. This is mathematically equivalent to training with a true batch size of 32 while using only a quarter of the VRAM.
**Problem 3: spatial augmentations corrupt the co-localization signal.** Standard computer vision augmentation libraries (e.g., Torchvision) apply spatial transformations (random rotations, horizontal/vertical flips, and random crops) as a default strategy to promote translation and rotation invariance. This practice is explicitly and deliberately incompatible with our co-localization objective and was therefore completely prohibited. In spatial metabolomics, the absolute $(x, y)$ pixel grid of a single-slice acquisition is the immutable biological ground truth [@alexandrov_maldi_2012]. Our framework operates strictly within the paradigm of Camp A (Single-Experiment Co-localization): the goal is not to learn features that are invariant to spatial position, but precisely to learn which ions share the same position. A random 90° flip applied to two different views of the same image would teach the encoder that the top-left quadrant is equivalent to the bottom-right quadrant, destroying the spatial registration matrix and corrupting the co-localization signal. The exclusive use of chemical-noise augmentations (which simulate detector artifacts while leaving the coordinate grid untouched) is therefore a deliberate, foundational design choice, consistent with established best practices in MSI deep learning [@hu_deepion_2021].
**Problem 4: dataset sizes are moderate but augmentation makes them effectively infinite.** The training corpus typically comprises hundreds to thousands of ion images that pass the 2% intensity threshold filter and ROI mask selection (e.g., 1,596 for the *Datura* leaf, 858 for the root, 775 for San Pedro). This number is mathematically sufficient for this self-supervised task for two compounding reasons. First, the custom 4-layer fully convolutional architecture is a lightweight, low-dimensional feature extractor. Unlike overparameterized ImageNet backbones such as EfficientNet-B0 [@tan_efficientnet_2019] (which carry over 5 million parameters trained for 1,000 natural image categories), our encoder is purpose-built to extract a compact morphological fingerprint; it requires far fewer samples to converge on a meaningful manifold. Second, the `apply_msi_chemical_noise` augmentation pipeline functions as a stochastic, infinite data generator. Because intensity scaling factors, Poisson noise seeds, and dropout masks are sampled randomly at each epoch, the network never encounters the exact same image representation twice, exponentially expanding the effective training pool and providing robust protection against overfitting.
**Table 2.** Training hyperparameters and model configuration for the SimCLR-MSI workflow.
| Parameter | Value / Configuration |
|-----------|------------------------|
| Backbone Architecture | Custom 4-Layer CNN with Group Normalization |
| Projection Head | 2-layer MLP (Linear 256-ReLU-Linear 128) |
| Input Image Resolution | 256 × 256 pixels (Zero-Padded) |
| Optimization Algorithm | AdamW Optimizer |
| Learning Rate | $3 \times 10^{-4}$ with Cosine Annealing |
| Physical Batch Size / Accumulation Steps | 8 / 4 (Effective Batch Size: 32) |
| Temperature ($\tau$) | 0.5 (NT-Xent Loss) |
| Training Duration | 60 Epochs |
| Data Augmentations | Intensity Scaling (0.8×–1.2×), Poisson Shot Noise, Low-Signal Dropout |
**Clustering on the hypersphere.** The SimCLR objective (NT-Xent Loss) trains the encoder to project features onto a unit $L_2$ hypersphere, where semantic proximity is defined by directional cosine angles rather than Euclidean distances. The application of Principal Component Analysis (PCA) prior to clustering is a dimensionality reduction step that, as a side effect, breaks this hypersphere geometry by altering the magnitudes of the latent vectors. To restore geometric integrity, every feature vector was re-normalized to unit length after PCA transformation and before K-Means assignment. This converts standard Euclidean K-Means into a functional Spherical K-Means [@hornik_spherical_2012], ensuring that cluster centroids are determined by cosine similarity rather than arbitrary vector magnitudes (a critical requirement for correctly grouping ions with identical spatial silhouettes but different absolute intensities.
**Selecting the number of clusters.** To determine the optimal number of clusters (k), we performed a multi-metric systematic sweep from k = 2 to k = 20, evaluating the Silhouette Score, Davies-Bouldin Index, and Calinski-Harabasz Index at each value. Because k = 2 conflates an entire tissue into a single "tissue vs background" split and fails to resolve any internal anatomical compartment, the number of metabolic clusters is adopted from the joint optimum of the Davies-Bouldin and Calinski-Harabasz indices, which trade cluster compactness against anatomical resolution. This multi-metric, data-driven selection is applied independently per dataset, because the optimal number of metabolic domains is a property of each tissue architecture. The seven datasets returned optima ranging from k = 2 (San Pedro) to k = 20 (human colon), as summarized in Figure 2 and discussed in the section "Clustering Validation Across the Seven Datasets".
## Application Dataset: LD-LTP-MSI of *Datura innoxia*
To demonstrate the biological utility of the workflow, we acquired an MSI dataset from a *Datura innoxia* leaf, a medicinal plant whose root-biosynthesized tropane alkaloids are transported to the shoot [@schlesinger_tropane_2021], and whose imaging has previously been pursued with laser desorption low-temperature plasma (LD-LTP) techniques [@moreno-pedraza_elucidating_2019]. We performed imaging using an LD-LTP-MSI system coupled to an LCQ Fleet Ion Trap mass spectrometer (Thermo Scientific). The custom ionization source consisted of a Low-Temperature Plasma (LTP) probe [@harper_low-temperature_2008] and a continuous-wave violet laser (400–450 nm, 1.0 W). The LTP probe was operated with helium (0.1 L/min) at 3.3 kV and ~13 kHz, positioned at a 45° angle and 4 mm from the ion transfer capillary [@martinez-jarquin_low-temperature_2017]. The laser was oriented at 90° to the sample surface at a focal distance of 9 cm, producing a spot size of ~22 µm. We acquired data in positive ion mode (*m/z* 50–700) with a spatial resolution of 150 µm for the leaf sample.
## Benchmark Dataset: LD-LTP-MSI of San Pedro Cactus (*Echinopsis pachanoi*)
The San Pedro cactus (1.1 GB) dataset was acquired using the same LD-LTP-MSI platform described in Moreno-Pedraza et al. [@moreno-pedraza_elucidating_2019] at CINVESTAV Irapuato. A cactus cross-section (41.70 × 42.00 mm², 2.5 cm thick) was dissected with a scalpel, cleaned with a paper towel, and a wet filter paper was placed underneath to avoid dehydration during analysis. The LD-LTP system used a CW 405 nm UV diode laser (Fermion III Series, Micro Laser Systems Inc., up to 450 mW output) with a plano-convex lens (f = 50 mm) focused perpendicular to the sample, and a 3D-printed LTP probe operated at 0.1 L/min helium, 7 kV, 10 kHz, positioned at 45° and 2 mm from the MS inlet. An LCQ-Fleet ion trap MS (Thermo Scientific) was used in positive mode, *m/z* 50–500, full scan continuous mode (capillary voltage 55 V, capillary temperature 200 °C, tube lens 25 V, max injection time 300 ms, 2 microscans, AGC enabled). Imaging was performed with a RepRap-based stage in a meandering pattern at 300 × 300 µm step width (pixel size), acquiring 19,072 pixels over 164 min. Laser intensity was set to 317.86 MW cm⁻². Mescaline was detected at *m/z* 212.14 [M+H]⁺ and confirmed by MS² fragmentation and GC/EIMS of dissected chlorenchyma/parenchyma.
## Benchmark Datasets: MALDI-TOF MSI of Mouse Liver and Stomach on Bruker neoFlex
The mouse liver (2.2 GB) and mouse stomach (4.4 GB) datasets were acquired on a Bruker neoFlex MALDI-TOF mass spectrometer (Bruker Daltonics) at the Biomolecular Analysis Facility Core, W.M. Keck Biomedical Mass Spectrometry Laboratory, University of Virginia School of Medicine. Liver and stomach tissues were obtained from mice and, after being washed with 1× PBS, were embedded in a mold with 20% fish gelatin and frozen on dry ice. They were subsequently transferred to −20 °C for one hour and stored at −80 °C until use. Sectioning was performed on a microtome cryostat equipped with a blade holder (Epredia CryoStar NX50 OP 957250), and the sections were carefully mounted using a fine paintbrush to pull the tissues onto an Intelligent Slide previously cooled to −15 °C.
The DHB matrix (2,5-dihydroxybenzoic acid) was applied to both tissues using the Bruker method on an HTX Imaging M3+ Sprayer. Briefly, the method consists of dissolving 15 mg/mL of DHB in 90% ACN / 0.1% TFA, with a flow rate of 125 µL/min, 14 passes in a criss-cross pattern, and a pressure of 10 psi. Subsequently, the slides were dried in a vacuum desiccator for 40 minutes before data acquisition on the neoFlex.
Data acquisition on the neoFlex was performed in reflector positive-ion mode across *m/z* 400–1400 at 20 µm spatial resolution, using 35% laser power, 2,000 laser shots per pixel at 10,000 Hz, with external calibration via red phosphorus (Bruker method RedP_Positive_0_to_2000) and the Bruker Imaging_Lipids_pos_R.par acquisition method [@muller_neoflex_lipid_2025].
# Results and Discussion
## Computational Benchmark: Julia vs Cardinal and MALDIquant Across Seven Datasets
The controlled three-way benchmark (Figure 1) evaluates the identical preprocessing workload (imzML load plus one in-memory ion slice at each dataset's canonical reference *m/z* (see the section "Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)", tolerance 0.1 Da)) on seven datasets spanning an order of magnitude in file size (0.61–4.4 GB). Load memory (VmRSS delta) and wall-clock time were measured on the same hardware (Intel i5-9400F, 22 GB RAM). The results establish three findings, all consistent across every dataset in the benchmark figures, which show the Julia engine ahead in both memory and ion-slice throughput on all seven samples.
First, the Julia ion-slice operation is one to two orders of magnitude faster than Cardinal on every dataset (0.00009–0.32 s vs 6.3–19.5 s) and materially faster than MALDIquant (1.3–3.9 s) (54- to 79,949-fold faster than Cardinal depending on the dataset (Figure 1A). This is the dominant per-ion cost when exporting a full ion corpus, and therefore the step that decides whether processing a full MSI dataset is feasible in reasonable wall-clock time: at Cardinal's per-slice cost, exporting the 1,596-ion *Datura* leaf corpus would take hours, whereas the Julia engine completes the export in minutes within a single pass.
Second, peak load resident memory (VmRSS) favors Julia unconditionally (Figure 1B): the memory-mapped loader keeps the working set at 7–84 MB, below Cardinal's ~120 MB on all seven datasets and far below MALDIquant (up to 4.0 GB on the Datura root), which ran out of memory on the two heaviest samples (mouse liver and mouse stomach). Because the memory-mapped parser never materializes the full acquisition, peak RAM is decoupled from on-disk file size: the largest dataset (mouse stomach, 4.4 GB) is processed at 83 MB of resident RAM. This is the property that makes the pipeline runnable on commodity workstations and laptops.
Third, the differentiation is not universal raw wall-clock speed (Cardinal's fully in-memory load is faster in wall time than the Julia lazy mapping on the larger files (0.9–2.0 s vs 0.006–1.1 s), because it reads the whole file eagerly (but that eager scheme is precisely what drives its larger resident set). The value of the Julia-Python pipeline is therefore its ability to complete the *entire* analytical job (ion extraction, TrIQ normalization, and PNG export of every ion image in a deep-learning-ready format) within the same measured RAM envelope, in a single memory-mapped pass that requires no staged intermediate files and no manual memory management. We report the measurements transparently in the benchmark repository, including those that favor the R ecosystem.
## Clustering Validation Across the Seven Datasets
Because the deep learning stage is a core contribution of this workflow, we report its behavior across all seven benchmark datasets rather than on a single tissue. For each dataset, Stage 3 (see the section "Complete Hybrid Pipeline: From imzML to Metabolic Domains") evaluated the learned latent space with a K-sweep (k = 2–20) and three internal metrics (Silhouette, Davies-Bouldin, and Calinski-Harabasz) (Figure 2 shows the sweeps for the two *Datura* demonstration datasets). The optimal K is a property of each tissue's architecture and varies strongly across datasets: the two-zone tissues (San Pedro stem, *Datura* root) converge at low k (k = 2 and k = 3, with all three metrics in agreement), whereas the histologically complex tissues saturate at the upper bound of the sweep (human colon at k = 20, mouse bladder at k = 19–20), and the *Datura* leaf and the two mouse tissues fall between (k = 5 and k = 7–12 by the Davies-Bouldin/Calinski-Harabasz optima). The multi-metric sweep is therefore not cosmetic: it is required to scale the workflow to arbitrary tissues without manual tuning, and the pipeline adopts the joint Davies-Bouldin/Calinski-Harabasz optimum as the metabolic cluster count, since the Silhouette optimum of k = 2 merely reproduces the trivial tissue-versus-background split.
The learned embeddings systematically outperform a PCA baseline on the same features (see the section "Self-Supervised Representation Learning (Python)") for every dataset, and cluster assignments are stable across random seeds (Adjusted Rand Index $\geq 0.9$). Isotope co-localization validation (a natural ground truth requiring no annotation) is positive across datasets and reaches high significance where the ion corpus is large enough to support the statistical test (Welch's t-test, $p < 10^{-6}$ for the human colon, $p < 10^{-300}$ for the *Datura* leaf). These results show that the deep learning stage scales from the smallest (610 MB, 682 ions) to the largest (4.4 GB) datasets in the benchmark without parameter changes, and that the file-based Julia-to-Python handoff keeps the whole analysis reproducible in a single container.
**Figure 1.** Equalized three-way benchmark of JuliaMSI vs Cardinal (R) and MALDIquant (R) preprocessing under an identical per-stage workload (load + average spectrum + peaks + one ion slice at each dataset's canonical reference *m/z*, tolerance 0.1 Da) across seven public datasets ordered by file size (lightest to heaviest). (A) Slice-generation throughput (slices per second, log scale): the Julia engine generates ion slices one to two orders of magnitude faster than Cardinal on every dataset (54- to 79,949-fold) and materially faster than MALDIquant, a difference that dominates the cost of exporting a full ion corpus. (B) Peak load resident RAM (VmRSS, MB, log scale): the memory-mapped lazy loader keeps the working set at 7–84 MB (below Cardinal's ~120 MB on every dataset and far below MALDIquant (up to 4.0 GB). Red X markers indicate the datasets that MALDIquant could not process (mouse liver and mouse stomach), which exhausted the 22 GB reference machine.
![Figure 1: Benchmark of JuliaMSI vs Cardinal and MALDIquant.](figure1.png){width=16cm}
**Figure 2.** Clustering validation of the two *Datura innoxia* demonstration datasets via K-sweep (k = 2–20). Panels A–D show the *Datura* leaf; panels E–H show the *Datura* root. (A, E) Elbow method (inertia); (B, F) Silhouette score; (C, G) Davies-Bouldin index; (D, H) Calinski-Harabasz index. The joint Davies-Bouldin/Calinski-Harabasz optimum is adopted as the number of metabolic clusters, since the Silhouette optimum of k = 2 always reproduces the trivial tissue-versus-background split. This selects k = 5 for the leaf (Davies-Bouldin 0.9124; Calinski-Harabasz 1304.29) and k = 3 for the root (0.8518; 868.21), reflecting the distinct metabolic architecture of the two tissues.
![Figure 2: K-sweep clustering validation for the Datura leaf (A–D) and root (E–H).](figure2.png){width=16cm}
## *Datura innoxia* Ion Image Gallery
**Figure 3.** Ion images of key tropane alkaloids and precursors in *Datura innoxia*. (A) *Datura* leaf: photograph with 1 cm scale bar, followed by ion slices of scopolamine (*m/z* 304.17), atropine/hyoscyamine (*m/z* 290.08), cuscohygrine (*m/z* 225.92), 6-hydroxyhyoscyamine (*m/z* 306.25), tropine (*m/z* 142.08), and tropinone (*m/z* 140.17). (B) *Datura* root: photograph with 5 mm scale bar, followed by ion slices of atropine/hyoscyamine (*m/z* 290.08), tropinone (*m/z* 140.17), tropine (*m/z* 142.08), and cuscohygrine (*m/z* 225.92). All ion images are TrIQ-normalized, zero-padded to 256 × 256, and displayed with the viridis colormap.
![Figure 3: Datura leaf and root photographs and key ion images.](figure3.png){width=16cm}
## Multi-Dataset Unsupervised Segmentation
The segmentations of the two most architecturally demanding benchmark tissues are shown in Figure 4: the learned 128-dimensional embeddings projected with t-SNE and colored by the K-Means assignment at each dataset's adopted K, alongside biologically interpretable ion images from distinct metabolic domains of each tissue. For both the mouse bladder (AP-SMALDI) and the human colon (DESI), the workflow recovers spatially coherent, interpretable metabolic domains without any manual annotation or dataset-specific parameter tuning, resolving 20 domains per tissue. The t-SNE projections display the clearly separated, tissue-specific cluster geometries discussed below (circular arrangements for the bladder and colon) confirming that the recovered clusters are discrete metabolic compartments rather than arbitrary bands of a continuum.
**Figure 4.** Unsupervised segmentation of the two fine-grained benchmark tissues, the mouse bladder (AP-SMALDI) and the human colon (DESI). For each dataset, the left panel is the t-SNE projection of the SimCLR latent space colored by K-Means cluster assignment at the adopted K; the right panels show biologically interpretable ion images (viridis, putative compound and adduct) from four distinct metabolic domains of each tissue (the sphingomyelin SM(34:1) (d18:1/16:0, [M+H]+ and [M+Na]+), the phosphatidylcholine PC(34:1), and the reference phospholipid for the bladder; the phosphatidylinositols PI(38:4) (18:0/20:4) and PI(36:2), the phosphatidylglycerol PG(34:1), and the phosphatidylserine PS(36:1) (18:0/18:1) for the colon) illustrating the distinct spatial morphology of each recovered metabolic domain. The workflow resolves the histologically complex architecture of both tissues (20 metabolic domains for each) with the same Julia preprocessing, the same SimCLR encoder, and the same K-selection logic, requiring no manual tuning.
![Figure 4: t-SNE segmentations and representative ion images for the mouse bladder and human colon.](figure4.png){width=16cm}
The recovered domains are not only computationally validated but also biologically interpretable in every benchmark tissue, without any tissue-specific tuning. In the San Pedro cactus stem (*Echinopsis pachanoi*), the joint Davies-Bouldin/Calinski-Harabasz optimum selects k = 2, partitioning the 775-ion corpus into two metabolic domains (Clusters 0 and 1, with 358 and 417 ions, respectively). The cactus stem is anatomically organized as a two-compartment structure (the photosynthetically active cortex with the underlying vascular system and the inner water-storage pith) and the mescaline region (m/z ≈ 212.1) falls in Cluster 0, consistent with the star-like mescaline distribution around the vascular bundles originally reported for this specimen [@robert_winkler_laser_2020; @moreno-pedraza_elucidating_2019]. This star-like patterning, where mescaline concentrates around vascular bundles in the cortical region, reflects the plant's metabolic zonation and has been previously documented in the literature [@moreno-pedraza_elucidating_2019]. In the mouse liver (MALDI-TOF), the k = 7–8 optimum resolves the lobular architecture of hepatic zonation, in which periportal and pericentral hepatocytes differ in their metabolic programs, and the reference ion at m/z 796.18 is placed in Cluster 2. The mouse stomach (MALDI-TOF, DHB matrix) is segmented into k = 12 domains, consistent with the regional organization of the gastric mucosa (forestomach, corpus, and antrum) with the reference ion m/z 804.3 distributed between Clusters 7 and 10. For the two high-resolution benchmark specimens, the workflow resolves 20 domains each. In the mouse urinary bladder (AP-SMALDI [@rompp_histology_2010; @rompp_proteomexchange_2014]), the domains follow the layered histology of the bladder wall (urothelium, lamina propria, detrusor muscle), and the reference phospholipid at m/z 716.05 falls in Cluster 4. In the human colorectal adenocarcinoma (DESI [@oetjen_benchmark_2015]), the 20 domains recover the molecular heterogeneity of the tumor and its surrounding stroma, and the anion at m/z 885.55 (consistent with the glycerophospholipid PI(18:0/20:4) signature commonly observed in malignant colon epithelium) is confined to Cluster 2.
### Interpreting the t-SNE Embedding Shapes
Reviewers from a computer vision background may expect an optimal unsupervised result to yield discrete, well-separated "blobs" in the t-SNE projection (and this is exactly what the workflow produces on all seven datasets). The K-Means domains appear as clearly separated, self-contained groups in every projection, with no overlapping or interleaved clusters, so the discretization into metabolic domains does not depend on any arbitrary threshold along a continuous gradient. Beyond this clean separation, each tissue imprints a characteristic global geometry onto its learned embedding, and these shapes are consistent and reproducible: the human colon and the mouse bladder organize into closed, roughly circular arrangements; the *Datura* leaf resolves into a donut-shaped (annular) structure; the mouse liver, the *Datura* root, and the San Pedro cactus fold into ear-shaped configurations; and the mouse stomach extends into an elongated, fish-shaped topology. Because the same encoder and the same K-selection logic were applied to every sample, these consistent, dataset-specific geometries indicate that the contrastive stage captures genuine tissue-level structure rather than dataset-specific artifacts [@moon_visualizing_2019]. The application of K-Means onto each of these well-separated manifolds is therefore interpreted as the identification of independent, biologically meaningful chemical compartments, not as the arbitrary banding of an amorphous continuum.
## Advantages of Contrastive Learning over Linear Decomposition
Furthermore, the superiority of the self-supervised contrastive learning approach over traditional linear methods, such as Principal Component Analysis (PCA), lies in its fundamental shift from intensity-driven variance to morphological feature extraction [@shah_msinet_2025]. To establish a fair quantitative baseline, we compared SimCLR and PCA embeddings under identical conditions: both feature sets were projected to the same dimensionality via PCA and clustered using standard k-means at the pipeline-selected k. For the leaf (k = 5), the SimCLR pipeline achieved a Silhouette Score of 0.3703, compared to the PCA baseline of 0.1641, while the Calinski-Harabasz Index rose from 351.56 to 1304.29. The Davies-Bouldin Index for SimCLR was 0.9124 versus 1.7096 for PCA, confirming that the combination of contrastive feature learning produces substantial improvements in spatial separation. Furthermore, the SimCLR embeddings exhibited exceptional stability across multiple random seeds, with a mean Silhouette Score of 0.3703 $\pm$ 0.0000 and an Adjusted Rand Index (ARI) of 0.9959 between runs, indicating that the learned representations are highly reproducible and independent of stochastic initialization. The same superiority holds for the root at its pipeline-selected k = 3 (Silhouette 0.4716 vs 0.2871; Davies-Bouldin 0.8518 vs 1.2417; Calinski-Harabasz 868.21 vs 626.25; mean Silhouette 0.4716 $\pm$ 0.0000; ARI 1.0000), showing that the advantage is not specific to a single tissue.
While PCA relies on magnitude-dependent variance (essentially grouping ions based on their absolute 'brightness' and pixel-to-pixel correlation) it is highly sensitive to the dynamic range of the detector and often fails to resolve low-abundance metabolites that do not contribute significantly to the total variance. In contrast, the custom SimCLR architecture prioritizes the underlying spatial topographies (morphological fingerprints) of the ion images. This allows the model to project ions with vastly different absolute intensities but identical anatomical 'silhouettes' (such as a primary alkaloid and its trace-level isotopes or precursors) into adjacent coordinates within the latent space. By decoupling chemical distribution from absolute abundance, this workflow captures the structural integrity of the tissue, offering a more robust and biologically grounded segmentation that traditional linear or intensity-based algorithms cannot easily achieve.
## Case Study: *Datura innoxia* Segmentation
The unsupervised decomposition of the latent space of the *Datura innoxia* leaf yielded five distinct molecular domains (Clusters 0–4), each representing a reproducible and spatially resolved chemical pattern across the leaf surface (Figure 3A). These clusters capture the heterogeneity of ion distributions and reveal a structured organization of metabolites at the tissue level. The key tropane alkaloids scopolamine (*m/z* 304.0), atropine/hyoscyamine (*m/z* 290.08), and 6-hydroxyhyoscyamine (*m/z* 306.25) are co-localized in a single domain (Cluster 2), while the biosynthetic precursors tropinone (*m/z* 140.17), tropine (*m/z* 142.08), and cuscohygrine (*m/z* 225.92) occupy three distinct domains (Clusters 0, 3, and 4). This co-localization is consistent with acropetal transport of the alkaloids through the vascular system and their distribution across the leaf mesophyll [@ziegler_alkaloid_2008; @schlesinger_tropane_2021].
To confirm the identity of the tropane alkaloids *in situ*, we subjected the precursor ion at *m/z* 304.17 to tandem mass spectrometry (MS/MS) at a collision energy of 20 eV. The resulting fragmentation pattern from the leaf surface showed an excellent spectral match with the commercial scopolamine reference standard, and the diagnostic product ions across the *m/z* 80–320 range confirm the unambiguous structural identification of scopolamine directly from the plant surface without the need for extensive sample preparation [@garcia-rojas_identification_2024]. Critically, the MS/MS precursor at *m/z* 304.17 corresponds exactly to one of the centroid bins independently generated by the pipeline's peak-picking algorithm, producing the ion image `ion_304.17.png`. The adjacent bins (*m/z* 304.00–304.42) capture the isotopic envelope of scopolamine and are also structurally consistent with this assignment, as confirmed by their shared vascular-related spatial patterns.
Quantitatively, the leaf validation signature is strong: a global statistical analysis across 1,394 discovered isotopic pairs yielded a mean latent distance of $0.2687$, compared to $0.5715$ for random ion pairs, achieving profound statistical significance (Welch's t-test, $p < 10^{-300}$). Of these, 1,353 pairs (97.1\%) passed strict structural validation (Cosine Similarity $\geq 0.80$), including Atropine (*m/z* 290.08) and its $+1$ isotope (*m/z* 291.17) with a cosine similarity of 0.9959. The pipeline was applied identically to the *Datura innoxia* root dataset (2.5 GB, 21,060 pixels, 858 ion images), where all three metrics agree on k = 3 and the segmentation reflects the longitudinal architecture of the root rather than a single biosynthetic site (Figure 3B). The three recovered domains differ in their spatial polarity: Cluster 2 (the largest domain, 351 ions) concentrates its ion presence close to the stem junction; Cluster 1 is enriched at the root apex and markedly weaker at the stem connection; and Cluster 0 combines both features, presenting signal both at the root apex and at the stem junction. These domains partition the alkaloid biosynthetic machinery accordingly: tropinone (*m/z* 140.17) and tropine (*m/z* 142.08) fall in Cluster 0, the both-zones domain, while cuscohygrine (*m/z* 225.92) and atropine/hyoscyamine (*m/z* 290.08) fall in Cluster 1, the apex-enriched domain. Scopolamine is absent from the root ion corpus because the root spectrum is dominated by the biosynthetic precursors (the base peak is tropine, *m/z* 142.08), so the scopolamine channel reaches only 1.5% of the base-peak intensity and falls below the 2% cutoff (consistent with the classical model in which scopolamine is produced in the root but accumulates distally in the shoot [@schlesinger_tropane_2021]). The root result demonstrates that the workflow generalizes across tissues without any parameter change.
# Data and Code Availability
In keeping with the open-science philosophy that motivates this work, all code is released under the MIT License, and every result in this manuscript is reproducible from the repository alone. The GitHub repository at https://github.com/anomalyco/msi-hybrid-workflow contains: (i) the Julia preprocessing engine and Python preprocessing fallback; (ii) the Python SimCLR training, clustering, validation, and visualization scripts; (iii) the benchmark harness used for the Julia-vs-Cardinal-vs-MALDIquant comparison, including the exact measurement protocol (VmRSS via `/proc/self/status`) and raw per-stage measurements for all seven datasets; (iv) pre-trained encoder weights; and (v) a single entry point, `run_full_pipeline.sh`, that reproduces the full analysis from raw imzML to final segmentation.
The complete computational environment is containerized: the Docker image pins the Julia package set, the Python virtual environment, the R/Bioconductor stack, and all system-level dependencies. Building the image and running the container reproduces every figure, table, and quantitative result reported here on any host with Docker, without manual installation or version resolution. All seven benchmark datasets are public: the LD-LTP *Datura* leaf and root, the MALDI San Pedro cactus, the MALDI mouse liver and mouse stomach, the AP-SMALDI mouse bladder, and the DESI human colon datasets, with access instructions in the repository. All raw data, intermediate artifacts, and figures are archived for long-term access.
# Funding
This work was supported by the University of Virginia's School of Medicine grant to the Biomolecular Analysis Facility Core and W.M. Keck Biomedical Mass Spectrometry Laboratory (RRID:SCR_025476).
# Conclusion
The equalized benchmark against Cardinal (R/Bioconductor) and MALDIquant (R) (identical per-stage workloads on the same hardware across seven public datasets spanning 0.61 to 4.4 GB) shows that the Julia engine generates ion slices one to two orders of magnitude faster than Cardinal on every dataset (0.00009–0.32 s vs 6.3–19.5 s, 54- to 79,949-fold) while keeping peak load resident memory (VmRSS) at 7–84 MB (lower than Cardinal's ~120 MB and far below MALDIquant's up to 4.0 GB) and it completes the additional normalization and export steps within the same memory envelope. We report the per-stage timings transparently, including where the R ecosystem is competitive (Cardinal's eager load is faster in wall time on the larger files), and we note that MALDIquant exhausted the reference machine on the two heaviest datasets. This decoupling of peak RAM from on-disk file size is what makes the workflow scale from commodity laptops to GPU-equipped workstations, and the containerized environment and permissive open-source license allow any researcher to rebuild the entire analysis (from raw imzML to trained embeddings and final segmentation) on any hardware.
On the deep learning side, we have shown how the Python stage is engineered for big, zero-padded MSI data: Group Normalization to neutralize the background mask, gradient accumulation to fit large effective batches on consumer GPUs, chemical-noise-only augmentation to preserve the spatial co-localization signal, and spherical K-Means to respect the latent hypersphere geometry. Applied across all seven benchmark datasets, the workflow selects its own number of metabolic domains per tissue, systematically outperforms a PCA baseline, and produces stable, biologically coherent segmentations. As a demonstration of biological utility, application to *Datura innoxia* recovered five spatially coherent metabolic domains in the leaf and three in the root, resolving the spatial organization of tropane alkaloid metabolism without manual annotation: the leaf co-localizes the full scopolamine envelope with atropine/hyoscyamine and 6-hydroxyhyoscyamine in a single transport domain, with the precursors tropinone, tropine, and cuscohygrine compartmentalized in three separate domains. Together, the computational benchmark, the algorithmic treatment of the deep learning stage, and the containerized reproducibility establish the workflow as a scalable, democratized foundation for MSI analysis (lowering the memory and setup barriers that currently gate the analysis of next-generation imaging datasets).
# Acknowledgments
We thank Dr. Nicholas E. Sherman, Dr. Ana Oliveira, and Yulica Santos Ortega for providing the mouse liver (2.2 GB) and mouse stomach (4.4 GB) imaging datasets. The datasets were generated at the Biomolecular Analysis Facility Core, W.M. Keck Biomedical Mass Spectrometry Laboratory, University of Virginia School of Medicine, Charlottesville, VA. This facility is funded by a grant from the University of Virginia's School of Medicine (RRID:SCR_025476). All investigators are asked to acknowledge the Biomolecular Analysis Facility Core and W.M. Keck Biomedical Mass Spectrometry Laboratory personnel and funding sources in any publications using these data.
+3 -3
View File
@@ -61,7 +61,7 @@ pipeline:
step1: # Julia preprocessing
@if [ -z "$(D)" ]; then echo "Usage: make step1 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu julia --threads auto --project=/app/environment \
/app/scripts_julia/julia_msi_bridge.jl /app/datos_para_ai/$(D) $(D)
/app/scripts_julia/julia_msi_bridge.jl /app/ai_data/$(D) $(D)
step2: # SimCLR training
@if [ -z "$(D)" ]; then echo "Usage: make step2 D=Datura_leaf"; exit 1; fi
@@ -86,7 +86,7 @@ step6: # Galleries
step7: # Mass spectra
@if [ -z "$(D)" ]; then echo "Usage: make step7 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu julia --project=/app/environment \
/app/scripts_julia/plot_mass_spectra.jl $(D) /app/datos_para_ai/$(D)
/app/scripts_julia/plot_mass_spectra.jl $(D) /app/ai_data/$(D)
# ============================================================
# Plots
@@ -94,7 +94,7 @@ step7: # Mass spectra
plot-spectra:
@if [ -z "$(D)" ]; then echo "Usage: make plot-spectra D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu julia --project=/app/environment \
/app/scripts_julia/plot_mass_spectra.jl $(D) /app/datos_para_ai/$(D)
/app/scripts_julia/plot_mass_spectra.jl $(D) /app/ai_data/$(D)
# ============================================================
# Cleanup (outputs only; datasets are symlinked and never removed)
+42 -58
View File
@@ -6,21 +6,15 @@ 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 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 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](#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
@@ -45,9 +39,9 @@ required. Raw MSI datasets are supplied by the user (see [Datasets](#datasets)).
│ ├── 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)
│ ├── 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
```
@@ -71,10 +65,10 @@ required. Raw MSI datasets are supplied by the user (see [Datasets](#datasets)).
make build
# 2) put each dataset in its own folder, e.g.
# datos_para_ai/Datura_leaf/<name>.imzML (+ <name>.ibd, optional ROI .png)
# 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 datos_para_ai/
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):
@@ -89,13 +83,13 @@ 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/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 datos_para_ai/
bash run_full_pipeline.sh # all datasets under ai_data/
bash run_full_pipeline.sh Datura_leaf # a single dataset
```
@@ -123,13 +117,13 @@ Requires **Julia 1.11.x** (matching `environment/Manifest.toml`) and **Python 3.
`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>
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> datos_para_ai/<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
@@ -139,15 +133,15 @@ count `K`; Stage 3 prints and stores the best value (Silhouette optimum by defau
## Datasets
The pipeline reads **any valid imzML** (profile or centroid) — it is **not** restricted to
the manuscript datasets.
a fixed set of datasets.
**Each dataset must live in its own subfolder of `datos_para_ai/`.** The folder name *is*
**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
`datos_para_ai/` — **not inside a subfolder — are ignored** by `run_full_pipeline.sh`, so a
`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.
```
datos_para_ai/
ai_data/
├── Mouse_bladder/ # folder name = dataset name
│ ├── HR2MSImouseurinarybladderS096.imzML # exactly one .imzML
│ ├── HR2MSImouseurinarybladderS096.ibd # its sibling .ibd (matching basename)
@@ -168,17 +162,6 @@ Rules for each dataset folder:
`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
@@ -204,7 +187,7 @@ commit and re-run Stage 1. The MIT license of the vendored code is in `src/LICEN
| `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_DATA_ROOT` | `ai_data` | override the dataset root directory |
| `MSI_K` | auto | force a cluster count instead of the Stage-3 Silhouette choice |
## Prerequisites
@@ -214,23 +197,6 @@ commit and re-run Stage 1. The MIT license of the vendored code is in `src/LICEN
- 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)
@@ -301,13 +267,6 @@ 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.
@@ -348,6 +307,31 @@ spec. If you have no NVIDIA GPU, ignore `*-gpu` targets entirely — the CPU fal
**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:
- San Pedro Cactus: <https://doi.org/10.5281/zenodo.3625054>
- Human Colon & Mouse Bladder: <https://doi.org/10.5281/zenodo.10084132>
- Datura Leaf & Datura Root: pending.
- Mouse Stomach & Mouse Liver: pending.
## 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...
-289
View File
@@ -1,289 +0,0 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% This is a "template" model document for submission to the
%% American Chemical Society (ACS).
%%
%% The guidance here contains information about how you may wish to
%% modify it to match the requirements of various ACS journals. The
%% ACS do *not* typeset accepted articles using LaTeX, so there is
%% no specific class required.
%%
%% This template deliberately does *not* seek to reproduce
%% the layout of the typeset journal: this is explicitly not
%% required by the ACS for LaTeX submissions.
%%
%% Please report any issues with the template at
%% https://github.com/josephwright/acs-template/issues
%%
%% Released under the Creative Commons 0 license
%% https://creativecommons.org/public-domain/cc0/
%%
%% Copyight (c) 2025 Joseph Wright
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[letterpaper]{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Font setup - delete if you are using LuaLaTeX
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T1]{fontenc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Adjust the margins and allow for line spacing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{geometry}
\geometry{margin = 1in}
\usepackage{setspace}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Reference support
%%
%% The recommended method for producing the reference section is
%% to use biblatex. If you wish to use a classical BibTeX
%% approach, this is easiest to achieve using the achemso package.
%% In that case, you should remove the biblatex lines.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% You can adjust the printing of DOI, article title, etc. using
% package options, e.g. "doi = true"; see the biblatex manual for
% details of adjusting the number of authors printed, e.g.
% "maxnames = 15" to print no more than 15 authors.
\usepackage[style = chem-acs]{biblatex}
\addbibresource{acs-template.bib}
% If you are using classical BibTeX, remove the above lines and
% uncomment:
%\usepackage{achemso}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Graphic inclusion and scheme and chart support
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{graphicx}
\usepackage{float}
\newfloat{scheme}{htbp}{los}
\floatname{scheme}{Scheme}
\floatname{chart}{Chart}
\newfloat{graph}{htbp}{loh}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Common support packages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{chemformula} % Formulas using \ch{}
% or
\usepackage[version = 4]{mhchem} % Formulas using \ce{}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Many journals require that sections are unnumbered: this
%% is activated here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\setcounter{secnumdepth}{-1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Place any additional macros here. Please use \newcommand* where
%% possible, and avoid layout-changing macros (which are not used
%% when typesetting).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand*\mycommand[1]{\texttt{\emph{#1}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Author and title data:
%% the authblk package is currently the simplest way to provide this
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{authblk}
\author[1]{Andrew N. Other}
\author[1]{Fred T. Secondauthor}
\author[1]{I. Ken Groupleader*}
\affil[1]{Department of Chemistry, Unknown University, Unknown Town}
\author[2]{Susanne K. Laborator}
\affil[2]{Lead Discovery, BigPharma, Big Town, USA}
\author[1]{Kay T. Finally}
\title{A ``template'' model document for submission to the
American Chemical Society (ACS)}
% Use the \date command for email address(s) of corresponding authors
\date{*Email: i.k.groupleader@unknown.uu}
\begin{document}
\maketitle
\begin{abstract}
This is an example document for creating \LaTeX{} submissions to the American
Chemical Society (ACS) for publication. As ACS does not use \LaTeX{} for
typesetting accepted manuscripts, this template does not seek to
reproduce the appearance of a published paper.
\end{abstract}
\section*{Keywords}
Some journals require keywords: these normally should be given immediately
after the abstract.
\section*{Abbreviations}
Some journals require a list of abbreviations: these normally should be given
immediately after the keyswords (if required).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Start the main part of the manuscript here.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Introduction}
This is a paragraph of text to fill the introduction of the demonstration file.
\section{Results and discussion}
\subsection{Outline}
The document layout should follow the style of the journal concerned. Where
appropriate, sections and subsections should be added in the normal way.
\subsection{References}
References should be given in the normal way in \LaTeX{}. If you are using
\textsf{biblatex} (as recommended) then you can use the full range of citation
commands it provides. If you choose to use classical Bib\TeX{}, the
\textsf{natbib} package will be loaded and you can use it's commands.
\subsection{Floats}
New float types are set up in the preamble. The means graphics are included as
follows (Scheme~\ref{sch:example}). As illustrated, the float is ``here'' if
possible.
\begin{scheme}
\centering
Your scheme graphic would go here: PDF graphics are recommended.
%\includegraphics{graphic}
\caption{An example scheme}
\label{sch:example}
\end{scheme}
\begin{figure}
\centering
A standard figure environment.
\label{fgr:example}
\end{figure}
The use of the different floating environments is not required, but it is
intended to make document preparation easier for authors. In general, you
should place your graphics where they make logical sense; the production
process will move them if needed.
\subsection{Math}
If packages such as \textsf{amsmath} are required, they should be loaded in the
preamble. However, the basic \LaTeX\ math(s) input should work correctly
without this. Some inline material $1 + 1 = 2$ followed by some display. \[ A =
\pi r^2 \]
It is possible to label equations in the usual way (Eq.~\ref{eqn:example}).
\begin{equation}
\frac{\mathrm{d}}{\mathrm{d}x} \, r^2 = 2r \label{eqn:example}
\end{equation}
This can also be used to have equations containing graphical content. To align
the equation number with the middle of the graphic, rather than the bottom, a
minipage may be used.
\begin{equation}
\begin{minipage}[c]{0.80\linewidth}
\centering
As illustrated here, the width of \\
the minipage needs to allow some \\
space for the number to fit in to.
%\includegraphics{graphic}
\end{minipage}
\label{eqn:graphic}
\end{equation}
\section{Experimental}
The usual experimental details should appear here. This could include a table,
which can be referenced as Table~\ref{tbl:example}. Notice that the caption is
positioned at the top of the table.
\begin{table}
\caption{An example table}
\label{tbl:example}
\centering
\begin{tabular}{ll}
\hline
Header one & Header two \\
\hline
Entry one & Entry two \\
Entry three & Entry four \\
Entry five & Entry five \\
Entry seven & Entry eight \\
\hline
\end{tabular}
\end{table}
Adding notes to tables can be complicated. Perhaps the easiest method is to
generate these using the basic \texttt{\textbackslash textsuperscript} and
\texttt{\textbackslash emph} macros, as illustrated (Table~\ref{tbl:notes}).
\begin{table}
\caption{A table with notes}
\label{tbl:notes}
\centering
\begin{tabular}{ll}
\hline
Header one & Header two \\
\hline
Entry one\textsuperscript{\emph{a}} & Entry two \\
Entry three\textsuperscript{\emph{b}} & Entry four \\
\hline
\end{tabular}
\textsuperscript{\emph{a}} Some text;
\textsuperscript{\emph{b}} Some more text.
\end{table}
The example file also loads the optional \textsf{chemformula} and
\textsf{mhchem} packages, so that formulas are easy to input:
\texttt{\textbackslash ce\{H2SO4\}} gives \ce{H2SO4}. The two have similar
syntax but authors may prefer one or the other.
The use of new commands should be limited to simple things which will not
interfere with the production process. For example, \texttt{\textbackslash
mycommand} has been defined in this example, to give italic, mono-spaced text:
\mycommand{some text}.
\section*{Acknowledgements}
Please use ``The authors thank \ldots'' rather than ``The authors would like to
thank \ldots''.
\section*{Supporting information}
A listing of the contents of each file supplied as Supporting Information
should be included. For instructions on what should be included in the
Supporting Information as well as how to prepare this material for
publications, refer to the journal's Instructions for Authors.
The following files are available free of charge.
\begin{itemize}
\item Filename-1: brief description
\item Filename-2: brief description
\end{itemize}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% If you are using classical BibTeX rather than biblatex,
%% remove the \printbibliography and uncomment the \bibliograpy one
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\printbibliography
%\bibliography{acs-template.bib}
\newpage
\rule{0.05in}{1.75in}%
\begin{minipage}[b][1.75in]{3.25in}
\sffamily
\frenchspacing
Some journals require a graphical entry for the Table of Contents. This
should be laid out ``print ready'' so that the sizing of the text is correct.
The space available depends on the journal: J. Am. Chem. Soc. allows 3.25 in
by 1.75 in and requires sanserif text. Some journals want different sizes:
you can easily adjust here.
The two rules either side of the content are there to help judge the height
of your material: they may be deleted once not required.
\end{minipage}%
\rule{0.05in}{1.75in}
\end{document}
+2 -2
View File
@@ -9,7 +9,7 @@ services:
volumes:
# `:z` relabels the bind mount for SELinux hosts (Fedora/RHEL + Podman).
# It is ignored by Docker. Remove it if your host has no SELinux.
- ./datos_para_ai:/app/datos_para_ai:z
- ./ai_data:/app/ai_data:z
- ./outputs:/app/outputs:z
msi-pipeline-cpu:
@@ -22,5 +22,5 @@ services:
volumes:
# `:z` relabels the bind mount for SELinux hosts (Fedora/RHEL + Podman).
# It is ignored by Docker. Remove it if your host has no SELinux.
- ./datos_para_ai:/app/datos_para_ai:z
- ./ai_data:/app/ai_data:z
- ./outputs:/app/outputs:z
-73
View File
@@ -1,73 +0,0 @@
# Technical Documentation & Experimental Rationale
This document provides a detailed technical overview of the computational choices, hyperparameter tuning, and validation strategies implemented in the hybrid Julia-Python MSI workflow.
## Docker Maintenance & Disk Space
If you encounter disk space issues due to failed builds or unused images, use these commands:
- **Safe Clean (Dangling layers only):** `docker image prune`
- **Deep Clean (Everything unused):** `docker system prune -a --volumes`
- **Clear Build Cache:** `docker builder prune`
## 1. Hyperparameter Tuning Rationale (SimCLR)
The training configuration in `scripts_python/CNN_proof_1.py` follows the standard SimCLR framework (Chen et al., 2020) while being optimized for the morphological characteristics of Mass Spectrometry Imaging (MSI) data.
| Hyperparameter | Value | Rationale |
| :--- | :--- | :--- |
| **Temperature ($\tau$)** | 0.5 | **Selected via grid search.** We tested $\tau \in \{0.1, 0.5, 1.0\}$. A value of 0.1 led to unstable gradients and collapsed representations, while 1.0 was too permissive. $\tau=0.5$ provided the most stable convergence and distinct cluster boundaries. |
| **Projection Dim** | 128 | Standard for SimCLR. Reducing to 64 lost anatomical detail; increasing to 256 did not improve Silhouette scores but increased computational overhead. |
| **Training Epochs** | 50 | Observed convergence of NT-Xent loss between epochs 40-50. Further training (tested up to 200 epochs) led to minor overfitting to instrumental artifacts. |
| **Batch Size** | 32 | Optimized for the i5 CPU environment to balance memory usage and gradient stability. |
## 2. Advanced Validation Strategies
To satisfy rigorous peer review, we implemented three quantitative validation layers in `scripts_python/quantitative_validation.py`:
### 2.1 Baseline Comparison (PCA vs. SimCLR)
* **Method:** We compared our self-supervised approach against a traditional baseline where PCA is applied directly to raw pixel vectors (flattened ion images).
* **Result:** SimCLR consistently yields higher Silhouette scores and lower Davies-Bouldin indices. This proves that the neural network's non-linear feature extraction captures anatomical "shapes" better than linear variance-based methods.
### 2.2 Stability & Reproducibility Analysis
* **Metric:** Adjusted Rand Index (ARI).
* **Method:** We ran the clustering pipeline across 10 different random seeds. By computing the ARI between all pairs of runs, we demonstrate that the metabolic domains identified (Clusters 0-9) are stable and not artifacts of k-means initialization.
### 2.3 Isotope Co-localization (Natural Ground Truth)
* **Scientific Anchor:** Isotopes ($[M+H]^+$ and $[M+H+1]^+$) must co-localize perfectly in tissue.
* **Validation:** We measure the Euclidean distance of isotopic pairs in the latent manifold. A t-test confirms that these distances are significantly smaller than those of random ion pairs, providing objective evidence that the model has learned chemical-biological reality.
## 3. Biological & Mathematical Rationale for $k=10$
While mathematical metrics (Elbow method, Silhouette) often suggest $k=2$ or $k=3$ (tissue vs. background), we selected **$k=10$** based on:
1. **Anatomical Fidelity:** This threshold is required to resolve the hierarchy between the primary midrib, secondary veins, and apical accumulation zones.
2. **Stability:** Metric stabilization was observed in the $k=8$ to $k=12$ range.
3. **Metabolic Heatmaps:** Average ion intensities per cluster for scopolamine ($m/z$ 304.1) and atropine ($m/z$ 290.1) show clear sequestration in Clusters 9 (Vascular) and 7 (Apical), validating the biological relevance of the segmentation.
## 4. Technical Specifications & Citations
### 4.1 Data Augmentations
We implemented **Additive Gaussian Noise ($\sigma=0.01$)**. This is critical for MSI to simulate detector background noise.
* *Citation:* DeepION (2024) and Hu et al. (2022, Table S1).
### 4.2 Model Backbone
**EfficientNet-B0** with ImageNet weights was used for transfer learning. The MBConv blocks are highly efficient for CPU-based inference.
* *Citation:* Tan & Le (2019).
### 4.3 Preprocessing (JuliaMSI)
* **Spectral Averaging:** Done via `MSI_src.get_average_spectrum`.
* **Tolerance:** $\pm 0.05$ Da window for mass slices. This is standard for low-resolution Ion Trap instruments (LCQ Fleet) to ensure all isotopic signal is captured.
* *Citation:* Sierra-Álvarez et al. (2025).
### 4.4 Dimensionality Reduction
PCA was used to reduce the 1280-dim (EfficientNet) or 128-dim (Projector) features to **50 components** before k-means. This heuristic stabilizes clustering by removing noise and redundant dimensions.
* *Citation:* Jolliffe (2002).
## Benchmarking & Hardware Realism
The pipeline is optimized for efficiency on consumer-grade hardware.
- **Julia Stage**: Uses `BenchmarkTools.jl` to profile binary parsing.
- **Python Stage**: Uses `psutil` and `CUDA` monitoring to track hardware overhead.
- **Determinism**: All stochastic steps are locked with `seed=42`.
## Julia-Python Bridge Details
The "two-language problem" is solved by an intermediate file-system bridge. Julia performs binary MSI parsing and **Threshold Intensity Quantization (TrIQ)**. The resulting data is saved as high-contrast 224x224 grayscale PNG images, allowing the Python PyTorch pipeline to consume it efficiently.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 294 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 379 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 780 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 359 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 341 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 349 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 379 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

-794
View File
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 15 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

-134
View File
@@ -1,134 +0,0 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% This is a "template" model document for submission to the
%% American Chemical Society (ACS).
%%
%% The guidance here contains information about how you may wish to
%% modify it to match the requirements of various ACS journals. The
%% ACS do *not* typeset accepted articles using LaTeX, so there is
%% no specific class required.
%%
%% This template deliberately does *not* seek to reproduce
%% the layout of the typeset journal: this is explicitly not
%% required by the ACS for LaTeX submissions.
%%
%% Please report any issues with the template at
%% https://github.com/josephwright/acs-template/issues
%%
%% Released under the Creative Commons 0 license
%% https://creativecommons.org/public-domain/cc0/
%%
%% Copyight (c) 2025 Joseph Wright
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[letterpaper]{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Font setup - delete if you are using LuaLaTeX
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T1]{fontenc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Adjust the margins and allow for line spacing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{geometry}
\geometry{margin = 1in}
\usepackage{setspace}
\usepackage{textcomp}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Reference support
%%
%% The recommended method for producing the reference section is
%% to use biblatex. If you wish to use a classical BibTeX
%% approach, this is easiest to achieve using the achemso package.
%% In that case, you should remove the biblatex lines.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% You can adjust the printing of DOI, article title, etc. using
% package options, e.g. "doi = true"; see the biblatex manual for
% details of adjusting the number of authors printed, e.g.
% "maxnames = 15" to print no more than 15 authors.
\usepackage[style = chem-acs]{biblatex}
\addbibresource{zotero.bib}
% If you are using classical BibTeX, remove the above lines and
% uncomment:
%\usepackage{achemso}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Graphic inclusion and scheme and chart support
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{graphicx}
\setkeys{Gin}{width=17.1cm,keepaspectratio}
\usepackage{float}
\newfloat{scheme}{htbp}{los}
\floatname{scheme}{Scheme}
\floatname{chart}{Chart}
\newfloat{graph}{htbp}{loh}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Common support packages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{calc}
\usepackage{amsmath}
\usepackage{array}
\usepackage{booktabs}
%% Fix for pandoc-generated \real{} in table widths - define as pass-through macro
%% \unskip removes the space that pandoc inserts before \real
\newcommand{\real}[1]{\unskip#1}
%% Fix for pandoc-generated \pandocbounded for bounded images
\newcommand{\pandocbounded}[1]{\makebox[0pt][l]{#1}}
%% Fix for pandoc-generated \texorpdfstring (from hyperref)
\newcommand{\texorpdfstring}[2]{#1}
\usepackage{chemformula} % Formulas using \ch{}
% or
\usepackage[version = 4]{mhchem} % Formulas using \ce{}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Many journals require that sections are unnumbered: this
%% is activated here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\setcounter{secnumdepth}{-1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Place any additional macros here. Please use \newcommand* where
%% possible, and avoid layout-changing macros (which are not used
%% when typesetting).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand*\mycommand[1]{\texttt{\emph{#1}}}
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\usepackage{longtable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Author and title data:
%% the authblk package is currently the simplest way to provide this
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{authblk}
\author[1]{Carlos Daniel Sierra Álvarez}
\author[1]{Juan Francisco Moreno Luna}
\author[1]{José Julián Sierra Álvarez}
\author[1]{José Jovani Martínez}
\author[1,*]{Robert Winkler}
\affil[1]{Advanced Genomics Unit, Cinvestav, km 9.6 Libr. Nte. Irapuato-León, Irapuato, 36824, Gto., Mexico.}
\title{$title$}
% Use the \date command for email address(s) of corresponding authors
\date{*Email: robert.winkler@cinvestav.mx}
\begin{document}
\maketitle
\begin{abstract}
$abstract$
\end{abstract}
\section*{Keywords}
$keywords$
$body$
\printbibliography
\end{document}
+4 -4
View File
@@ -2,11 +2,11 @@
# =============================================================================
# run_full_pipeline.sh -- seven-stage MSI pipeline (one or many datasets)
#
# bash run_full_pipeline.sh # every dataset under datos_para_ai/
# bash run_full_pipeline.sh # every dataset under ai_data/
# bash run_full_pipeline.sh Datura_leaf # a single dataset
# MSI_K=5 bash run_full_pipeline.sh Datura_leaf
#
# Each dataset lives in datos_para_ai/<name>/ and must contain exactly one
# Each dataset lives in ai_data/<name>/ and must contain exactly one
# .imzML file and its sibling .ibd binary (optional ROI mask .png).
#
# Stages: 1 Julia preprocessing -> 2 SimCLR -> 3 K sweep -> 4 t-SNE + K-Means
@@ -16,7 +16,7 @@
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DATA_ROOT="${MSI_DATA_ROOT:-$ROOT/datos_para_ai}"
DATA_ROOT="${MSI_DATA_ROOT:-$ROOT/ai_data}"
ENV_DIR="$ROOT/environment"
# Native runs: prefer a repo-local venv/ if one exists (ignored inside Docker).
@@ -26,7 +26,7 @@ fi
if [ ! -d "$DATA_ROOT" ]; then
echo "ERROR: dataset root '$DATA_ROOT' not found." >&2
echo " Create it and add datos_para_ai/<name>/<file>.imzML (+ .ibd)." >&2
echo " Create it and add ai_data/<name>/<file>.imzML (+ .ibd)." >&2
exit 1
fi
+24 -24
View File
@@ -1,7 +1,7 @@
using MSI_src
using Statistics, Plots, Images
# 1. Definir función de contraste (si no la tienes ya en la sesión)
# 1. Define the contrast function (if you do not already have it in the session)
function apply_triq(img_matrix)
vals = filter(x -> x > 0 && isfinite(x), img_matrix)
if isempty(vals) return img_matrix end
@@ -10,45 +10,45 @@ function apply_triq(img_matrix)
return clamp.(img_matrix ./ q, 0.0, 1.0)
end
# 2. Configuración de rutas
path_data = "Hoja.imzML"
path_mask = "region_interes.png"
output_folder = "resultados_expertos/batch_triq"
# 2. Path configuration
path_data = "Leaf.imzML"
path_mask = "region_of_interest.png"
output_folder = "expert_results/batch_triq"
mkpath(output_folder)
# 3. Carga de datos
# 3. Data loading
data = OpenMSIData(path_data)
# 4. Obtener espectro promedio SOLO de la zona de la máscara (ROI)
println("Calculando espectro promedio en la ROI...")
# Nota: Usamos la función de MSI_src para obtener el promedio filtrado
# 4. Get the average spectrum ONLY for the mask region (ROI)
println("Computing average spectrum over the ROI...")
# Note: We use the MSI_src function to obtain the filtered average
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=path_mask)
# 5. Identificar picos importantes (ej. > 2% del pico base)
# 5. Identify important peaks (e.g. > 2% of the base peak)
max_int = maximum(avg_ints)
umbral = max_int * 0.02 # Ajusta este valor (0.01 para 1%, 0.05 para 5%)
indices_picos = findall(x -> x > umbral, avg_ints)
threshold = max_int * 0.02 # Adjust this value (0.01 for 1%, 0.05 for 5%)
peak_indices = findall(x -> x > threshold, avg_ints)
println("Se encontraron $(length(indices_picos)) iones que superan el umbral.")
println("Found $(length(peak_indices)) ions above the threshold.")
# 6. Bucle para generar imágenes con TrIQ
for idx in indices_picos
# 6. Loop to generate images with TrIQ
for idx in peak_indices
mz_val = mzs[idx]
# Validar rango (ejemplo: m/z 50 a 700)
# Validate range (example: m/z 50 to 700)
if mz_val < 50.0 || mz_val > 700.0
continue
end
println("Procesando m/z: $(round(mz_val, digits=2))")
println("Processing m/z: $(round(mz_val, digits=2))")
# A. Extraer los datos crudos con la máscara aplicada
# A. Extract the raw data with the mask applied
raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=path_mask)
# B. Aplicar contraste TrIQ
# B. Apply TrIQ contrast
enhanced_slice = apply_triq(raw_slice)
# C. Crear el mapa de calor (Heatmap)
# C. Create the heatmap
p = heatmap(enhanced_slice,
title="Ion m/z: $(round(mz_val, digits=2))",
color=:viridis,
@@ -56,9 +56,9 @@ for idx in indices_picos
yflip=true,
xaxis=false, yaxis=false)
# D. Guardar
nombre_archivo = "ion_$(round(mz_val, digits=2))_triq.png"
savefig(p, joinpath(output_folder, nombre_archivo))
# D. Save
filename = "ion_$(round(mz_val, digits=2))_triq.png"
savefig(p, joinpath(output_folder, filename))
end
println("--- Proceso completado. Revisa la carpeta: $output_folder ---")
println("--- Process completed. Check the folder: $output_folder ---")
+1 -1
View File
@@ -4,7 +4,7 @@ using Statistics, Images, Interpolations
# 1. Configuration
data_path = "Leaf.imzML"
mask_path = "region_of_interest.png"
output_folder = "datos_para_ai"
output_folder = "ai_data"
img_size = (224, 224) # Standard size for CNN
mkpath(output_folder)
+2 -2
View File
@@ -14,8 +14,8 @@ using Plots.Measures
dataset_name = length(ARGS) >= 1 ? ARGS[1] : "leaf"
# Second positional arg (optional) overrides the dataset directory, e.g.
# `julia plot_mass_spectra.jl Datura_leaf /path/to/datos_para_ai/Datura_leaf`.
data_dir = length(ARGS) >= 2 ? ARGS[2] : joinpath(project_root, "datos_para_ai", dataset_name)
# `julia plot_mass_spectra.jl Datura_leaf /path/to/ai_data/Datura_leaf`.
data_dir = length(ARGS) >= 2 ? ARGS[2] : joinpath(project_root, "ai_data", dataset_name)
output_dir = joinpath(project_root, "outputs", dataset_name)
figures_dir = joinpath(output_dir, "figures")
cluster_csv = joinpath(output_dir, "msi_clusters_results.csv")
+28 -28
View File
@@ -12,24 +12,24 @@ from sklearn.manifold import TSNE
import pandas as pd
import matplotlib.pyplot as plt
# 1. CONFIGURACIÓN
IMG_DIR = "datos_para_ai"
OUTPUT_DIR = "pruebas_clusters"
# 1. CONFIGURATION
IMG_DIR = "ai_data"
OUTPUT_DIR = "cluster_tests"
N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
os.makedirs(OUTPUT_DIR, exist_ok=True)
# 2. CARGAR MODELO PRE-ENTRENADO (Directo de PyTorch)
# 2. LOAD PRETRAINED MODEL (Directly from PyTorch)
def get_pretrained_extractor():
# Usamos los pesos por defecto de ImageNet
# We use the default ImageNet weights
model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
model.classifier = nn.Identity() # Quitamos la capa de clasificación
model.classifier = nn.Identity() # Remove the classification layer
model.to(DEVICE)
model.eval()
return model
# 3. DATASET CON NORMALIZACIÓN ESTÁNDAR
# 3. DATASET WITH STANDARD NORMALIZATION
class MSIDatasetDirect(Dataset):
def __init__(self, img_dir):
self.img_dir = img_dir
@@ -37,7 +37,7 @@ class MSIDatasetDirect(Dataset):
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
# Normalización obligatoria para modelos pre-entrenados
# Normalization required for pretrained models
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
@@ -50,7 +50,7 @@ class MSIDatasetDirect(Dataset):
return self.transform(image), self.img_names[idx]
if __name__ == "__main__":
print(f"Extrayendo características con red pre-entrenada en {DEVICE}...")
print(f"Extracting features with the pretrained network on {DEVICE}...")
model = get_pretrained_extractor()
dataset = MSIDatasetDirect(IMG_DIR)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
@@ -62,55 +62,55 @@ if __name__ == "__main__":
for img, name in loader:
img = img.to(DEVICE)
feat = model(img)
# Aplanar el vector de características (1280 dimensiones para EffNet-B0)
# Flatten the feature vector (1280 dimensions for EffNet-B0)
features.append(feat.cpu().numpy().flatten())
ion_names.append(name[0])
features = np.array(features)
print(f"Características extraídas: {features.shape}")
print(f"Extracted features: {features.shape}")
# 4. REDUCCIÓN DE DIMENSIONALIDAD (PCA)
# Esto ayuda a que el clustering no se pierda en dimensiones irrelevantes
print("Reduciendo ruido con PCA...")
# 4. DIMENSIONALITY REDUCTION (PCA)
# This helps clustering from getting lost in irrelevant dimensions
print("Reducing noise with PCA...")
features_scaled = StandardScaler().fit_transform(features)
pca = PCA(n_components=0.95) # Mantenemos el 95% de la varianza
pca = PCA(n_components=0.95) # We keep 95% of the variance
features_pca = pca.fit_transform(features_scaled)
print(f"Dimensiones tras PCA: {features_pca.shape[1]}")
print(f"Dimensions after PCA: {features_pca.shape[1]}")
# 5. CLUSTERING K-MEANS
print(f"Agrupando en {N_CLUSTERS} clusters...")
# 5. K-MEANS CLUSTERING
print(f"Grouping into {N_CLUSTERS} clusters...")
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
labels = km.fit_predict(features_pca)
# 6. VISUALIZACIÓN (t-SNE)
print("Generando visualización t-SNE para verificar consistencia...")
# 6. VISUALIZATION (t-SNE)
print("Generating t-SNE visualization to verify consistency...")
tsne = TSNE(n_components=2, random_state=42)
features_tsne = tsne.fit_transform(features_pca)
plt.figure(figsize=(10, 8))
scatter = plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=labels, cmap='tab10', alpha=0.7)
plt.colorbar(scatter, ticks=range(N_CLUSTERS), label='Cluster ID')
plt.title(f"Visualización de Clusters (K={N_CLUSTERS}) - Directo")
plt.title(f"Cluster Visualization (K={N_CLUSTERS}) - Direct")
plt.xlabel("t-SNE 1")
plt.ylabel("t-SNE 2")
plt.grid(True, linestyle='--', alpha=0.5)
plt.savefig(os.path.join(OUTPUT_DIR, "msi_clusters_direct_plot.png"))
print(f"Gráfico de consistencia guardado en '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
print(f"Consistency plot saved to '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
# 7. GUARDAR Y REPORTAR
# 7. SAVE AND REPORT
df = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
df['mz'] = df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_results.csv"), index=False)
# Crear un resumen de cuántos iones hay por cluster
print("\nResumen de Clusters (Consistente con el CSV y el Gráfico):")
# Create a summary of how many ions there are per cluster
print("\nCluster Summary (Consistent with the CSV and the Plot):")
counts = df['cluster'].value_counts().sort_index()
print(counts)
# Guardar también el resumen para evitar confusiones con otros archivos
# Also save the summary to avoid confusion with other files
summary_df = counts.reset_index()
summary_df.columns = ['Cluster_ID', 'Ion_Count']
summary_df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_summary.csv"), index=False)
print(f"\nResultados guardados en '{OUTPUT_DIR}/msi_clusters_direct_results.csv' y '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
print(f"Usa '{OUTPUT_DIR}/msi_clusters_direct_plot.png' para validar visualmente los puntos.")
print(f"\nResults saved to '{OUTPUT_DIR}/msi_clusters_direct_results.csv' and '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
print(f"Use '{OUTPUT_DIR}/msi_clusters_direct_plot.png' to visually validate the points.")
@@ -10,17 +10,17 @@ from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
# 1. CONFIGURACIÓN
# 1. CONFIGURATION
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "../..", "datos_para_ai")
IMG_DIR = os.path.join(BASE_DIR, "../..", "ai_data")
ENCODER_PATH = os.path.join(BASE_DIR, "../..", "models", "msi_encoder_trained.pth")
N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. CARGAR EL MODELO ENTRENADO
# 2. LOAD THE TRAINED MODEL
def load_trained_encoder(path):
if not os.path.exists(path):
raise FileNotFoundError(f"No se encontró el modelo en {path}")
raise FileNotFoundError(f"Model not found at {path}")
model = models.efficientnet_b0()
model.classifier = nn.Identity()
@@ -31,7 +31,7 @@ def load_trained_encoder(path):
model.eval()
return model
# 3. DATASET PARA INFERENCIA
# 3. DATASET FOR INFERENCE
class MSIDatasetInference(Dataset):
def __init__(self, img_dir):
self.img_dir = img_dir
@@ -49,18 +49,18 @@ class MSIDatasetInference(Dataset):
image = Image.open(img_path).convert("RGB")
return self.transform(image), self.img_names[idx]
# --- PROCESO ---
# --- PROCESS ---
if __name__ == "__main__":
print("Extrayendo características con el encoder...")
print("Extracting features with the encoder...")
try:
encoder = load_trained_encoder(ENCODER_PATH)
except Exception as e:
print(f"Error al cargar el modelo: {e}")
print(f"Error loading the model: {e}")
exit(1)
dataset = MSIDatasetInference(IMG_DIR)
if len(dataset) == 0:
print(f"No se encontraron imágenes en {IMG_DIR}")
print(f"No images found in {IMG_DIR}")
exit(1)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
@@ -72,28 +72,28 @@ if __name__ == "__main__":
for img, name in loader:
img = img.to(DEVICE)
feat = encoder(img)
# Normalización L2
# L2 normalization
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
features.append(feat.cpu().numpy().flatten())
ion_names.append(name[0])
features = np.array(features)
# 4. CLUSTERING K-MEANS
print(f"Realizando KMeans con {N_CLUSTERS} clusters...")
# 4. K-MEANS CLUSTERING
print(f"Running KMeans with {N_CLUSTERS} clusters...")
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
labels = km.fit_predict(features)
# 5. VISUALIZACIÓN t-SNE CORREGIDA
print("Generando visualización t-SNE con escala corregida...")
# 5. CORRECTED t-SNE VISUALIZATION
print("Generating t-SNE visualization with corrected scale...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features)
plt.figure(figsize=(10, 8))
# Aplicando tu corrección específica:
# Applying your specific correction:
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50)
# Configuración de la barra de colores con los ticks exactos para 10 clusters
# Configure the colorbar with exact ticks for 10 clusters
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
cbar.set_label('Cluster ID')
@@ -102,8 +102,8 @@ if __name__ == "__main__":
plt.ylabel("t-SNE dimension 2")
plt.grid(True, linestyle='--', alpha=0.5)
output_file = "msi_tsne_corregido.png"
output_file = "msi_tsne_corrected.png"
plt.savefig(output_file, dpi=300, bbox_inches='tight')
# plt.show()
print(f"Visualización guardada exitosamente en '{output_file}'.")
print(f"Visualization successfully saved to '{output_file}'.")
@@ -9,17 +9,17 @@ from sklearn.manifold import TSNE
import pandas as pd
import plotly.express as px
# 1. CONFIGURACIÓN
IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai"
ENCODER_PATH = "Reporte/Model/msi_encoder_trained.pth"
CSV_PATH = "msi_clusters_results.csv" # Fuente de verdad
# 1. CONFIGURATION
IMG_DIR = "/home/sierra/Documents/Test teams/Julia_msi_GUI-main/ai_data"
ENCODER_PATH = "Report/Model/msi_encoder_trained.pth"
CSV_PATH = "msi_clusters_results.csv" # Source of truth
N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. CARGAR EL MODELO ENTRENADO
# 2. LOAD THE TRAINED MODEL
def load_trained_encoder(path):
if not os.path.exists(path):
raise FileNotFoundError(f"No se encontró el modelo en {path}")
raise FileNotFoundError(f"Model not found at {path}")
model = models.efficientnet_b0()
model.classifier = nn.Identity()
@@ -30,7 +30,7 @@ def load_trained_encoder(path):
model.eval()
return model
# 3. DATASET BASADO EN EL CSV
# 3. DATASET BASED ON THE CSV
class MSIDatasetFromCSV(Dataset):
def __init__(self, img_dir, img_names):
self.img_dir = img_dir
@@ -48,17 +48,17 @@ class MSIDatasetFromCSV(Dataset):
image = Image.open(img_path).convert("RGB")
return self.transform(image)
# --- PROCESO ---
# --- PROCESS ---
if __name__ == "__main__":
# 4. CARGAR EL CSV DE RESULTADOS
print(f"Cargando datos desde {CSV_PATH}...")
# 4. LOAD THE RESULTS CSV
print(f"Loading data from {CSV_PATH}...")
df = pd.read_csv(CSV_PATH)
ion_names = df['ion_image'].tolist()
# Asegurarnos de que cluster sea categórico para Plotly
# Make sure cluster is categorical for Plotly
df['cluster'] = df['cluster'].astype(str)
print("Extrayendo características con el encoder...")
print("Extracting features with the encoder...")
encoder = load_trained_encoder(ENCODER_PATH)
dataset = MSIDatasetFromCSV(IMG_DIR, ion_names)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
@@ -68,40 +68,40 @@ if __name__ == "__main__":
for i, img in enumerate(loader):
img = img.to(DEVICE)
feat = encoder(img)
# Normalización L2
# L2 normalization
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
features.append(feat.cpu().numpy().flatten())
if (i+1) % 100 == 0:
print(f"Iones procesados: {i+1}/{len(ion_names)}")
print(f"Ions processed: {i+1}/{len(ion_names)}")
features = np.array(features)
# 5. t-SNE
print("Calculando t-SNE...")
print("Computing t-SNE...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features)
# Agregar coordenadas t-SNE al DataFrame original
# Add t-SNE coordinates to the original DataFrame
df['tsne_1'] = embeddings_2d[:, 0]
df['tsne_2'] = embeddings_2d[:, 1]
# 6. VISUALIZACIÓN INTERACTIVA CON PLOTLY
print("Generando gráfica interactiva con Plotly...")
# 6. INTERACTIVE VISUALIZATION WITH PLOTLY
print("Generating interactive plot with Plotly...")
# Usar escala de colores similar a tab10 o cualitativa estándar
# Use a color scale similar to tab10 or the standard qualitative one
fig = px.scatter(
df,
x='tsne_1',
y='tsne_2',
color='cluster',
hover_data={'ion_image': True, 'mz': True, 'cluster': True, 'tsne_1': False, 'tsne_2': False},
title=f"t-SNE Interactivo de Iones MSI (Consistente con {CSV_PATH})",
title=f"Interactive t-SNE of MSI Ions (Consistent with {CSV_PATH})",
labels={'tsne_1': 't-SNE 1', 'tsne_2': 't-SNE 2'},
category_orders={"cluster": [str(i) for i in range(N_CLUSTERS)]},
color_discrete_sequence=px.colors.qualitative.Plotly # O T10 si está disponible
color_discrete_sequence=px.colors.qualitative.Plotly # Or T10 if available
)
# Mejorar el diseño
# Improve the layout
fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey')))
fig.update_layout(
legend_title_text='Cluster ID',
@@ -109,9 +109,9 @@ if __name__ == "__main__":
hoverlabel=dict(bgcolor="white", font_size=16)
)
# Guardar como HTML
output_html = "msi_tsne_interactivo.html"
# Save as HTML
output_html = "msi_tsne_interactive.html"
fig.write_html(output_html)
print(f"\n¡Éxito! Gráfica interactiva guardada en '{output_html}'.")
print("Puedes abrir este archivo en cualquier navegador para explorar los clusters.")
print(f"\nSuccess! Interactive plot saved to '{output_html}'.")
print("You can open this file in any browser to explore the clusters.")
+2 -2
View File
@@ -104,11 +104,11 @@ def main():
ap.add_argument("--tile-size", type=int, default=96)
ap.add_argument("--clusters", action="store_true", help="also emit per-cluster mosaics")
ap.add_argument("--data-dir", default=None,
help="dataset directory (default: <root>/datos_para_ai/<dataset>)")
help="dataset directory (default: <root>/ai_data/<dataset>)")
args = ap.parse_args()
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
dataset_dir = args.data_dir or os.path.join(root, "datos_para_ai", args.dataset)
dataset_dir = args.data_dir or os.path.join(root, "ai_data", args.dataset)
viridis_dir = os.path.join(root, "outputs", "ion_images_viridis", args.dataset)
ions = load_ions(viridis_dir, args.tile_size, args.dataset)
out_dir = os.path.join(root, "outputs", args.dataset, "figures")
+1 -1
View File
@@ -214,7 +214,7 @@ def extract_ion_images(spectra_info, ibd_path, target_mzs, tolerance, mz_format,
return exported
if __name__ == "__main__":
data_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(PROJECT_ROOT, "datos_para_ai", "Datura_leaf")
data_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(PROJECT_ROOT, "ai_data", "Datura_leaf")
dataset_name = sys.argv[2] if len(sys.argv) > 2 else "Datura_leaf"
imzml_path, ibd_path, output_dir, viridis_dir = configure(data_dir, dataset_name)
-56795
View File
File diff suppressed because it is too large Load Diff