Subir archivos a "/"

This commit is contained in:
2026-08-09 06:50:42 +02:00
parent 922ae74e2e
commit d4646da256
+147 -52
View File
@@ -1,30 +1,58 @@
--- ---
title: Anatomical mapping of alkaloids in plant tissues from mass spectrometry imaging data using a deep neuronal network segmentation title: "A scalable deep learning workflow for mass spectrometry imaging: benchmarking Julia-Python hybrid processing across multi-instrument datasets"
bibliography: zotero.bib bibliography: zotero.bib
abstract: | abstract: |
Mass Spectrometry Imaging (MSI) is a powerful technique for revealing the spatial distribution of metabolites in complex biological systems, where metabolism is highly localized and the non-uniform distribution of compounds carries important biological implications. Here we present a self-supervised deep learning workflow based on the SimCLR architecture with a custom Group-Normalized Fully Convolutional encoder to extract morphological features from ion images without prior labeling. Our hybrid Julia-Python computational framework leverages Julia for rapid data ingestion and Python for representation learning. Applied to *Datura innoxia* leaves at 150 µm spatial resolution via LD-LTP ionization, we analyze metabolite distribution and identify ten distinct metabolic domains, revealing the spatial organization of tropane alkaloid biosynthesis and transport. All code and data are available under permissive licenses to ensure reproducibility. 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 against Cardinal (R/Bioconductor) and MALDIquant (R) on seven public centroid-mode datasets spanning 0.07–4.4 GB (LD-LTP, AP-SMALDI, MALDI, DESI). Under this equalized workload, the Julia engine generates an ion slice in ~0.08–0.09 s across every dataset — roughly 50–150× faster than Cardinal and several times faster than MALDIquant — while its resident memory (VmRSS) is equal or lower than Cardinal's on the three largest datasets, and it completes the additional normalization and export steps within the same memory envelope, all orchestrated by a single reproducible entry point. 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 of the leaf recovers five spatially coherent metabolic domains and of the root six, co-localizing the tropane alkaloid biosynthetic pathway in the root and its transport intermediates in the leaf vasculature.
keywords: mass spectrometry imaging, Julia language, deep learning, SimCLR, contrastive learning, group normalization, Datura innoxia, spatial metabolomics keywords: mass spectrometry imaging, Julia language, Python, hybrid pipeline, benchmark, peak RAM, reproducibility, Docker, deep learning, SimCLR, contrastive learning, spatial metabolomics
--- ---
# Introduction # Introduction
The analysis of the spatial distribution of secondary metabolites in medicinal plants is essential for understanding biosynthesis, transport, and chemical defense processes [@ziegler_alkaloid_2008; @garcia-rojas_identification_2024]. *Datura innoxia*, known for its rich composition of tropane alkaloids, represents a highly complex biological model due to the biosynthesis of these compounds in the roots and their differential transport to the shoots [@schlesinger_tropane_2021]. Previous studies have employed laser desorption low-temperature plasma (LD-LTP) techniques to map these alkaloids in fruits and seeds [@moreno-pedraza_elucidating_2019]. 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. This is the "two-language problem" at the heart of current MSI software engineering: no single ecosystem offers both the throughput required for high-performance binary ingestion and the machine learning maturity required for representation learning.
Traditionally, MSI data analysis has relied on linear methods and standard imaging protocols [@cole_imaging_2023]. However, a software engineering challenge arises: while Python possesses the most mature ecosystem for Artificial Intelligence, its performance in handling massive binary files in imzML format [@schramm_imzml_2012] is often limited. Conversely, Julia offers execution speeds comparable to C++ for compute-heavy tasks and outperforms interpreted languages in scientific computing benchmarks. The integration of these two ecosystems addresses the "two-language problem"—the historical trade-off between the ease of a high-level language and the performance of a low-level one. In this article, we propose that the synergy between these two languages enables a "next-generation" MSI workflow. The remainder of this paper details the acquisition parameters, the hybrid Julia-Python implementation, the unsupervised segmentation results, and a comparison against traditional linear baselines. 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 without manual environment setup.
To evaluate this 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 centroid-mode datasets spanning 0.07–4.4 GB from multiple ionization platforms (LD-LTP, AP-SMALDI, MALDI, DESI) and biological matrices. 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. As a demonstration of the workflow's biological utility, we then apply it to a leaf 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 unsupervised segmentation of the demonstration dataset, and a comparison against traditional linear baselines.
# Materials and Methods # Materials and Methods
## MSI Data Acquisition (LD-LTP-MSI) ## Application Dataset: LD-LTP-MSI of *Datura innoxia*
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. 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.
## 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 \ref{tab:datasets}). All datasets are in centroid acquisition mode and were processed using the same pipeline configuration described in Section \ref{sec:julia_preprocessing}, with the exception that ROI masks were applied only to the Leaf dataset (for which an optical image was available). The remaining datasets were processed without a tissue mask, relying on the default intensity threshold of 2\% of the base peak for peak filtering.
\begin{table}[htbp]
\centering
\caption{Benchmark datasets used in this study.}
\label{tab:datasets}
\begin{tabular}{llllrl}
\toprule
Dataset & Ionization & Mass Analyzer & Organism & File Size & Pixels \\ \midrule
Leaf (Datura) & 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 \\
\bottomrule
\end{tabular}
\end{table}
## Computational Environment and Reproducibility ## Computational Environment and Reproducibility
All computational analyses, including the high-performance data extraction in Julia and the deep learning-based representation learning in Python, were performed across two mobile workstations. The primary data ingestion and analysis were executed on a system with the following specifications: Processor: Intel(R) Core(TM) i5-10210U CPU @ 1.60 GHz (4 cores, 8 threads), Memory: 32 GB DDR4 RAM, Graphics: Intel UHD Graphics (CometLake-U GT2), and Operating System: Ubuntu 24.04.4 LTS (Linux Kernel 6.8.0-110-generic). Hardware-accelerated neural network training (CUDA) was executed on a Dell G15 5525 equipped with an AMD Ryzen 5 6600H processor (6 cores, 12 threads @ 4.57 GHz), 8 GB RAM, and an NVIDIA GeForce RTX 3050 Mobile discrete GPU, running Pop OS 24.04 LTS. To ensure rigorous compliance with MSI reporting standards such as MIAMSIE [@gustafsson_balancing_2018] and SMART [@xi_smart_2023], as well as modern machine learning reproducibility guidelines like REFORMS [@kapoor_reforms_2024], the complete hybrid workflow was containerized using Docker. This guarantees that both the Julia binary parsing algorithms and the Python machine learning dependencies remain perfectly reproducible across diverse hardware platforms. All computational analyses, including the high-performance data extraction in Julia and the deep learning-based representation learning in Python, were performed across two mobile workstations. The primary data ingestion and analysis were executed on a system with the following specifications: Processor: Intel(R) Core(TM) i5-10210U CPU @ 1.60 GHz (4 cores, 8 threads), Memory: 22 GB DDR4 RAM, Graphics: Intel UHD Graphics (CometLake-U GT2), and Operating System: Ubuntu 24.04.4 LTS (Linux Kernel 6.8.0-110-generic). Hardware-accelerated neural network training (CUDA) was executed on a Dell G15 5525 equipped with an AMD Ryzen 5 6600H processor (6 cores, 12 threads @ 4.57 GHz), 8 GB RAM, and an NVIDIA GeForce RTX 3050 Mobile discrete GPU, running Pop OS 24.04 LTS.
Reproducibility is a core design goal of the workflow, not an afterthought. 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 (Section \ref{sec:pipeline}) 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.
The manuscript itself is version-controlled markdown compiled to a natbib/biber PDF in a single command, so the text, figures, and tables can be regenerated on any machine. Locally, with a LaTeX toolchain (pandoc, pdflatex, biber), \texttt{make all} rebuilds the PDF from this source; alternatively, without installing any LaTeX software, \texttt{make docker-build \&\& make docker-pdf} builds a portable compiler image (pandoc + TeX Live on Debian Bookworm) that produces the identical PDF. The complete pipeline and manuscript therefore require nothing more than Docker to reproduce the results, figures, and compiled article bit-for-bit.
## High-Performance Processing and Data Normalization (Julia) ## High-Performance Processing and Data Normalization (Julia)
\label{sec:julia_preprocessing}
We conducted the preprocessing stage using the JuliaMSI framework [@sierra-alvarez_juliamsi_2025], a platform specifically engineered to address the computational bottlenecks of the "two-language problem." 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. We conducted the preprocessing stage using the JuliaMSI framework [@sierra-alvarez_juliamsi_2025], a platform specifically engineered to address the computational bottlenecks of the "two-language problem." 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.
The selection of Julia as the primary engine for data ingestion is justified by its superior performance in handling the high-dimensional sparse matrices characteristic of imzML files. Recent benchmarks have demonstrated that Julia-based architectures, such as the JuliaMSI framework, outperform traditional R-based implementations (e.g., RmsiGUI) by significant margins, showing up to 5.2-fold faster processing on Linux environments [@sierra-alvarez_juliamsi_2025]. Furthermore, at the library level, Julia's native parsing of binary spectral data has been shown to be up to 214 times faster than equivalent implementations in R [@rosas-roman_technical_2024]. This computational efficiency is critical for resolving the "two-language problem," as it allows the rapid extraction of hundreds of mass slices and their subsequent normalization in a fraction of the time required by interpreted environments, effectively enabling a high-throughput bridge to the Python-based deep learning ecosystem. The selection of Julia as the primary engine for data ingestion is justified by its superior performance in handling the high-dimensional sparse matrices characteristic of imzML files. Recent benchmarks have demonstrated that Julia-based architectures, such as the JuliaMSI framework, outperform traditional R-based implementations (e.g., RmsiGUI) by significant margins, showing up to 5.2-fold faster processing on Linux environments [@sierra-alvarez_juliamsi_2025]. Furthermore, at the library level, Julia's native parsing of binary spectral data has been shown to be up to 214 times faster than equivalent implementations in R [@rosas-roman_technical_2024]. This computational efficiency is critical for resolving the "two-language problem," as it allows the rapid extraction of hundreds of mass slices and their subsequent normalization in a fraction of the time required by interpreted environments, effectively enabling a high-throughput bridge to the Python-based deep learning ecosystem.
Ion Extraction and Filtering: We extracted mass slices from the `Leaf.imzML` dataset within the \textit{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 $\sim$0.08--0.09 \textit{m/z} per channel. The monoisotopic peak of scopolamine $[M+H]^+$ (exact mass 304.1549) is detected at the binned channel \textit{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 (\textit{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. Ion Extraction and Filtering: We extracted mass slices from the `Leaf.imzML` dataset within the \textit{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$ \textit{m/z} per channel. The monoisotopic peak of scopolamine $[M+H]^+$ (exact mass 304.1549) is detected at the binned channel \textit{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 (\textit{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 implemented a dynamic TrIQ algorithm [@rosas-roman_contrast_2021]. For each raw ion map $I_{raw}$, the algorithm identifies a signal threshold $T$ based on the distribution of non-zero, finite intensity values $V = \{i \in I_{raw}\mid i > 0, i < \infty\}$. The threshold is defined as the 98th percentile of this distribution: TrIQ Normalization (Threshold Intensity Quantization): To mitigate the impact of "hotspots"—stochastic pixels with disproportionately high intensities that obscure lower-abundance metabolic distributions—we implemented a dynamic TrIQ algorithm [@rosas-roman_contrast_2021]. For each raw ion map $I_{raw}$, the algorithm identifies a signal threshold $T$ based on the distribution of non-zero, finite intensity values $V = \{i \in I_{raw}\mid i > 0, i < \infty\}$. The threshold is defined as the 98th percentile of this distribution:
@@ -38,19 +66,51 @@ This transformation ensures that 98% of the chemical signal is represented withi
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 serves as an absolute spatial ground truth. Standard computational interpolation (such as bilinear resizing) forces anisotropic stretching —disproportionately warping the leaf morphology— and introduces artificial floating-point values at the sharp boundaries of the tissue mask. By mapping the raw $161 \times 106$ coordinates directly into the center of a zero-matrix, we preserved the true, undistorted anatomical geometry of the leaf while achieving the uniform dimensionality required by the convolutional layers. 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 serves as an absolute spatial ground truth. Standard computational interpolation (such as bilinear resizing) forces anisotropic stretching —disproportionately warping the leaf morphology— and introduces artificial floating-point values at the sharp boundaries of the tissue mask. By mapping the raw $161 \times 106$ coordinates directly into the center of a zero-matrix, we preserved the true, undistorted anatomical geometry of the leaf while achieving the uniform dimensionality required by the convolutional layers.
Benchmark against Cardinal (R): To contextualize the performance of our Julia-based preprocessing within the current MSI software landscape, we conducted a controlled benchmark against Cardinal 3.14.0, the standard R/Bioconductor package for MSI analysis [@bemis_cardinal_2015]. Both pipelines processed the same `Leaf.imzML` dataset on identical hardware (Intel i5-10210U, 32 GB RAM, Ubuntu 24.04). Cardinal was run in its default configuration with in-memory storage, while Julia used the pipeline configuration described above (ROI mask, 2\% peak threshold, TrIQ normalization, zero-padded 256$\times$256 PNG export). The benchmark measured three comparable stages---file loading, spectral data extraction, and ion image extraction---and recorded the number of ions each workflow made available for downstream analysis. Cardinal loaded and processed all 17,066 raw \textit{m/z} channels in 4.84 seconds but applied no ROI masking, peak filtering, intensity normalization, or image export (Figure \ref{fig:benchmark}A). Julia completed all preprocessing stages---including ROI-masked peak picking (1,596 chemically relevant ions), batch slice extraction, TrIQ normalization, zero-padding, and threaded PNG export---in 33.63 seconds (Figure \ref{fig:benchmark}A). Although Cardinal's total wall time is lower, it leaves 100\% of the subsequent processing burden (normalization, masking, dimensionality reduction) to downstream R routines, which lack Julia's JIT compilation and multithreading. When normalized by throughput, Julia processes 47.5 ions per second versus Cardinal's 20.7 ions per second (Figure \ref{fig:benchmark}B), representing a 2.3$\times$ advantage in end-to-end preprocessing throughput. Critically, Cardinal's design loads the full, unfiltered mass list into memory---17,066 raw \textit{m/z} values per pixel across 17,066 pixels---which imposes an increasingly severe RAM bottleneck as datasets scale to higher spatial resolutions or larger tissue sections. Julia's on-the-fly binary parsing and ROI-masked peak filtering reduce the in-memory footprint from the full sparse matrix to only the chemically relevant ions (1,596 channels), directly addressing the scalability challenge that emerges when processing whole-organ or multi-tissue MSI acquisitions with millions of pixels. This throughput advantage grows with dataset size: Julia's threaded slice extraction and batch I/O scale across available CPU cores, whereas R's single-threaded architecture and interpreter overhead create a compounding performance gap at every stage of the preprocessing pipeline (Figure \ref{fig:benchmark}C). ## 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 \ref{tab:datasets}) on identical hardware (Intel i5-10210U, 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, (2) average spectrum computation and peak detection (2\% threshold of base peak, binned to a common 0.01 Da grid spanning 50--1000 m/z), and (3) in-memory extraction of the target ion image at the biologically validated precursor *m/z* 304.17 (tolerance 0.05 Da). 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 the same 0.01 Da grid and the target ion image was extracted with the native 3.x API (\texttt{bin()} + \texttt{sliceImage()}); for MALDIquant, spectra were read into \texttt{MassSpectrum} objects and processed with \texttt{reduceIntensity}/\texttt{detectPeaks}, and the ion image was recovered from the aligned spectrum objects. Peak resident memory (VmRSS) and wall-clock time were measured per stage via `/proc/self/status`. This apples-to-apples design deliberately excludes Julia-only steps (TrIQ normalization and PNG export) so that the comparison reflects identical computational work and no stage overlap between instruments.
The equalized benchmark shows that the Julia and R pipelines land at very different per-stage strengths (Figure \ref{fig:benchmark}). The single most dramatic, reproducible difference is ion-image (slice) generation: Julia returns the target ion slice in 0.08--0.09 s on every dataset, whereas Cardinal requires 4.4--13.6 s and MALDIquant 0.15--1.5 s — a 50--150-fold margin over Cardinal and a severalfold margin over MALDIquant. In peak resident memory (VmRSS), results are dataset-dependent rather than monotonically favorable to one ecosystem: Julia uses less peak resident RAM than Cardinal on five of the seven datasets (Datura leaf 2,708 MB vs 2,999 MB; Datura root 3,188 MB vs 3,601 MB; Mouse bladder 1,447 MB vs 1,620 MB; Mouse liver 2,810 MB vs 2,925 MB; Mouse stomach 4,964 MB vs 5,035 MB) but more than Cardinal on the two smallest (Human colon 720 MB vs 550 MB; San Pedro 1,745 MB vs 1,565 MB). Total wall-clock time for the identical three steps is likewise dataset-dependent: Julia is fastest on the two smallest datasets (Human colon 2.9 s vs 10.7 s; Mouse bladder 20.3 s vs 22.3 s), while Cardinal is faster on the five larger datasets, the gap driven almost entirely by Cardinal's batched average-spectrum step (e.g., Mouse stomach total 79.7 s vs 42.4 s; Datura leaf 42.4 s vs 17.5 s). We report these measurements transparently, including where the R ecosystem is superior: the advantage of the Julia-Python pipeline is not wall-clock speed on every isolated step, but that it \emph{completes the entire 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 does not require staged intermediate files or manual memory management. Practically, all three tools can preprocess all seven datasets on the 22 GB reference machine, and the Julia workflow's differentiation lies in its integrated end-to-end export and its ion-slice throughput at scale.
\begin{figure}[htbp] \begin{figure}[htbp]
\centering \centering
\includegraphics[width=\textwidth]{Figure-benchmark.png} \includegraphics[width=\textwidth]{figure_ram_comparison.png}
\caption{Benchmark comparison of preprocessing performance: Cardinal (R) vs Julia workflow on the \texttt{Leaf.imzML} dataset. (A) Stage-by-stage timing breakdown. Cardinal loads raw data (4.46 s) and extracts 100 ion images (0.37 s) without masking or normalization. Julia loads data (4.16 s), performs ROI-masked peak picking (16.92 s), batch-extracts 1,596 slices (11.45 s), and exports fully preprocessed PNGs (1.09 s). (B) Throughput in ions processed per second. Julia achieves 47.5 ions/s vs 20.7 ions/s for Cardinal, a 2.3$\times$ advantage, while applying TrIQ normalization, ROI masking, and zero-padded embedding. (C) Estimated total preprocessing time as a function of dataset \textit{m/z} channels. Cardinal's linear scaling (blue, dashed) reflects unfiltered processing of all raw channels. Julia's sub-linear scaling (orange, solid) reflects ROI-filtered peak selection that restricts processing to chemically informative ions, with the throughput gap widening at larger \textit{m/z} ranges.} \caption{Equalized three-way benchmark of Julia-Python vs Cardinal (R) and MALDIquant (R) preprocessing under an identical per-stage workload (load + average spectrum + peaks + one ion slice at the biologically validated *m/z* 304.17, tolerance 0.05 Da) across seven public datasets ordered by file size (lightest to heaviest). Peak resident RAM (VmRSS) per dataset. Julia uses less peak resident RAM than Cardinal on five of the seven datasets, including the three largest, and more on the two smallest; per-stage timings, including the two-orders-of-magnitude faster Julia ion-slice generation, are discussed in the text. The Julia engine additionally completes TrIQ normalization and PNG export of every ion image within its measured envelope.}
\label{fig:benchmark} \label{fig:benchmark}
\end{figure} \end{figure}
## Complete Hybrid Pipeline: From imzML to Metabolic Domains
\label{sec:pipeline}
The full workflow (Figure \ref{fig:workflow}) is orchestrated by a single entry point, \texttt{run\_full\_pipeline.sh}, which chains seven stages that consume only the raw imzML/ibd file pair and produce the final metabolic segmentation, together with a standalone artifact generator that assembles the ion carpets from the Stage-1 export. 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 (\texttt{ion\_<mz>.png}) reserved exclusively for the deep learning stage, and a viridis-colored PNG of the same map (\texttt{outputs/ion\_images\_viridis/}) built with the native Julia \texttt{ViridisPalette}, so every ion of the dataset is exported individually in a publication-ready colormap. 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.
**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.
**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$.
**Stage 4 — t-SNE visualization.** Latent embeddings are projected to two dimensions and colored by the selected number of clusters.
**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.
**Stage 7 — Mass spectra.** Mean spectra per cluster and the full average spectrum are plotted for biological interpretation.
**Ion carpet export (standalone generator).** A carpet assembler tiles the Julia-produced viridis corpus (every ion of the dataset, exported individually during Stage 1) into a full-dataset mosaic, plus per-cluster mosaics, for manual exploration and publication figures. The grayscale PNG corpus remains reserved exclusively for the deep learning stage.
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.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{Figure-workflow.png}
\caption{Complete hybrid Julia-Python workflow. Julia ingests the imzML/ibd files, extracts and normalizes all ion images, and exports them as PNGs; Python trains a SimCLR convolutional encoder, clusters the resulting embeddings, and validates and visualizes the metabolic domains.}
\label{fig:workflow}
\end{figure}
## Self-Supervised Representation Learning (Python) ## 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. We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorch_2019], adapting the framework to the unique properties of mass spectrometry imaging.
Model Architecture and VRAM Optimization: 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 1). Model Architecture and VRAM Optimization: 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 \ref{tab:training_hyperparameters}).
To enable training on consumer-grade hardware (NVIDIA RTX 3050 Mobile, ~4 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. To enable training on consumer-grade hardware (NVIDIA RTX 3050 Mobile, ~4 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.
@@ -81,99 +141,134 @@ The Camp A Paradigm: Prohibition of Spatial Augmentations: Standard computer vis
Spherical K-Means via Latent Re-Normalization: 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. Spherical K-Means via Latent Re-Normalization: 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.
Clustering and Optimization: To determine the optimal number of clusters (k), we performed a multi-metric systematic sweep from k = 2 to k = 20 (Figure 1A). While global mathematical optima were observed at k = 2 and k = 5 —corresponding to a coarse differentiation between the leaf tissue and the background— these configurations failed to resolve the specialized anatomical compartments of the leaf. We identified k = 10 as the functional optimum, supported by a Silhouette Score of 0.4675 (Figure 1B), a Davies-Bouldin Index of 0.9389 (Figure 1C), and a Calinski-Harabasz Index of 1212.54 (Figure 1D). This value represents a stable convergence point where the latent space successfully deconvolutes the hierarchical vascular architecture (midrib and secondary veins) and localized metabolic sequestration sites without incurring over-segmentation. Consequently, this choice prioritizes anatomical fidelity over mathematical parsimony, ensuring that the resulting metabolic map accurately reflects the complex tissue compartmentalization of *Datura innoxia*. Clustering and Optimization: To determine the optimal number of clusters (k), we performed a multi-metric systematic sweep from k = 2 to k = 20 (Figure \ref{fig:clustering}A), evaluating the Silhouette Score, Davies-Bouldin Index, and Calinski-Harabasz Index at each value. The three metrics agree that the optimum does not lie at high k: the Silhouette Score peaks at k = 2 (0.5668) and declines monotonically thereafter, while the Davies-Bouldin Index and Calinski-Harabasz Index both reach their optimum at k = 5 (0.9124 and 1304.29, respectively; Figure \ref{fig:clustering}B--D). Because k = 2 conflates the entire tissue into a single "leaf vs background" split and fails to resolve any internal anatomical compartment, we adopt k = 5, the optimum returned jointly by Davies-Bouldin and Calinski-Harabasz, as the number of metabolic clusters. This value balances cluster compactness against anatomical resolution, producing stable, spatially coherent domains (Silhouette Score 0.5087 at k = 5) without the over-segmentation observed at higher k, where the Calinski-Harabasz Index decreases steadily (from 1304 at k = 5 to 821 at k = 20). The resulting five-cluster map resolves the vascular and laminar architecture of the *Datura innoxia* leaf while remaining biologically interpretable.
# Results and Discussion # Results and Discussion
## Computational Benchmark: Julia vs Cardinal and MALDIquant Across Seven Datasets
The controlled three-way benchmark (Figure \ref{fig:benchmark}) evaluates the identical preprocessing workload — imzML load, average spectrum, peak detection (2\% of base peak), and one in-memory ion slice at *m/z* 304.17 — on seven datasets spanning two orders of magnitude in file size (69 MB to 4.4 GB). Peak resident memory and wall-clock time were measured on the same hardware (Intel i5-10210U, 22 GB RAM). The results establish three findings. First, the Julia ion-slice operation is two orders of magnitude faster than Cardinal on every dataset (0.08 s vs 4.4--13.6 s) and materially faster than MALDIquant, which is the dominant per-ion cost when exporting a full ion corpus. Second, peak resident memory (VmRSS) is Julia-leaning but dataset-dependent: Julia is below Cardinal on five of the seven datasets, including the three largest; Cardinal and MALDIquant are both lighter on the two smallest samples (Human colon and San Pedro). Third, the differentiation is not universal raw wall-clock speed: total runtime for the identical three steps is Julia-favorable on the two smallest datasets (e.g., Human colon 2.9 s vs 10.7 s) and R-favorable on the largest, driven by Cardinal's batched average-spectrum step. 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. All three tools preprocess all seven datasets on this 22 GB machine, and we report the measurements transparently in the benchmark repository, including those that favor the R ecosystem.
Having established the computational performance of the workflow, the remainder of the results section demonstrates its biological utility on a *Datura innoxia* leaf as a case study.
\begin{figure}[p] \begin{figure}[p]
\centering \centering
\includegraphics{Fig-clustering.png} \includegraphics{Fig-clustering.png}
\caption{Clustering architecture exploration and metabolic specialization visualization across anatomical zones of \textit{Datura innoxia} leaf. (A-D) Quantitative validation: Elbow Method, Silhouette Score (0.4675 at k=10), Davies-Bouldin Index (0.9389 at k=10), Calinski-Harabasz Index (1212.54 at k=10). (E) t-SNE visualization of metabolic similarity across anatomical zones with ten distinct clusters.} \caption{Case-study application of the workflow to a *Datura innoxia* leaf: clustering architecture exploration. (A-D) Quantitative validation across the k-sweep (k = 2--20): Elbow Method (inertia), Silhouette Score (peak at k = 2; 0.5087 at k = 5), Davies-Bouldin Index (optimum 0.9124 at k = 5), Calinski-Harabasz Index (optimum 1304.29 at k = 5). The dashed optimum at k = 5 (Davies-Bouldin and Calinski-Harabasz) is adopted as the number of metabolic clusters.}
\label{fig:clustering} \label{fig:clustering}
\end{figure} \end{figure}
We conducted direct surface analysis of *Datura innoxia* leaves using an LD-LTP-MS setup in positive ionization mode. 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. Although we acquired raw data in profile mode, we subsequently processed the spectra for baseline correction and centroid refinement to facilitate comparison. The resulting fragmentation pattern from the leaf surface showed an excellent spectral match with the commercial scopolamine reference standard. The presence of diagnostic product ions across the *m/z* 80–320 range confirms 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 \textit{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 \texttt{ion\_304.17.png}. The MS/MS fragmentation pattern therefore provides direct structural validation for the ion signal contained in this specific binned channel, establishing a direct link between the high-resolution tandem mass spectrometry identification and the imaging data. The adjacent bins (\textit{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. We conducted direct surface analysis of the *Datura innoxia* leaf using an LD-LTP-MS setup in positive ionization mode. 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. Although we acquired raw data in profile mode, we subsequently processed the spectra for baseline correction and centroid refinement to facilitate comparison. The resulting fragmentation pattern from the leaf surface showed an excellent spectral match with the commercial scopolamine reference standard. The presence of diagnostic product ions across the *m/z* 80–320 range confirms 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 \textit{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 \texttt{ion\_304.17.png}. The MS/MS fragmentation pattern therefore provides direct structural validation for the ion signal contained in this specific binned channel, establishing a direct link between the high-resolution tandem mass spectrometry identification and the imaging data. The adjacent bins (\textit{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.
## Latent Space Geometry and Chemical Validation ## Latent Space Geometry and Chemical Validation
The high-dimensional embeddings generated by the custom GroupNorm backbone were projected into a 2-D manifold using t-SNE (Figure 1E) [@van_der_maaten_visualizing_2008]. The resulting latent space exhibits a highly structured geometry, where ions are grouped not by their absolute intensity, but by their shared spatial topographies. A cornerstone of the validation for this self-supervised approach is the emergence of Isotopic Coherence within the latent manifold (Table 2). In MSI, a molecular species and its naturally occurring isotopes (e.g., $[M+H]^+$ and $[M+H+1]^+$) are fundamentally tied by an identical spatial distribution, providing a form of natural "ground truth" that requires no manual annotation. The high-dimensional embeddings generated by the custom GroupNorm backbone were projected into a 2-D manifold using t-SNE (Figure \ref{fig:tsne_clusters}) [@van_der_maaten_visualizing_2008]. The resulting latent space exhibits a highly structured geometry, where ions are grouped not by their absolute intensity, but by their shared spatial topographies. A cornerstone of the validation for this self-supervised approach is the emergence of Isotopic Coherence within the latent manifold (Table \ref{tab:metabolites}). In MSI, a molecular species and its naturally occurring isotopes (e.g., $[M+H]^+$ and $[M+H+1]^+$) are fundamentally tied by an identical spatial distribution, providing a form of natural "ground truth" that requires no manual annotation.
To quantitatively validate this, we calculated the Cosine Similarity between the normalized feature vectors of known isotopic pairs. A global statistical analysis across 1,394 discovered isotopic pairs yielded a mean latent distance of $0.2879$, compared to $0.5979$ for random ion pairs, achieving profound statistical significance (Welch's t-test, $p < 10^{-300}$). Of these, 540 pairs 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.9968. Although the SimCLR framework is entirely agnostic to the mass-to-charge (*m/z*) values or the chemical identity of the inputs, the encoder consistently projected isotopic pairs into tightly bound coordinates. To quantitatively validate this, we calculated the Cosine Similarity between the normalized feature vectors of known isotopic pairs. 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. Although the SimCLR framework is entirely agnostic to the mass-to-charge (*m/z*) values or the chemical identity of the inputs, the encoder consistently projected isotopic pairs into tightly bound coordinates.
Disproving Background Mask Exploitation: A common concern in applying deep learning to zero-padded imaging data is that the network may exploit the outer tissue boundary —an artifact shared identically by every single ion image— as a "shortcut" feature, rather than learning true internal biology [@purushwalkam_demystifying_2020]. Our data provides an elegant empirical refutation of this hypothesis. Atropine (*m/z* 290.08) and its $+1$ isotope (*m/z* 291.17) share a perfectly identical outer mask boundary but have fundamentally different absolute signal intensities due to natural isotopic abundance ratios. If the encoder were exploiting the mask, these two ions would appear identical regardless, yielding a trivially high similarity—providing no discriminative power. Instead, the NT-Xent loss function explicitly penalizes the encoder for relying on zero-variance features shared across all images in the negative pair denominator [@chen_simple_2020]. Any feature constant across all ion images —including the outer mask— provides zero contrastive gradient, and is mathematically discarded in favor of internal morphological variations. The observed cosine similarity of 0.9968 therefore constitutes proof that the network has converged on the true shared spatial silhouette of the ion inside the tissue, not the common boundary around it. Disproving Background Mask Exploitation: A common concern in applying deep learning to zero-padded imaging data is that the network may exploit the outer tissue boundary —an artifact shared identically by every single ion image— as a "shortcut" feature, rather than learning true internal biology [@purushwalkam_demystifying_2020]. Our data provides an elegant empirical refutation of this hypothesis. Atropine (*m/z* 290.08) and its $+1$ isotope (*m/z* 291.17) share a perfectly identical outer mask boundary but have fundamentally different absolute signal intensities due to natural isotopic abundance ratios. If the encoder were exploiting the mask, these two ions would appear identical regardless, yielding a trivially high similarity—providing no discriminative power. Instead, the NT-Xent loss function explicitly penalizes the encoder for relying on zero-variance features shared across all images in the negative pair denominator [@chen_simple_2020]. Any feature constant across all ion images —including the outer mask— provides zero contrastive gradient, and is mathematically discarded in favor of internal morphological variations. The observed cosine similarity of 0.9959 therefore constitutes proof that the network has converged on the true shared spatial silhouette of the ion inside the tissue, not the common boundary around it.
Furthermore, this structural mapping revealed the phenomenon of Inverse Mask Correlation (Negative Space Co-Exclusion). The network successfully grouped ions that concentrate directly within the vascular bundle (positive distributions, e.g., Scopolamine *m/z* 304.00, achieving a similarity of $0.9863$ with Atropine *m/z* 290.08) with ions that are biologically excluded from the vein (negative distributions, appearing as dark shadows). Because the encoder projects all spatial maps onto an $L_2$ unit hypersphere, it recognizes that the sharp geometric boundary of a bright vein and the boundary of its complementary dark shadow are topologically equivalent structures. Such coherence confirms that the learned representations are anchored in global biological reality rather than technical artifacts. Notably, the scopolamine signal identified by MS/MS at *m/z* 304.17 appears in the imaging data across multiple binned channels spanning the isotopic envelope (\textit{m/z} 304.00 to 304.42, bin spacing $\sim$0.08--0.09). The pipeline independently generates an ion image at the exact \textit{m/z} 304.17 bin (\texttt{ion\_304.17.png}), which receives direct structural validation from the MS/MS fragmentation pattern. In the clustering, the lower-mass bins (303.83--304.08) are assigned to Cluster 7 while the higher-mass bins (304.17--304.42) are assigned to Cluster 2, reflecting subtle spatial intensity variations across the isotopic distribution at the tissue level. Both clusters capture vascular-related patterns (Section 4.3), confirming that the spectral binning inherent to MSI acquisition preserves biological coherence in the clustering despite the technical splitting of a single molecular species across multiple channels. Furthermore, this structural mapping revealed the phenomenon of Inverse Mask Correlation (Negative Space Co-Exclusion). The network successfully grouped ions that concentrate directly within the vascular bundle (positive distributions, e.g., Scopolamine *m/z* 304.00, achieving a similarity of $0.9850$ with Atropine *m/z* 290.08) with ions that are biologically excluded from the vein (negative distributions, appearing as dark shadows). Because the encoder projects all spatial maps onto an $L_2$ unit hypersphere, it recognizes that the sharp geometric boundary of a bright vein and the boundary of its complementary dark shadow are topologically equivalent structures. Such coherence confirms that the learned representations are anchored in global biological reality rather than technical artifacts. Notably, the scopolamine signal identified by MS/MS at *m/z* 304.17 appears in the imaging data across multiple binned channels spanning the isotopic envelope (\textit{m/z} 304.00 to 304.42, bin spacing $\sim0.08$--$0.09$). The pipeline independently generates an ion image at the exact \textit{m/z} 304.17 bin (\texttt{ion\_304.17.png}), which receives direct structural validation from the MS/MS fragmentation pattern. In the clustering, every bin of the scopolamine isotopic envelope — 303.92 through 304.42 — is assigned to the same domain, Cluster 2, together with atropine/hyoscyamine (*m/z* 290.08) and 6-hydroxyhyoscyamine (*m/z* 306.25). The self-supervised encoder therefore groups the full isotopic envelope of a single molecular species into one spatially coherent metabolic domain (Section \ref{sec:case_study_segmentation}), confirming that the spectral binning inherent to MSI acquisition does not fragment the biological signal.
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 *Datura innoxia* leaf is not a collection of discrete, isolated tissue types; it is an anatomical continuum transitioning from the dense, alkaloid-rich midrib through the paravascular tissue into the diffuse parenchyma of the lamina. 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 (k=10) 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. 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 *Datura innoxia* leaf is not a collection of discrete, isolated tissue types; it is an anatomical continuum transitioning from the dense, alkaloid-rich midrib through the paravascular tissue into the diffuse parenchyma of the lamina. 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 (k=5) 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.
\begin{table}[htbp] \begin{table}[htbp]
\centering \centering
\caption{Representative metabolites identified in \textit{Datura innoxia} and their latent space assignment.} \caption{Representative metabolites identified in \textit{Datura innoxia} leaf and their latent space assignment (k = 5).}
\label{tab:metabolites} \label{tab:metabolites}
\begin{tabular}{ccclp{6cm}} \begin{tabular}{ccclp{6cm}}
\toprule \toprule
\textit{m/z} Obs. & Identification & Formula $[M+H]^+$ & Cluster & Anatomical Significance \\ \midrule \textit{m/z} Obs. & Identification & Formula $[M+H]^+$ & Cluster & Anatomical Significance \\ \midrule
304.00 & Scopolamine & $C_{17}H_{22}NO_4$ & 7 & Midrib-associated distribution with laminar islands. Lower-mass bins of the isotopic envelope. \\ 304.00 & Scopolamine & $C_{17}H_{22}NO_4$ & 2 & Lower-mass bin of the isotopic envelope; vascular-parenchymal distribution. \\
304.17 & Scopolamine & $C_{17}H_{22}NO_4$ & 2 & Directly validated by MS/MS fragmentation at this exact \textit{m/z}. Vascular-parenchymal distribution. \\ 304.17 & Scopolamine & $C_{17}H_{22}NO_4$ & 2 & Directly validated by MS/MS fragmentation at this exact \textit{m/z}. Vascular-parenchymal distribution. \\
304.33 & Scopolamine (adjacent bin) & $C_{17}H_{22}NO_4$ & 2 & Higher-mass bin of the isotopic envelope. Vascular pattern. \\ 304.33 & Scopolamine (adjacent bin) & $C_{17}H_{22}NO_4$ & 2 & Higher-mass bin of the isotopic envelope; same domain as the full envelope (303.92--304.42). \\
290.08 & Atropine / Hyoscyamine & $C_{17}H_{24}NO_3$ & 7 & Co-localized with scopolamine in vascular-parenchymal distribution. Chemical defense and biosynthetic precursor of scopolamine. \\ 290.08 & Atropine / Hyoscyamine & $C_{17}H_{24}NO_3$ & 2 & Co-localized with the full scopolamine envelope (cosine similarity 0.9850). Vascular-parenchymal. \\
225.92 & Cuscohygrine & $C_{13}H_{25}N_2O$ & 3 & Vascular architecture extending from petiole to leaf tip with laminar islands. \\ 225.92 & Cuscohygrine & $C_{13}H_{25}N_2O$ & 4 & Distinct vascular-associated domain with laminar signal. \\
306.25 & 6-Hydroxyhyoscyamine & $C_{17}H_{24}NO_4$ & 2 & Vascular distribution throughout the leaf. \\ 306.25 & 6-Hydroxyhyoscyamine & $C_{17}H_{24}NO_4$ & 2 & Vascular distribution; co-clustered with scopolamine and atropine. \\
142.08 & Tropine / Pseudotropine & $C_8H_{16}NO$ & 9 & Broad parenchymal distribution. Key biosynthetic precursor of tropane alkaloids. \\ 142.08 & Tropine / Pseudotropine & $C_8H_{16}NO$ & 3 & Parenchymal distribution. Key biosynthetic precursor of tropane alkaloids. \\
140.17 & Tropinone & $C_8H_{14}NO$ & 0 & Vascular-apical distribution. Essential for downstream tropane alkaloid biosynthesis. \\ 140.17 & Tropinone & $C_8H_{14}NO$ & 0 & Vascular-apical distribution. Essential for downstream tropane alkaloid biosynthesis. \\
\bottomrule \bottomrule
\end{tabular} \end{tabular}
\end{table} \end{table}
(Identified by MS/MS at *m/z* 304.17). The scopolamine isotopic envelope spans multiple centroid bins (\textit{m/z} 304.00--304.42, spacing $\sim$0.08--0.09). The pipeline independently generates an ion image at \textit{m/z} 304.17, which corresponds exactly to the MS/MS precursor and receives direct structural validation. Lower-mass bins (304.00, 304.08) fall in Cluster 7; higher-mass bins (304.17, 304.25, 304.33, 304.42) in Cluster 2. This split reflects subtle spatial intensity variations across the isotopic distribution, yet both clusters capture vascular-related anatomical patterns, confirming biological coherence. (Identified by MS/MS at *m/z* 304.17). The scopolamine isotopic envelope spans multiple centroid bins (\textit{m/z} 303.92--304.42, spacing $\sim0.08$--$0.09$). The pipeline independently generates an ion image at \textit{m/z} 304.17, which corresponds exactly to the MS/MS precursor and receives direct structural validation. In the k = 5 segmentation, the entire envelope is assigned to Cluster 2 together with atropine/hyoscyamine (*m/z* 290.08) and 6-hydroxyhyoscyamine (*m/z* 306.25), so the self-supervised encoder keeps the complete isotopic envelope of a molecular species within a single metabolic domain instead of fragmenting it across adjacent *m/z* channels.
## Chemical-Anatomical Segmentation in *Datura innoxia* ## Case-Study Segmentation: *Datura innoxia* Leaf and Root
The unsupervised decomposition of the latent space yielded ten distinct molecular domains (Clusters 0–9), each representing a reproducible and spatially resolved chemical pattern across the *Datura innoxia* leaf. These clusters capture the heterogeneity of ion distributions and reveal a structured organization of metabolites at the tissue level. \label{sec:case_study_segmentation}
The unsupervised decomposition of the latent space of the *Datura innoxia* leaf yielded five distinct molecular domains (Clusters 0--4; Figure \ref{fig:tsne_clusters}, Table \ref{tab:summary_segmentation}), 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).
Rather than reflecting random variation, the observed spatial arrangements define consistent chemical domains characterized by differences in ion intensity, co-localization, and spatial continuity. In particular, the distribution of key ions such as atropine ($m/z \approx 290.08$) and scopolamine ($m/z \approx 304.0$) highlights the presence of chemically distinct regions associated with specific anatomical features, including the midrib, lamina, and apical tip (Figure 2, Table 3). Rather than reflecting random variation, the observed spatial arrangements define consistent chemical domains characterized by differences in ion intensity, co-localization, and spatial continuity. In particular, the distribution of key ions such as atropine ($m/z \approx 290.08$) and scopolamine ($m/z \approx 304.0$) highlights the presence of chemically distinct regions associated with specific anatomical features, including the midrib, lamina, and apical tip (Figure \ref{fig:tsne_clusters}, Table \ref{tab:summary_segmentation}).
\begin{figure}[htbp] \begin{figure}[htbp]
\centering \centering
\includegraphics{Figure4.png} \includegraphics{Figure4.png}
\caption{t-SNE-based clustering reveals ten spatially resolved chemical domains in \textit{Datura innoxia} leaves (k=10). Representative ion images (one per cluster) illustrate the characteristic spatial topology: Clusters 0-1 show apical distributions; Clusters 2-3, 5-6, 8-9 exhibit vascular and parenchymal patterns; Cluster 4 and 7 display mixed patterns. A representative photograph of a \textit{Datura innoxia} leaf provides anatomical reference.} \caption{t-SNE projection of the SimCLR latent space for the \textit{Datura innoxia} leaf (k=5), colored by cluster assignment. Five spatially resolved chemical domains are recovered; the continuous manifold reflects the anatomical gradient from the midrib to the lamina. Representative ion images (one per cluster) illustrate the characteristic spatial topology. A representative photograph of a \textit{Datura innoxia} leaf provides anatomical reference.}
\label{fig:tsne_clusters} \label{fig:tsne_clusters}
\end{figure} \end{figure}
\begin{table}[htbp] \begin{table}[htbp]
\centering \centering
\caption{Summary of unsupervised segmentation domains in \textit{Datura innoxia} leaf.} \caption{Summary of unsupervised segmentation domains in the \textit{Datura innoxia} leaf (k = 5).}
\label{tab:summary_segmentation} \label{tab:summary_segmentation}
\begin{tabular}{p{2cm}lp{4cm}p{7cm}} \begin{tabular}{p{1.6cm}cp{4cm}p{6.5cm}}
\toprule \toprule
Domain Group & Clusters & Spatial Pattern & Biological Interpretation \\ \midrule Domain & Cluster & Defining Ions & Biological Interpretation \\ \midrule
Apical & 0, 1 & Large defined islands near apex (0); fully concentrated at distal tip (1) & Terminal accumulation and specialized sequestration at the leaf apex. \\ Tropane alkaloid transport & 2 & Scopolamine (304.00--304.42), Atropine/Hyoscyamine (290.08), 6-Hydroxyhyoscyamine (306.25) & Vascular-parenchymal domain co-localizing the accumulated tropane alkaloids and the full scopolamine isotopic envelope. \\
Vascular & 3, 5 & Midrib signal with small (3) or medium (5) islands across the lamina & Long-distance transport through the vascular system with parenchymal unloading. \\ Cuscohygrine vascular & 4 & Cuscohygrine (225.92) & Vascular-associated domain with laminar signal. \\
Vascular-Apical & 4, 6, 8 & Combined midrib, tip, and pan-laminar islands of varying size & Metabolites concurrently involved in vascular transport and apical accumulation. \\ Tropine parenchymal & 3 & Tropine/Pseudotropine (142.08) & Broad parenchymal domain of the biosynthetic precursor tropine. \\
Vascular-Parenchymal & 2, 7, 9 & Uniform entire leaf surface (2); large islands throughout the leaf (7, 9) & Metabolites transported through the vascular system and broadly distributed across the parenchyma via acropetal transport, with varying degrees of tissue penetration and localized accumulation. \\ Tropinone apical & 0 & Tropinone (140.17) & Vascular-apical domain of the pathway's first committed intermediate. \\
Diffuse / laminar & 1 & -- (no alkaloid markers) & Largest domain (355 ions); diffuse laminar distribution without alkaloid-specific markers. \\
\bottomrule \bottomrule
\end{tabular} \end{tabular}
\end{table} \end{table}
### Vascular and Midrib-Associated Domains (Clusters 3, 4, 5, 6, 8) ### Tropane Alkaloid Co-Localization (Cluster 2)
The clustering analysis reveals a group of domains that exhibit a strong association with the midrib and vascular architecture of the leaf, each with distinct secondary spatial distributions. Cluster 3 displays a clear midrib signal accompanied by small islands distributed across the lamina and enrichment toward the apical tip, suggesting a vascular component with localized parenchymal deposition and terminal accumulation. Cluster 4 combines midrib-associated signal with detectable presence at the leaf tip and large metabolic islands across the leaf surface, indicating a broader spatial dispersion of vascular-associated ions with both terminal and parenchymal components. Cluster 5 presents medium-sized islands throughout the leaf in conjunction with midrib signal, reflecting a predominantly vascular pattern with moderate parenchymal penetration. Cluster 6 exhibits a complex distribution encompassing the midrib, apical tip, and the entire leaf surface, representing a multi-compartmental pattern consistent with metabolites both transported through the vascular system and widely distributed across the mesophyll. Cluster 8 shows midrib and tip signal combined with medium-sized islands across the leaf, indicating a mixed vascular-apical distribution with intermediate parenchymal coverage. The convergence of these clusters around the midrib confirms the central role of the vascular network as a primary conduit for metabolite distribution, while the distinct secondary patterns reflect differences in compound-specific transport efficiency, accumulation zones, and tissue affinity. The most striking result of the k = 5 segmentation is that the entire tropane alkaloid signature of the leaf collapses into a single metabolic domain, Cluster 2 (378 ions). Scopolamine (*m/z* 304.00, 304.17, 304.33), its complete isotopic envelope (303.92--304.42), atropine/hyoscyamine (*m/z* 290.08), and 6-hydroxyhyoscyamine (*m/z* 306.25) are all assigned to this cluster, with a cosine similarity of 0.9850 between scopolamine and atropine embeddings. This co-localization is consistent with acropetal transport of the alkaloids through the vascular system and their distribution across the leaf mesophyll: scopolamine and atropine share a vascular-parenchymal spatial signature, and 6-hydroxyhyoscyamine — the direct biosynthetic precursor of scopolamine — follows the same distribution. The fact that the encoder merges, rather than fragments, the isotopic envelope and the chemically related alkaloids into one domain is the cleanest demonstration of biologically coherent representation learning at this resolution.
### Apical Accumulation and Terminal Regions (Clusters 0, 1) ### Precursor Compartmentalization (Clusters 0, 3, 4)
Two clusters are defined by a primary spatial association with the apical region of the leaf, characterized by highly localized ion intensity at the distal tip. Cluster 0 displays large, well-defined islands concentrated near the apex, housing 193 ions including tropinone (*m/z* 140.17), suggesting specialized sequestration zones proximal to the terminal region. This pattern may reflect the localized accumulation of defense-related compounds at the leaf apex, a common strategy in plant chemical defense against herbivores that first encounter the leaf tip. Cluster 1 exhibits the most spatially restricted pattern among all clusters, with a highly defined signal concentrated exclusively at the distal tip, comprising 141 ions. This pure apical distribution represents the terminal accumulation of specific metabolites, potentially corresponding to the final deposition of tropane alkaloids following acropetal transport through the vascular system. The clear delineation of these two apical clusters suggests a hierarchical organization within the terminal accumulation zone, with Cluster 1 representing the extreme tip and Cluster 0 capturing the broader peri-apical sequestration domain. The biosynthetic precursors occupy three distinct domains, revealing that the pathway intermediates are not uniformly mixed with the final alkaloids in the leaf. Tropinone (*m/z* 140.17), the first committed intermediate of tropane alkaloid biosynthesis, defines Cluster 0 (295 ions) with a vascular-apical signature, consistent with transport toward the terminal accumulation zone. Tropine (*m/z* 142.08), the immediate reduction product of tropinone, defines Cluster 3 (342 ions) with a broad parenchymal distribution, reflecting its role as the substrate for esterification with phenylpropanoid-derived acids. Cuscohygrine (*m/z* 225.92), which shares an early biosynthetic precursor (N-methyl-$\Delta^1$-pyrrolinium) with tropinone, defines Cluster 4 (226 ions) with a distinct vascular-associated distribution and laminar islands. The separation of tropinone, tropine, and cuscohygrine into three different domains — while the downstream alkaloids co-cluster in one — demonstrates that the encoder resolves spatial heterogeneity at the level of individual pathway intermediates, providing a spatially resolved map of alkaloid metabolism in the leaf.
### Vascular-Parenchymal Distributions (Clusters 2, 7, 9) ### Diffuse Laminar Domain (Cluster 1)
Three clusters are characterized by broad spatial distributions that span the entire leaf surface, reflecting compounds actively transported through the vascular system and distributed across the parenchyma. Cluster 2 exhibits a uniform pattern across the leaf surface with 137 ions spanning m/z 70.33 to 306.33, including 6-hydroxyhyoscyamine (*m/z* 306.25) and a scopolamine adjacent bin (*m/z* 304.33), consistent with the distribution of compounds transported acropetally and distributed throughout the leaf mesophyll. Cluster 7 is dominated by large, well-defined islands distributed across the lamina, comprising 159 ions including scopolamine (*m/z* 304.00) and atropine (*m/z* 290.08), demonstrating that the encoder correctly co-localizes these biosynthetically related tropane alkaloids within the same metabolic domain. The island-like pattern within a broad distribution suggests localized zones of metabolic specialization or differential accumulation following vascular transport. Cluster 9 displays a heterogeneous pattern combining both large and small islands across the leaf surface with moderate enrichment at the tip, representing the most complex distribution among the vascular-parenchymal group with 211 ions, including tropine (*m/z* 142.08). Cluster 1 is the largest domain (355 ions, *m/z* 59.67--279.25) and contains no tropane alkaloid markers. It comprises low-mass, broadly distributed ions spanning the diffuse laminar signal, representing the general metabolite background of the mesophyll. Its separation from the alkaloid-bearing clusters confirms that the segmentation reflects metabolic specialization rather than trivial tissue-vs-background partitioning.
The spatial distribution of key tropane alkaloids reveals distinct but complementary anatomical patterns that reflect their biosynthetic relationships and functional roles. Scopolamine (*m/z* 304.00) and Atropine (*m/z* 290.08), both assigned to Cluster 7, exhibit a co-localized midrib and laminar island distribution, consistent with their shared biosynthetic pathway. Cuscohygrine (*m/z* 225.92), in Cluster 3, displays a striking vascular architecture from primary to secondary veins extending from the petiole to the leaf tip. 6-Hydroxyhyoscyamine (*m/z* 306.25), in Cluster 2, follows a vascular distribution throughout the leaf. Tropine (*m/z* 142.08) in Cluster 9 shows broad parenchymal distribution as a key biosynthetic precursor of tropane alkaloids. Tropinone (*m/z* 140.17), assigned to Cluster 0, shows vascular-apical distribution essential for downstream alkaloid synthesis. The co-localization of scopolamine and atropine within Cluster 7 (cosine similarity 0.9863), alongside the distinct vascular assignments of cuscohygrine (Cluster 3), tropine (Cluster 9), and tropinone (Cluster 0), demonstrates that the self-supervised encoder successfully discriminates between subtle variations in spatial topography while capturing genuine biosynthetic and metabolic relationships. The spatial organization of the tropane alkaloid pathway in the leaf can therefore be summarized as: tropinone (Cluster 0) and cuscohygrine (Cluster 4) in vascular-associated domains, tropine (Cluster 3) in the parenchyma, and the accumulated end products — scopolamine, atropine/hyoscyamine, and 6-hydroxyhyoscyamine — merged in a single transport domain (Cluster 2), with a diffuse laminar background (Cluster 1). This five-domain architecture is a direct, unsupervised readout of the well-established spatial biology of tropane alkaloids: root-synthesized precursors are transported acropetally and compartmentalized as they progress through the biosynthetic pathway [@ziegler_alkaloid_2008; @schlesinger_tropane_2021].
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{Figure-carpet.png}
\caption{Ion carpet of the \textit{Datura innoxia} leaf: the complete set of 1,596 ion images of the dataset (one per ion, at native $256\times 256$ resolution) tiled into a single mosaic rendered in viridis with the Julia preprocessing stage's native \texttt{ViridisPalette}. Because every ion of the dataset appears in the carpet, it serves as a full visual index of the MSI dataset: each tile can be located by grid position and mapped back to its \textit{m/z} via the sorted ion manifest produced by Stage 1. The carpet is one of the exploration artifacts generated by the standalone ion-carpet exporter that follows the pipeline (Section \ref{sec:pipeline}), allowing direct visual comparison of the spatial morphology of arbitrary ions.}
\label{fig:carpet}
\end{figure}
### Root Case Study: Biosynthetic Site (k = 6)
The pipeline was applied identically to the *Datura innoxia* root dataset (2.5 GB, 21,060 pixels, 1,218 ion images). The same multi-metric sweep (k = 2--20) was applied, and under the same Davies-Bouldin-driven selection criterion used for the leaf it selects k = 6 (Davies-Bouldin optimum 0.8430 at k = 6; at this k the Calinski-Harabasz Index is 988.87 and the Silhouette Score is 0.5591), confirming that the root's metabolic architecture is distinct from the leaf's. The root segmentation places the tropane alkaloid biosynthetic machinery at its source: tropinone (*m/z* 140.17), tropine (*m/z* 142.08), cuscohygrine (*m/z* 225.92), and atropine/hyoscyamine (*m/z* 290.08) are all co-localized in a single domain, Cluster 1 (289 ions). Notably, no scopolamine signal (*m/z* 304.17) is detected in the root dataset, which is consistent with the classical model in which scopolamine is produced in the root but accumulates distally in the shoot [@schlesinger_tropane_2021]: the root is the biosynthetic site where the pathway intermediates and atropine/hyoscyamine co-reside, whereas the leaf is the accumulation site where the mature alkaloid mixture is transported.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.85\textwidth]{Figure-root-tsne.png}
\caption{t-SNE projection of the SimCLR latent space for the \textit{Datura innoxia} root (k=6), colored by cluster assignment. The tropane alkaloid biosynthetic intermediates and atropine/hyoscyamine co-localize in a single domain (Cluster 1), while no scopolamine signal is detected in the root.}
\label{fig:root_tsne}
\end{figure}
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{Figure-carpet-root.png}
\caption{Ion carpet of the \textit{Datura innoxia} root: the complete set of 1,218 ion images of the dataset (one per ion, at native $256\times 256$ resolution) tiled into a single mosaic rendered in viridis with the Julia preprocessing stage's native \texttt{ViridisPalette}. As for the leaf, every ion of the dataset appears in the carpet, providing a full visual index in which any tile can be mapped back to its \textit{m/z} via the sorted ion manifest produced by Stage 1.}
\label{fig:carpet_root}
\end{figure}
Quantitatively, the root recapitulates the same validation signature as the leaf. The SimCLR embeddings outperform a PCA baseline on all three metrics (Silhouette 0.4236 vs 0.2969; Davies-Bouldin 0.8430 vs 1.1723; Calinski-Harabasz 988.87 vs 805.31), and the segmentation is highly stable across seeds (mean Silhouette 0.4235 $\pm$ 0.0001; Adjusted Rand Index 0.9962). Isotope co-localization is positive (943 isotopic pairs; mean latent distance 0.6422 for isotopes vs 0.6669 for random pairs, Welch's t-test $p = 0.027$), although the effect is weaker than in the leaf, consistent with the root's more homogeneous biosynthetic metabolism. The root result demonstrates that the workflow generalizes across tissues without any parameter change: the same Julia preprocessing, the same SimCLR encoder, and the same K-selection logic produce a biologically coherent segmentation of a second, independent *Datura* tissue.
## Advantages of Contrastive Learning over Linear Decomposition ## 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 (k = 10). Under these conditions, the SimCLR pipeline achieved a Silhouette Score of 0.3496, compared to the PCA baseline of 0.1476, while the Calinski-Harabasz Index rose from 248.26 to 1212.54. The Davies-Bouldin Index for SimCLR was 0.9389 versus 1.5962 for PCA, confirming that the combination of contrastive feature learning produces massive improvements in spatial separation. Furthermore, the SimCLR embeddings exhibited exceptional stability across multiple random seeds, with a mean Silhouette Score of 0.3499 $\pm$ 0.0006 and an Adjusted Rand Index (ARI) of 0.9351 between runs, indicating that the learned representations are highly reproducible and independent of stochastic initialization. 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 = 6 (Silhouette 0.4236 vs 0.2969; Davies-Bouldin 0.8430 vs 1.1723; Calinski-Harabasz 988.87 vs 805.31; mean Silhouette 0.4235 $\pm$ 0.0001; ARI 0.9962), 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. 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.
# Data and Code Availability # Data and Code Availability
The complete hybrid Julia-Python workflow, including the Julia preprocessing scripts, Python training and evaluation scripts, and pre-trained encoder weights, is available under the MIT License at https://github.com/anomalyco/msi-hybrid-workflow. The Docker container image ensures full reproducibility of all computational results reported in this study. 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, \texttt{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 # Conclusion
Our findings provide a spatial validation of tropane alkaloid biosynthesis and distribution in *Datura innoxia*, demonstrating that the vascular system acts as a specialized conduit for systemic chemical defense, while the parenchymal tissue serves as a storage site for these compounds. The non-uniform distribution of metabolites carries significant biological implications, revealing how plants compartmentalize chemical defense mechanisms across different tissue types. The equalized benchmark against Cardinal (R/Bioconductor) and MALDIquant (R) — three identical preprocessing steps on the same hardware across seven public datasets spanning 69 MB to 4.4 GB — shows that the Julia engine generates ion slices two orders of magnitude faster than Cardinal and uses lower peak resident memory (VmRSS) than Cardinal on five of the seven datasets, while completing the additional normalization and export steps within the same memory envelope. We report the per-stage timings transparently, including the dataset-dependent total wall-clock, which favors the Julia engine on the two smallest datasets and the R ecosystem on the largest samples. The workflow scales from commodity laptops to GPU-equipped workstations and is fully reproducible: 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.
The methodology presented here establishes a new standard for spatial metabolomics. By combining self-supervised contrastive learning with a hybrid Julia-Python workflow that prioritizes anatomical fidelity, we enable the automated interpretation of complex biological systems without the need for manual annotation. This approach opens new avenues for studying the biosynthesis and transport of secondary metabolites in plants, with potential applications in crop improvement, pharmaceutical development, and ecological research. With all code and data available under the MIT License, this work offers a robust and reproducible framework for the democratization of advanced MSI analysis in plant science and beyond. As a demonstration of biological utility, application of the workflow to *Datura innoxia* recovered five spatially coherent metabolic domains in the leaf and six in the root. The segmentation resolves the spatial organization of tropane alkaloid metabolism without manual annotation: the biosynthetic intermediates and atropine/hyoscyamine co-localize in the root — the biosynthetic site, where no scopolamine is detected — while 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 containerized reproducibility, and the two-tissue biological case study 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 in plant science and beyond.