Files
MSI_Julia_CNN_Release/MSI_julia-python_mapping.md
T
2026-08-13 03:57:20 +02:00

48 KiB
Raw Blame History

title, bibliography, abstract, keywords
title bibliography abstract keywords
A scalable deep learning workflow for mass spectrometry imaging: benchmarking Julia-Python hybrid processing across multi-instrument datasets zotero.bib 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 "two-language problem": 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 at each dataset's reference *m/z*) against Cardinal (R/Bioconductor) and MALDIquant (R) on seven public datasets spanning 0.07–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 (0.00009–0.32 s vs 6.3–19.5 s) 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 (~120 MB) 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. mass spectrometry imaging, Julia language, Python, hybrid pipeline, benchmark, peak RAM, reproducibility, Docker, deep learning, SimCLR, contrastive learning, spatial metabolomics

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.07–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.07--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, was processed without a mask. 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
Datura Leaf LD-LTP Ion Trap D. innoxia 2.0 GB 17,066
Datura Root LD-LTP Ion Trap D. innoxia 2.5 GB 21,060
San Pedro MALDI TOF E. pachanoi 1.1 GB 19,600
Mouse bladder AP-SMALDI Orbitrap M. musculus 778 MB 34,840
Human colon DESI Orbitrap H. sapiens 69 MB 20,022
Mouse liver MALDI TOF M. musculus 2.2 GB 28,587
Mouse stomach MALDI TOF M. musculus 4.4 GB 54,245

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. We extracted mass slices from the Leaf.imzML dataset within the m/z 50.0 to 700.0 range. This upper limit was selected because no significant signals were detected beyond this threshold using the LD-LTP-MSI technique for this specific sample, and its implementation allowed for a more computationally manageable dataset. To ensure the inclusion of only chemically relevant signals and to exclude background noise, we applied a Region of Interest (ROI) mask derived from the optical image of the leaf. The average spectrum was computed exclusively from pixels within the tissue mask, and peaks were filtered using an intensity threshold of 2% relative to the base peak, resulting in 1,596 ion images for downstream analysis. 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 of $\sim0.08$--0.09 m/z per channel. The monoisotopic peak of scopolamine [M+H]^+ (exact mass 304.1549) is detected at the binned channel m/z 304.17, which is independently produced by the centroid-based peak-picking engine and corresponds to the same precursor selected for MS/MS structural confirmation. The adjacent bins (m/z 304.00, 304.08, 304.25, 304.33, 304.42) 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 500.0 for San Pedro; 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.

Stage 1 — Data ingestion and preprocessing (Julia, with Python fallback). The imzML file is memory-mapped and parsed by the Julia engine, which (i) computes the average spectrum across all pixels (restricted to the ROI mask when available), (ii) selects peaks above a 2% threshold of the base peak, (iii) extracts an ion image for every detected peak within a 0.05 Da tolerance, (iv) applies the TrIQ normalization per ion map, (v) spatially standardizes each map to a 256\times 256 grid by strict zero-padding, and (vi) exports each normalized ion image twice: a grayscale PNG (ion_<mz>.png) reserved exclusively for the deep learning stage, and a viridis-colored PNG of the same map (outputs/ion_images_viridis/) built with the native Julia ViridisPalette. For imzML variants that the Julia parser rejects (e.g., certain vendor-encoded name spaces), 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.

Stage 2 — Contrastive representation learning (Python, SimCLR). 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, projecting each ion map into a 128-dimensional latent space. The algorithmic details — and how they make this tractable on big data and consumer GPUs — are given in the section "Self-Supervised Representation Learning (Python)".

Stage 3 — Clustering evaluation. The optimal number of metabolic clusters is selected via a multi-metric sweep (Silhouette, Davies-Bouldin, Calinski-Harabasz) over k = 2,\dots,20, computed per dataset from the learned latent space (Figure 2).

Stage 4 — t-SNE visualization. Latent embeddings are projected to two dimensions and colored by the selected number of clusters (Figure 3).

Stage 5 — Quantitative validation. The clustering is validated by testing the spatial co-localization of isotopologue pairs against random ion pairs (Welch's t-test), and against a PCA baseline, including stability analysis (Adjusted Rand Index across seeds).

Stage 6 — Cluster galleries. Representative ion images are assembled per cluster to visually confirm the anatomical domains (Figure 3).

Stage 7 — Mass spectra. Mean spectra per cluster and the full average spectrum are plotted for biological interpretation.

In summary, the Julia layer performs all high-throughput binary parsing and image export, while the Python layer performs the 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 comprises 1,596 ion images for the Datura leaf that passed the 2% intensity threshold filter and ROI mask selection. 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.

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 two orders of magnitude in file size (0.07--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 (69 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.

Figure 2. Clustering validation of the two Datura innoxia demonstration datasets. For each dataset, the SimCLR latent space (see the section "Self-Supervised Representation Learning (Python)") was evaluated over a K-sweep (k = 2--20) with four panels: Elbow method (inertia), Silhouette score, Davies-Bouldin index, and 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 and root.

Multi-Dataset Unsupervised Segmentation

The segmentations of the two most architecturally demanding benchmark tissues are shown in Figure 3: the learned 128-dimensional embeddings projected with t-SNE and colored by the K-Means assignment at each dataset's adopted K, alongside individual representative ion images for the four largest clusters 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 consistently display the continuous, gradient-like geometry discussed below, which reflects the underlying anatomical continuum rather than clustering failure.

Figure 3. 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 individual representative ion images (viridis, m/z annotated) from the four largest clusters of each tissue, 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 3 — t-SNE segmentations and representative ion images for the mouse bladder and human colon.

Interpreting the Continuous Latent Manifold

Reviewers from a computer vision background may expect an optimal unsupervised result to yield discrete, well-separated "blobs" in the t-SNE projection. The continuous, connected geometry observed in our manifold—resembling a smooth curve or "S-shape"—is not a sign of clustering failure; it is, in fact, the mathematically correct and expected projection of a continuous biological gradient [@diaconis_horseshoes_2008]. A biological tissue is not a collection of discrete, isolated tissue types; it is an anatomical continuum transitioning from dense, metabolite-rich structures through paravascular tissue into diffuse parenchyma. Because our encoder successfully learned the underlying structural morphology rather than arbitrary cluster membership, the t-SNE algorithm faithfully projects this continuous biological spectrum into a continuous geometric trajectory [@moon_visualizing_2019]. The application of K-Means clustering onto this manifold is then interpreted as the discretization of this gradient into biologically meaningful bands, not as the discovery of independent, non-overlapping chemical compartments.

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. 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 separates the biosynthetic-site domains: tropinone (m/z 140.17) and tropine (m/z 142.08) are co-localized in one domain, while cuscohygrine (m/z 225.92) and atropine/hyoscyamine (m/z 290.08) are co-localized in a second 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.

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.07 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. Nicolas Sherman, Dra. 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 provided by Yulica Santos Ortega, Spatial Biology Core, University of Virginia, Charlottesville, VA.