Files
MSI_Julia_CNN_Release/MSI_Toloache_Paper_English.md
T

125 lines
23 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Deep Learning in Mass Spectrometry Imaging: A Hybrid Julia-Python Workflow for the Automated Anatomical Mapping of *Datura innoxia*
**Authors:** Carlos Daniel Sierra Álvarez, Juan Francisco Moreno Luna, José Jovani Martínez, José Julián Sierra Álvarez.
**Affiliation:** Advanced Genomics Unit, Cinvestav, km 9.6 Libr. Nte. Irapuato-León, Irapuato, 36824, Gto., Mexico.
**Keywords:** MSI, Julia Language, Deep Learning, SimCLR, EfficientNet-B0, *Datura innoxia*, Spatial Metabolomics.
---
## Abstract
Mass Spectrometry Imaging (MSI) has emerged as a fundamental tool in spatial metabolomics, enabling the *in situ* visualization of molecular distributions. However, the nature of these data—characterized by massive volumes of multivariate information and high levels of instrumental noise—poses critical challenges for traditional analysis methods. In this work, we present an innovative computational architecture that addresses the "two-language problem" by integrating **Julia** for high-performance data processing and **Python** for representation learning via deep neural networks. We implemented a self-supervised learning workflow based on the **SimCLR** architecture with an **EfficientNet-B0** encoder, designed to extract robust morphological features from ion images without prior labeling. This system was applied to the study of *Datura innoxia* (toloache) leaves at a spatial resolution of 150 µm, achieved via Laser Desorption Low-Temperature Plasma (LD-LTP) ionization. By prioritizing anatomical fidelity over mathematical parsimony, we identified an optimal clustering of $k=10$ that accurately distinguishes vascular, paravascular, and parenchymal tissues. Our results demonstrate that the latent space generated by the neural network captures fundamental chemical relationships, such as the co-localization of isotopic patterns, offering a scalable and objective pathway for the interpretation of complex biological systems.
---
## 1. Introduction
The analysis of the spatial distribution of secondary metabolites in medicinal plants is essential for understanding biosynthesis, transport, and chemical defense processes (Ziegler & Facchini, 2008). *D. 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 et al., 2021). Previous studies have employed laser desorption low-temperature plasma (LD-LTP) techniques to map these alkaloids in fruits and seeds (Moreno-Pedraza et al., 2019).
Traditionally, MSI data analysis has relied on linear methods and standard imaging protocols (Cole & Clench, 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 et al., 2012) is limited. Conversely, Julia offers execution speeds comparable to C++, making it ideal for processing high-dimensional matrices in MSI, demonstrating speeds up to 200 times faster than R in data reading tasks (Rosas-Román et al., 2024). In this article, we propose that the synergy between these two languages enables a "next-generation" MSI workflow.
---
## 2. Methodology
### 2.1 MSI Data Acquisition (LD-LTP-MSI)
Imaging was performed 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 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. The laser was oriented at 90° to the sample surface at a focal distance of 9 cm, producing a spot size of ~22 µm. Data were acquired in positive ion mode (*m/z* 50–700) with a spatial resolution of **150 µm** for the leaf samples.
### 2.2 Computational Environment
All computational analyses, including the high-performance data extraction in Julia and the deep learning-based representation learning in Python, were performed on a mobile workstation with the following specifications: **Processor:** Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz (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).
### 2.3 High-Performance Processing and Data Normalization (Julia)
The preprocessing stage was conducted using the **JuliaMSI** framework (Sierra-Álvarez et al., 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-Álvarez et al., 2025), this architecture provides a significant performance advantage over interpreted environments such as Python or R, 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-Álvarez et al., 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-Román et al., 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.
1. **Ion Extraction and Filtering:** Mass slices were extracted from the `Leaf.imzML` dataset within the ***m/z* 50.0 to 700.0** range. This upper limit was selected because no significant signals were detected beyond this threshold using the LD-LTP-MSI technique for this specific sample, and its implementation allowed for a more computationally manageable dataset. To ensure the inclusion of only chemically relevant signals, peaks were filtered using an intensity threshold of 2% relative to the base peak of the average spectrum, resulting in a refined subset of ion images for downstream analysis.
2. **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-Román et al., 2024). 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.
3. **Spatial Standardization:** To ensure compatibility with the deep learning backbone, each normalized ion map was spatially resampled to a resolution of **224x224 pixels** using bilinear interpolation. This step standardizes the input geometry while maintaining the structural integrity of the leaf’s anatomical features, such as the vascular midrib and parenchymal regions (Hu et al., 2022).
### 2.4 Self-Supervised Representation Learning (Python)
We implemented a **Contrastive Learning (SimCLR)** scheme in PyTorch, following the methodology proposed by Hu et al. (2022).
1. **Model Architecture:** **EfficientNet-B0** was used as the backbone encoder. The final classification layer was removed and replaced with a two-layer MLP projection head to project the data into a 128-dimensional space.
2. **MSI-Specific Data Augmentations:** Stochastic transformations were applied to simulate experimental variability, including slight rotations, Gaussian blur, and the addition of additive Gaussian noise to bolster the model against detector background noise.
3. **Clustering and Optimization:** To determine the optimal number of clusters ($k$), we performed a systematic sweep from $k=3$ to $k=17$. While mathematical heuristics (Silhouette Score) suggested a lower $k$, we selected **$k=10$** as the functional optimum. This choice prioritized **anatomical fidelity**, allowing the model to resolve specialized features such as primary and secondary venation (nervatures) and discrete epidermal sequestration sites (island-like patterns).
---
## 3. Results and Discussion
### 3.1 Latent Space Geometry and Chemical Validation
The high-dimensional embeddings generated by the EfficientNet-B0 backbone were projected into a 2-D manifold using t-SNE (Fig.[1]). 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. [1]). 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. 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 adjacent coordinates within the same latent clusters. This clustering behavior demonstrates that the network successfully prioritized the underlying morphological fingerprints over stochastic instrumental noise or absolute intensity variations. Such coherence serves as a robust internal control, confirming that the learned representations are anchored in biological reality rather than technical artifacts. Furthermore, this **Chemical Coherence** extends beyond isotopes to include adducts and related fragments, suggesting that the model effectively deconvolutes the chemical complexity of the tissue into meaningful metabolic domains.
**Table 1. Representative metabolites identified in *D. innoxia* and their latent space assignment.**
| $m/z$ Obs. | Identification | Formula $[M+H]^+$ | Cluster | Anatomical Significance |
| :--- | :--- | :--- | :--- | :--- |
| 290.02 | Atropine / Hyoscyamine | $C_{17}H_{24}NO_3$ | **9** | Primary vascular transport (Midrib) |
| 304.00 | Scopolamine | $C_{17}H_{22}NO_4$ | **9** | Secondary vascular transport |
| 225.65 | Cuscohygrine | $C_{13}H_{25}N_2O$ | **9** | Alkaloid accumulation in veins |
| 306.28 | 6-Hydroxyhyoscyamine | $C_{17}H_{24}NO_4$ | **8** | Localized sequestration (Islands) |
| 142.09 | Tropine / Pseudotropine | $C_8H_{16}NO$ | **2** | Paravascular precursor distribution |
| 291.00 | *Atropine Isotope* | $[M+H+1]^+$ | **9** | Internal validation of Isotopic Coherence |
![[msi_tsne_corregido.png]]
**Figure 1. Visualizing metabolic specialization across anatomical zones of a _D. innoxia_ leaf using t-SNE.** This scatter plot displays the t-SNE dimensionality reduction of MSI data acquired from a leaf section at a spatial resolution of 150 µm. The original dataset of 588 *m/z* feature intensities was projected into a 2D space to visualize metabolic similarity. Ten distinct clusters are identified via automated segmentation of the co-localized ion images and are represented here by a qualitative color bar (right). Points of the same color indicate pixels with closely related metabolic signatures, corresponding to different anatomical regions within the leaf. The strong segregation between groups highlights a sharp molecular differentiation of metabolic functions across the tissue.
### 3.2 Chemical-Anatomical Segmentation in *D. 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 *D. 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.02$) 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 (Fig. [2], Table. [2]).
![[TSNE_figure.png]]
**Figure 2. t-SNE-based clustering reveals spatially resolved chemical domains in *D. innoxia* leaves (k = 10).** The t-distributed stochastic neighbor embedding (t-SNE) projection of MSI data separates the dataset into ten distinct clusters (Clusters 0–9), each corresponding to a reproducible spatial ion distribution pattern. Representative ion images (one per cluster) illustrate the characteristic spatial topology associated with each molecular domain. Clusters 9, 4, 2, 0, and 6 are primarily associated with the midrib and vascular architecture, showing varying degrees of continuity and intensity along the main vein and adjacent regions. Notably, Clusters 8 and 9 exhibit overlapping ion distributions along the midrib, with Cluster 9 displaying a continuous vascular signal and Cluster 8 presenting a more discontinuous, island-like pattern in the same region. Clusters 3, 5, and 7 are enriched toward the apical region, showing increased ion density at the distal tip combined with heterogeneous island-like distributions across the lamina. In contrast, Clusters 1 and 8 are characterized by discrete, spatially isolated ion islands distributed across the leaf surface, reflecting highly localized regions of signal intensity. A representative photograph of a *D. innoxia* leaf is included to provide anatomical reference for the spatial patterns observed in the MSI-derived clusters.
**Table 2. Summary of unsupervised segmentation domains in *D. innoxia* leaf.**
| Domain Group | Clusters | Spatial Pattern | Biological Interpretation |
| :--- | :--- | :--- | :--- |
| **Vascular** | 9, 4, 0 | Continuous midrib signal | Long-distance metabolic transport. |
| **Paravascular** | 2, 6 | Adjacent to main veins | Lateral transport and tissue loading. |
| **Apical** | 3, 5, 7 | High density at distal tip | Terminal accumulation of tropane alkaloids. |
| **Sequestration** | 1, 8 | Isolated "island" patterns | Specialized metabolic compartments. |
#### 3.2.1 Vascular and Midrib-Associated Domains (Clusters 9, 0, 2, 4, 6)
The clustering analysis reveals a group of domains strongly associated with the midrib and vascular architecture of the leaf. **Cluster 9** represents the most clearly defined vascular pattern, exhibiting a continuous and high-intensity signal along the midrib. Within this cluster, ions corresponding to atropine and scopolamine are readily distinguishable, indicating a strong co-localization of these compounds within this anatomical region. In addition to the midrib signal, Cluster 9 also includes smaller islands distributed throughout the lamina, suggesting a secondary spatial component characterized by localized ion enrichment outside the primary vein. **Cluster 4** maintains a clear midrib-associated signal but introduces larger and more defined metabolic islands across the leaf surface. This pattern indicates a broader spatial dispersion of ions while preserving a strong vascular signature. **Cluster 2** similarly combines vascular localization with medium-to-large islands, although with a more diffuse distribution compared to Cluster 4. The continuity of the midrib signal in this cluster is less pronounced, suggesting variability in ion intensity along the vascular axis. **Cluster 0** exhibits a weaker and more fragmented midrib presence, integrated with medium-sized islands distributed across the lamina. This pattern reflects a reduced dominance of vascular-associated signals relative to surrounding tissue. Finally, **Cluster 6** defines a distinct spatial configuration characterized by signals adjacent to the midrib (paravascular regions) as well as a broader distribution across the leaf surface. The lack of a strictly continuous midrib signal differentiates this cluster from the others in this group.
#### 3.2.2 Apical Accumulation and Terminal Regions (Clusters 3, 5, 7)
A second group of clusters is defined by a clear spatial association with the apical region of the leaf, characterized by increased ion intensity toward the distal tip. **Cluster 3** displays a distribution of small, discrete islands across the lamina, with a marked increase in density and intensity near the apex. This pattern suggests a spatial gradient in ion distribution, with enrichment toward the terminal region. **Cluster 5** presents a more heterogeneous distribution, combining both small and large islands with a pronounced concentration at the leaf tip. The coexistence of multiple island sizes indicates variability in local ion intensity and spatial aggregation. **Cluster 7** exhibits a multimodal distribution, integrating apical localization with small-to-medium islands distributed throughout the leaf and a minor presence along the midrib. This combination of features distinguishes it from clusters that are exclusively apical or vascular.
#### 3.2.3 Isolated Sequestration and Island-like Topographies (Clusters 1, 8)
Clusters 1 and 8 are characterized by highly discrete, island-like spatial patterns, representing localized regions of elevated ion intensity separated by areas of low signal. **Cluster 1** shows a relatively uniform distribution of small and medium-sized islands across the entire leaf surface. The regularity of this pattern suggests a widespread but compartmentalized presence of ions, without a clear association to major anatomical structures such as the midrib or apex. In contrast, **Cluster 8** exhibits highly defined and isolated islands with sharp spatial boundaries. These regions are surrounded by areas with minimal signal, resulting in a high-contrast spatial pattern. Additionally, this cluster shows detectable signals along the midrib and a slight presence at the apical tip, indicating overlap with other spatial domains. Additionally, **Clusters 8 and 9** share notable similarities in their spatial ion distribution along the midrib. While Cluster 9 exhibits a continuous and well-defined vascular signal, Cluster 8 also shows a detectable presence in the same anatomical region, albeit in a more discontinuous and island-like manner. This partial overlap suggests that both clusters capture ion populations associated with the midrib, differing primarily in spatial continuity and intensity rather than anatomical localization.
#### 3.3 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. 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 SimCLR-EfficientNet 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.
---
## 4. Conclusion
The integration of a hybrid Julia-Python pipeline (Sierra-Álvarez et al., 2025; Rosas-Román et al., 2024) represents a significant advancement in the democratization of advanced MSI analysis. While Julia overcomes performance barriers in massive data ingestion, contrastive learning in Python enables objective and automated biological interpretation. This approach establishes a standard for spatial metabolomics studies where tissue complexity exceeds manual analysis capacity.
---
## 5. References
* **Cole, L. M., & Clench, M. R. (Eds.). (2023).** *Imaging Mass Spectrometry: Methods and Protocols*. Springer US. https://doi.org/10.1007/978-1-0716-3319-9
* **García-Rojas, N. S., Sierra-Álvarez, C. D., et al. (2024).** Identification of Plant Compounds with Mass Spectrometry Imaging (MSI). *Metabolites*, 14(8), 419. https://doi.org/10.3390/metabo14080419
* **Hu, H., Bindu, J. P., & Laskin, J. (2022).** Self-supervised clustering of mass spectrometry imaging data using contrastive learning. *Chemical Science*, 13(1), 90–98. https://doi.org/10.1039/d1sc04077d
* **Moreno-Pedraza, A., Rosas-Román, I., et al. (2019).** Elucidating the Distribution of Plant Metabolites from Native Tissues with Laser Desorption Low-Temperature Plasma Mass Spectrometry Imaging. *Analytical Chemistry*, 91(4), 2734–2743. https://doi.org/10.1021/acs.analchem.8b04406
* **Rosas-Román, I., Guillén-Alonso, H., et al. (2024).** Technical Note: mzML and imzML Libraries for Processing Mass Spectrometry Data with the High-Performance Programming Language Julia. *Analytical Chemistry*, 96(10), 3999–4004. https://doi.org/10.1021/acs.analchem.3c05853
* **Schlesinger, D., et al. (2021).** Tropane alkaloid biosynthesis in Datura innoxia Mill. roots and their differential transport to shoots. *Phytochemistry Letters*, 43, 219–225. https://doi.org/10.1016/j.phytol.2021.04.012
* **Schramm, T., et al. (2012).** imzML — A common data format for the flexible exchange and processing of mass spectrometry imaging data. *Journal of Proteomics*, 75(16), 5106–5110. https://doi.org/10.1016/j.jprot.2012.07.026
* **Sierra-Álvarez, J. J., ..., Sierra-Álvarez, C. D., et al. (2025).** JuliaMSI: A high-performance graphical platform for mass spectrometry imaging data analysis. *Analytica Chimica Acta*, 1377, 344613. https://doi.org/10.1016/j.aca.2025.344613
* **Ziegler, J., & Facchini, P. J. (2008).** Alkaloid Biosynthesis: Metabolism and Trafficking. *Annual Review of Plant Biology*, 59(1), 735–769. https://doi.org/10.1146/annurev.arplant.59.032607.092730