180 lines
42 KiB
Markdown
180 lines
42 KiB
Markdown
---
|
||
title: Anatomical mapping of alkaloids in plant tissues from mass spectrometry imaging data using a deep neuronal network segmentation
|
||
bibliography: zotero.bib
|
||
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.
|
||
keywords: mass spectrometry imaging, Julia language, deep learning, SimCLR, contrastive learning, group normalization, Datura innoxia, spatial metabolomics
|
||
---
|
||
|
||
# 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].
|
||
|
||
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.
|
||
|
||
# Materials and Methods
|
||
|
||
## MSI Data Acquisition (LD-LTP-MSI)
|
||
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.
|
||
|
||
## 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.
|
||
|
||
## High-Performance Processing and Data Normalization (Julia)
|
||
We conducted the preprocessing stage using the JuliaMSI framework [@sierra-alvarez_juliamsi_2025], a platform specifically engineered to address the computational bottlenecks 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.
|
||
|
||
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.
|
||
|
||
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:
|
||
|
||
$$T = P_{98}(V)$$
|
||
|
||
In cases where the distribution is extremely sparse and $P_{98} = 0$, the threshold defaults to the maximum observed intensity ($T =\max(V)$). Each pixel's intensity is then normalized and bounded to the unit interval $[0, 1]$ using a clamping function:
|
||
|
||
$$I_{norm}(x, y) = \min\left(1, \frac{I_{raw}(x, y)}{T}\right)$$
|
||
|
||
This transformation ensures that 98% of the chemical signal is represented within a standardized dynamic range, effectively enhancing the contrast of parenchymal and vascular structures. By suppressing the influence of extreme outliers, TrIQ provides a morphologically consistent input for the subsequent contrastive learning phase, preventing the neural network from over-fitting to instrumental artifacts.
|
||
|
||
Spatial Standardization (Pristine Coordinate Mapping): To ensure compatibility with the deep learning backbone, each normalized ion map was spatially embedded into a standardized 256 $\times$ 256 pixel matrix using strict Zero-Padding, completely avoiding any sub-pixel interpolation. In MSI, the physical laser ablation grid 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).
|
||
|
||
\begin{figure}[htbp]
|
||
\centering
|
||
\includegraphics[width=\textwidth]{Figure-benchmark.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.}
|
||
\label{fig:benchmark}
|
||
\end{figure}
|
||
|
||
## 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.
|
||
|
||
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).
|
||
|
||
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.
|
||
|
||
\begin{table}[htbp]
|
||
\centering
|
||
\caption{Training hyperparameters and model configuration for the SimCLR-MSI workflow.}
|
||
\label{tab:training_hyperparameters}
|
||
\begin{tabular}{lp{8cm}}
|
||
\toprule
|
||
Parameter & Value / Configuration \\ \midrule
|
||
|
||
Backbone Architecture & Custom 4-Layer CNN with Group Normalization \\
|
||
Projection Head & 2-layer MLP (Linear 256-ReLU-Linear 128) \\
|
||
Input Image Resolution & 256 \texttimes 256 pixels (Zero-Padded) \\
|
||
Optimization Algorithm & AdamW Optimizer \\
|
||
Learning Rate & $3 \times 10^{-4}$ with Cosine Annealing \\
|
||
Physical Batch Size / Accumulation Steps & 8 / 4 (Effective Batch Size: 32) \\
|
||
Temperature ($\tau$) & 0.5 (NT-Xent Loss) \\
|
||
Training Duration & 60 Epochs \\
|
||
Data Augmentations & Intensity Scaling (0.8\texttimes–1.2\texttimes), Poisson Shot Noise, Low-Signal Dropout \\
|
||
\bottomrule
|
||
\end{tabular}
|
||
\end{table}
|
||
|
||
Dataset Size and the Dynamic Training Pool: The training corpus comprises 1,596 ion images that passed the 2% intensity threshold filter and ROI mask selection from the original spectral binning. This number is mathematically sufficient for this self-supervised task for two compounding reasons. First, the custom 4-layer fully convolutional architecture is a lightweight, low-dimensional feature extractor. Unlike overparameterized ImageNet backbones such as EfficientNet-B0 [@tan_efficientnet_2019] (which carry over 5 million parameters trained for 1,000 natural image categories), our encoder is purpose-built to extract a compact morphological fingerprint; it requires far fewer samples to converge on a meaningful manifold. Second, the `apply_msi_chemical_noise` augmentation pipeline functions as a stochastic, infinite data generator. Because intensity scaling factors, Poisson noise seeds, and dropout masks are sampled randomly at each epoch, the network never encounters the exact same image representation twice, exponentially expanding the effective training pool and providing robust protection against overfitting.
|
||
|
||
The Camp A Paradigm: Prohibition of Spatial Augmentations: Standard computer vision augmentation libraries (e.g., Torchvision) apply spatial transformations—random rotations, horizontal/vertical flips, and random crops—as a default strategy to promote translation and rotation invariance. This practice is explicitly and deliberately incompatible with our co-localization objective and was therefore completely prohibited. In spatial metabolomics, the absolute $(x, y)$ pixel grid of a single-slice acquisition is the immutable biological ground truth [@alexandrov_maldi_2012]. Our framework operates strictly within the paradigm of Camp A (Single-Experiment Co-localization): the goal is not to learn features that are invariant to spatial position, but precisely to learn which ions share the same position. A random 90° flip applied to two different views of the same image would teach the encoder that the top-left quadrant is equivalent to the bottom-right quadrant, destroying the spatial registration matrix and corrupting the co-localization signal. The exclusive use of chemical noise augmentations (which simulate detector artifacts while leaving the coordinate grid untouched) is therefore a deliberate, foundational design choice, consistent with established best practices in MSI deep learning [@hu_deepion_2021].
|
||
|
||
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*.
|
||
|
||
# Results and Discussion
|
||
|
||
\begin{figure}[p]
|
||
\centering
|
||
\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.}
|
||
\label{fig:clustering}
|
||
\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.
|
||
|
||
## 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.
|
||
|
||
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.08) with a similarity of 0.9067. 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.08) 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 similarity of 0.9067 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.
|
||
|
||
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.
|
||
|
||
\begin{table}[htbp]
|
||
\centering
|
||
\caption{Representative metabolites identified in \textit{Datura innoxia} and their latent space assignment.}
|
||
\label{tab:metabolites}
|
||
\begin{tabular}{ccclp{6cm}}
|
||
\toprule
|
||
\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.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. \\
|
||
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. \\
|
||
225.92 & Cuscohygrine & $C_{13}H_{25}N_2O$ & 3 & Vascular architecture extending from petiole to leaf tip with laminar islands. \\
|
||
306.25 & 6-Hydroxyhyoscyamine & $C_{17}H_{24}NO_4$ & 2 & Vascular distribution throughout the leaf. \\
|
||
142.08 & Tropine / Pseudotropine & $C_8H_{16}NO$ & 9 & Broad 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. \\
|
||
\bottomrule
|
||
\end{tabular}
|
||
\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.
|
||
|
||
## Chemical-Anatomical Segmentation in *Datura innoxia*
|
||
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.
|
||
|
||
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).
|
||
|
||
\begin{figure}[htbp]
|
||
\centering
|
||
\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.}
|
||
\label{fig:tsne_clusters}
|
||
\end{figure}
|
||
|
||
\begin{table}[htbp]
|
||
\centering
|
||
\caption{Summary of unsupervised segmentation domains in \textit{Datura innoxia} leaf.}
|
||
\label{tab:summary_segmentation}
|
||
\begin{tabular}{p{2cm}lp{4cm}p{7cm}}
|
||
\toprule
|
||
Domain Group & Clusters & Spatial Pattern & 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. \\
|
||
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. \\
|
||
Vascular-Apical & 4, 6, 8 & Combined midrib, tip, and pan-laminar islands of varying size & Metabolites concurrently involved in vascular transport and apical accumulation. \\
|
||
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. \\
|
||
\bottomrule
|
||
\end{tabular}
|
||
\end{table}
|
||
|
||
### Vascular and Midrib-Associated Domains (Clusters 3, 4, 5, 6, 8)
|
||
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.
|
||
|
||
### Apical Accumulation and Terminal Regions (Clusters 0, 1)
|
||
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.
|
||
|
||
### Vascular-Parenchymal Distributions (Clusters 2, 7, 9)
|
||
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).
|
||
|
||
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.
|
||
|
||
## 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.3225, compared to the PCA baseline of 0.1476, while the Calinski-Harabasz Index rose from 248.26 to 1231.21. The Davies-Bouldin Index for SimCLR was 0.9362 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.3226 $\pm$ 0.0003 and an Adjusted Rand Index (ARI) of 0.9324 between runs, indicating that the learned representations are highly reproducible and independent of stochastic initialization.
|
||
|
||
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
|
||
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.
|
||
|
||
# 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 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.
|