finished CNN validations and cluster verification, cleaned repo of tests

This commit is contained in:
Pixelguy14
2026-06-04 14:31:55 -06:00
parent d98cfccb5f
commit 237bad0189
47 changed files with 991 additions and 796 deletions
+58 -21
View File
@@ -2,19 +2,19 @@
**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.
**Keywords:** MSI, Julia Language, Deep Learning, SimCLR, Contrastive Learning, Group Normalization, *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.
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 computational challenges for traditional analysis methods (Shah et al., 2025). 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 a **custom Group-Normalized Fully Convolutional** 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.
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 often limited. Conversely, Julia offers execution speeds comparable to C++ for compute-heavy tasks (Godoy et al., 2023) and outperforms interpreted languages in scientific computing benchmarks (Churavy et al., 2020). 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 (Perkel, 2019). In this article, we propose that the synergy between these two languages enables a "next-generation" MSI workflow.
---
@@ -23,8 +23,8 @@ Traditionally, MSI data analysis has relied on linear methods and standard imagi
### 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 (Martínez-Jarquín & Winkler, 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. 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.2 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.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). 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 et al., 2018) and SMART (Xi et al., 2023), as well as modern machine learning reproducibility guidelines like REFORMS (Kapoor et al., 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.
### 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 (Rosas-Román et al., 2020), enabling the high-throughput extraction of mass slices without compromising spectral precision.
@@ -33,7 +33,7 @@ The selection of Julia as the primary engine for data ingestion is justified by
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:
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 & Winkler, 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)$$
@@ -43,33 +43,40 @@ $$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).
3. **Spatial Standardization (Pristine Coordinate Mapping):** To ensure compatibility with the deep learning backbone, each normalized ion map was spatially embedded into a standardized **256x256 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. As a demonstration of this high-throughput pipeline, the Julia engine parsed the raw `.ibd` binaries, applied TrIQ, and exported 588 padded individual ion slices in under 16 seconds.
### 2.4 Self-Supervised Representation Learning (Python)
We implemented a Contrastive Learning (SimCLR) scheme in PyTorch (Chen, T., et al., 2020), following the methodology proposed by Hu et al. (2022).
We implemented a Contrastive Learning (SimCLR) scheme in PyTorch (Paszke et al., 2019), adapting the framework to the unique properties of mass spectrometry imaging.
1. **Model Architecture:** **EfficientNet-B0** was used as the backbone encoder (Tan, M., & Le, Q., 2019). The final classification layer was removed and replaced with a two-layer MLP projection head to project the data into a 128-dimensional space (Table. [1]) (Kingma, D. P., & Ba, J., 2014).
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 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 (Hugging Face, 2025). This is mathematically equivalent to training with a true batch size of 32 while using only a quarter of the VRAM.
**Table 1. Training hyperparameters and model configuration for the SimCLR-MSI workflow.**
| Parameter | Value / Configuration |
| :--- | :--- |
| **Backbone Architecture** | EfficientNet-B0 (Pre-trained on ImageNet) |
| **Backbone Architecture** | Custom 4-Layer CNN with Group Normalization |
| **Projection Head** | 2-layer MLP (Linear 512-ReLU-Linear 128) |
| **Input Image Resolution** | 224 x 224 pixels |
| **Input Image Resolution** | 256 x 256 pixels (Zero-Padded) |
| **Optimization Algorithm** | Adam Optimizer |
| **Learning Rate** | $3 \times 10^{-4}$ |
| **Batch Size** | 32 |
| **Physical Batch Size / Accumulation Steps** | 8 / 4 (Effective Batch Size: 32) |
| **Temperature ($\tau$)** | 0.5 (NT-Xent Loss) |
| **Training Duration** | 50 Epochs |
| **Data Augmentations** | Random Rotation (10°), Gaussian Blur, Color Jitter, and Additive Gaussian Noise ($\sigma=0.01$) |
| **Training Duration** | 60 Epochs |
| **Data Augmentations** | Intensity Scaling (0.8×–1.2×), Poisson Shot Noise, Low-Signal Dropout |
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 multi-metric systematic sweep from $k=2$ to $k=20$ (Fig. [1(A)]). While global mathematical optima were observed at $k=2$ and $k=3$ —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.3526 (Fig. [1(B)]), a Davies-Bouldin Index of 0.9632 (Fig. [1(C)]), and a Calinski-Harabasz Index of 709.17 (Fig. [1(D)]). 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 *D. innoxia*.
2. **Dataset Size and the Dynamic Training Pool:** The training corpus comprises 588 ion images that passed the 2% intensity threshold filter 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 (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.
3. **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, 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 et al., 2021).
4. **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 et al., 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.
5. **Clustering and Optimization:** To determine the optimal number of clusters ($k$), we performed a multi-metric systematic sweep from $k=2$ to $k=20$ (Fig. [1(A)]). While global mathematical optima were observed at $k=2$ and $k=3$—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.6894 (Fig. [1(B)]), a Davies-Bouldin Index of 0.6243 (Fig. [1(C)]), and a Calinski-Harabasz Index of 2054.20 (Fig. [1(D)]). 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 *D. innoxia*.
![[cluster_validation_detailed_plot.png]]
**Figure 1. Quantitative validation of the clustering architecture for MSI representation learning.** To ensure the objectivity of the anatomical mapping, four independent clustering metrics were evaluated across a range of $k$ values: (A) The Elbow Method (Inertia) illustrates the rate of variance reduction, showing a gradual stabilization beyond $k=8$. (B) The Silhouette Score indicates the internal cohesion of the clusters; although the global maximum occurs at $k=2$ (tissue vs. background), the score remains stable at $k=10$ (0.3526), confirming a well-defined structure in the latent manifold. (C) The Davies-Bouldin Index—where lower values indicate superior cluster separation—remains below the critical threshold of 1.0 for $k=10$ (0.9632), demonstrating distinct boundaries between metabolic domains. (D) The Calinski-Harabasz Index—where higher values indicate better dispersion—shows a robust score of 709.17 at the selected $k$. Collectively, these metrics justify the selection of $k=10$ as a balanced threshold that maximizes both mathematical stability and the resolution of specialized biological features, such as paravascular and apical accumulation zones.
**Figure 1. Quantitative validation of the clustering architecture for MSI representation learning.** To ensure the objectivity of the anatomical mapping, four independent clustering metrics were evaluated across a range of $k$ values using Spherical K-Means on the re-normalized hypersphere: (A) The Elbow Method (Inertia) illustrates the rate of variance reduction, showing a gradual stabilization beyond $k=8$. (B) The Silhouette Score indicates the internal cohesion of the clusters; although the global maximum occurs at $k=2$ (tissue vs. background), the score achieves 0.6894 at $k=10$, confirming a well-defined structure in the latent manifold. (C) The Davies-Bouldin Index—where lower values indicate superior cluster separation—achieves 0.6243 at $k=10$, well below the critical threshold of 1.0, demonstrating distinct boundaries between metabolic domains. (D) The Calinski-Harabasz Index—where higher values indicate better dispersion—shows a robust score of 2054.20 at the selected $k$. Collectively, these metrics justify the selection of $k=10$ as a balanced threshold that maximizes both mathematical stability and the resolution of specialized biological features, such as paravascular and apical accumulation zones.
---
@@ -82,7 +89,15 @@ Direct surface analysis of *D. innoxia* leaves was conducted using a Laser Desor
**Figure 2. Mirrored MS/MS spectra for the confirmation of scopolamine (*m/z* 304.17) acquired via LD-LTP-MS in positive ion mode.** The upper panel (blue) represents the fragmentation profile obtained directly from the leaf surface of *D. innoxia*, while the lower panel (red) shows the commercial reference standard. Data were acquired in profile mode and are presented as refined centroids after baseline subtraction. Both spectra were generated using collision-induced dissociation (CID) at 20 eV. The axes denote relative abundance (%) and the mass-to-charge ratio (*m/z*), respectively.
### 3.2 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.[3]) (Van der Maaten & Hinton., 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. 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.
The high-dimensional embeddings generated by the custom GroupNorm backbone were projected into a 2-D manifold using t-SNE (Fig.[3]) (Van der Maaten & Hinton, 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. For example, Atropine ($m/z$ 290.02) and its $+1$ Isotope ($m/z$ 291.00) yielded a Cosine Similarity of **$0.9898$**. A global statistical analysis across 513 discovered isotopic pairs yielded a mean latent distance of $0.3156$, compared to $0.7076$ for random ion pairs, achieving profound statistical significance (Welch's t-test, $p = 6.7932 \times 10^{-74}$). 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 & Gupta, 2020). Our data provides an elegant empirical refutation of this hypothesis. Atropine ($m/z$ 290.02) and its $+1$ isotope ($m/z$ 291.00) 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 et al., 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.9898$ 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.8796$ with Atropine) 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.
**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 et al., 2008). A *D. 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 et al., 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.
**Table 2. Representative metabolites identified in *D. innoxia* and their latent space assignment.**
@@ -102,7 +117,7 @@ The high-dimensional embeddings generated by the EfficientNet-B0 backbone were p
### 3.3 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. [4], 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.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. [4], Table 3).
![[TSNE_figure.png]]
@@ -120,7 +135,7 @@ Rather than reflecting random variation, the observed spatial arrangements defin
#### 3.3.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.
The molecular architecture revealed by Cluster 9 provides a high-resolution spatial confirmation of the systemic metabolic trafficking in D. innoxia. The concentrated localization of atropine ($m/z$ 290.02) and scopolamine ($m/z$ 304.0) within the midrib and primary vascular bundles reflects the physiological reality of tropane alkaloid biosynthesis. Given that these secondary metabolites are primarily synthesized in the root system and subsequently translocated to the aerial tissues via acropetal transport (Schlesinger et al., 2021), their high-density visualization within the xilematic tissue serves as a robust physiological anchor for our unsupervised model. This spatial distribution suggests that the vascular network does not merely act as a structural element but as a specialized high-speed conduit for the delivery of chemical defenses to the lamina. By capturing this transport-specific signature, the SimCLR-based segmentation moves beyond static mapping, effectively resolving the spatial footprints of the plant's long-distance transport mechanisms.
The molecular architecture revealed by Cluster 9 provides a high-resolution spatial confirmation of the systemic metabolic trafficking in D. innoxia. The concentrated localization of atropine ($m/z$ 290.02) and scopolamine ($m/z$ 304.0) within the midrib and primary vascular bundles reflects the physiological reality of tropane alkaloid biosynthesis. Given that these secondary metabolites are primarily synthesized in the root system and subsequently translocated to the aerial tissues via acropetal transport (Schlesinger et al., 2021), their high-density visualization within the xylem tissue serves as a robust physiological anchor for our unsupervised model. This spatial distribution suggests that the vascular network does not merely act as a structural element but as a specialized high-speed conduit for the delivery of chemical defenses to the lamina. By capturing this transport-specific signature, the SimCLR-based segmentation moves beyond static mapping, effectively resolving the spatial footprints of the plant's long-distance transport mechanisms.
#### 3.3.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.
@@ -129,7 +144,9 @@ A second group of clusters is defined by a clear spatial association with the ap
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.4 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.
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 et al., 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 Euclidean K-Means ($k=10$) without the Spherical K-Means re-normalization described in Section 2.4.4, ensuring a direct apples-to-apples comparison. Under these conditions, the SimCLR pipeline achieved a Silhouette Score of **0.508**, compared to the PCA baseline of 0.163, while the Calinski-Harabasz Index rose from 103.7 to **2147.4**. When the full optimized post-processing pipeline is applied (Spherical K-Means with $L_2$ re-normalization, as described in Section 2.4.4–2.4.5), the Silhouette Score further improves to **0.6894** with a Davies-Bouldin Index of **0.6243**, confirming that the combination of contrastive feature learning and geometrically correct clustering produces massive improvements in spatial separation.
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.
---
@@ -138,6 +155,8 @@ In this study, we successfully implemented a high-performance computational fram
Our findings provide a spatial validation of the acropetal transport of tropane alkaloids, demonstrating that the vascular system acts as a specialized conduit for systemic chemical defense. This methodology establishes a new standard for spatial metabolomics, where the prioritization of anatomical fidelity over mathematical parsimony enables the automated interpretation of complex biological systems without the need for manual annotation. Ultimately, the integration of high-performance data ingestion and representation learning offers a robust and objective path forward for the democratization of advanced MSI analysis in plant science and beyond.
**Data and Code Availability:** The complete hybrid Julia-Python workflow, including the Dockerfile, Julia preprocessing scripts, Python training and evaluation scripts, and pre-trained encoder weights, will be made available at https://git.nube-gran.de/Carlos/MSI_Julia_CNN/src/branch/main upon publication. The Docker container image ensures full reproducibility of all computational results reported in this study.
---
## References
@@ -147,14 +166,32 @@ Our findings provide a spatial validation of the acropetal transport of tropane
* García-Rojas, N. S., Sierra-Álvarez, C. D., Ramos-Aboites, H. E., Moreno-Pedraza, A., & Winkler, R. (2024). Identification of Plant Compounds with Mass Spectrometry Imaging (MSI). Metabolites, 14(8), 419. https://doi.org/10.3390/metabo14080419
* Harper, J. D., Charipar, N. A., Mulligan, C. C., Zhang, X., Cooks, R. G., & Ouyang, Z. (2008). Low-temperature plasma probe for ambient desorption ionization. Analytical Chemistry, 80(23), 9097–9104. https://doi.org/10.1021/ac801641a
* 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
* Hugging Face. (2025). Gradient Accumulation. Hugging Face Documentation. Available at: https://huggingface.co/docs/transformers/en/perf_train_gpu_one#gradient-accumulation
* Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. https://doi.org/10.48550/arXiv.1412.6980
* Martínez-Jarquín, S., & Winkler, R. (2017). Low-temperature plasma (LTP) jets for mass spectrometry (MS): Ion processes, instrumental set-ups, and application examples. Trends in Analytical Chemistry, 89, 133–145. https://doi.org/10.1016/j.trac.2017.01.013
* Moreno-Pedraza, A., Rosas-Román, I., García-Rojas, N. S., Guillén-Alonso, H., Ovando-Vázquez, C., Díaz-Ramírez, D., ... & Winkler, R. (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., Ovando-Vázquez, C., Moreno-Pedraza, A., Guillén-Alonso, H., & Winkler, R. (2020). Open LabBot and RmsiGUI: Community development kit for sampling automation and ambient imaging. Microchemical Journal, 152, 104343. https://doi.org/10.1016/j.microc.2019.104343
* Rosas-Román, I., Guillén-Alonso, H., Moreno-Pedraza, A., & Winkler, R. (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
* Shah, M., Liu, S., Guo, L., Zhang, Y., Deng, L., Xu, X., ... & Dong, J. (2025). MSInet: A Self-Supervised CNN Framework Integrating Global and Local Context for Robust Mass Spectrometry Imaging Segmentation. Analytical Chemistry, 97(46), 24697–24705. https://doi.org/10.1021/acs.analchem.5c04885
* Godoy, W. F., Valero-Lara, P., Dettling, T. E., Trefftz, C., Jorquera, I., Sheehy, T., ... & Churavy, V. (2023). Evaluating performance and portability of high-level programming models: Julia, Python/Numba, and Kokkos on exascale nodes. arXiv preprint arXiv:2303.06195.
* Churavy, V., Bezanson, J., & Edelman, A. (2020). Julia Micro-Benchmarks. JuliaLang.org. Available at: https://julialang.github.io/Microbenchmarks/dev/benchmarks/ (Accessed: June 2026).
* Perkel, J. M. (2019). Julia: Come for the syntax, stay for the speed. Nature, 572(7767), 141-142.
* Gustafsson, O. J. R., Winderbaum, L. J., & Powell, D. R. (2018). Balancing sufficiency and impact in reporting standards for mass spectrometry imaging experiments. GigaScience, 7(10), giy102. https://doi.org/10.1093/gigascience/giy102
* Xi, Y., Sohn, A. L., Joignant, A. N., Cologna, S. M., Prentice, B. M., & Muddiman, D. C. (2023). SMART: A data reporting standard for mass spectrometry imaging. Journal of Mass Spectrometry, 58(2), e4904. https://doi.org/10.1002/jms.4904
* Kapoor, S., et al. (2024). REFORMS: Consensus-based Recommendations for Machine-learning-based Science. Science Advances, 10(18), eadk3452. https://doi.org/10.1126/sciadv.adk3452
* Zhang, Y., Li, Z., Bhatt, P., & Bhattacharya, D. (2024). DeepION: A Deep Learning-Based Low-Dimensional Representation Model of Ion Images for Mass Spectrometry Imaging. Analytical Chemistry, 96(9), 3829–3836. https://doi.org/10.1021/acs.analchem.3c05002
* Rosas-Román, I., & Winkler, R. (2021). Contrast optimization of mass spectrometry imaging (MSI) data visualization by threshold intensity quantization (TrIQ). PeerJ Computer Science, 7, e585. https://doi.org/10.7717/peerj-cs.585
* Paszke, A., et al. (2019). PyTorch: An imperative style, high-performance deep learning library. Advances in Neural Information Processing Systems, 32.
* 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., Rosas-Román, I., García-Rojas, N. S., Moreno-Pedraza, A., & Sierra-Álvarez, C. D. (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
* Tan, M., & Le, Q. (2019). EfficientNet: Rethinking model scaling for convolutional neural networks. In Proceedings of the 36th International Conference on Machine Learning (pp. 6105–6114). PMLR. https://doi.org/10.48550/arXiv.1905.11946
* Van der Maaten, L., & Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research, 9(11), 2579–2605.
* 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
* Alexandrov, T. (2012). MALDI imaging mass spectrometry: statistical data analysis and current computational challenges. BMC Bioinformatics, 13(Suppl 16), S11. https://doi.org/10.1186/1471-2105-13-S16-S11
* Hu, B., Huang, Z., Wu, X., Shen, X., & Laskin, J. (2021). DeepION: Deep Learning-Based Ion Image Reconstruction for Mass Spectrometry Imaging. Analytical Chemistry, 93(27), 9945–9954. https://doi.org/10.1021/acs.analchem.1c00223
* Purushwalkam, S., & Gupta, A. (2020). Demystifying Contrastive Self-Supervised Learning: Invariances, Shortcuts and Geometries. Advances in Neural Information Processing Systems (NeurIPS), 33, 16903–16916.
* Diaconis, P., Goel, S., & Holmes, S. (2008). Horseshoes in multidimensional scaling and local kernel methods. The Annals of Applied Statistics, 2(3), 777–807. https://doi.org/10.1214/08-AOAS165
* Moon, K. R., van Dijk, D., Wang, Z., Gigante, S., Burkhardt, D. B., Chen, W. S., ... & Krishnaswamy, S. (2019). Visualizing structure and transitions in high-dimensional biological data. Nature Biotechnology, 37(12), 1482–1492. https://doi.org/10.1038/s41587-019-0336-3
* Hornik, K., Feinerer, I., Kober, M., & Buchta, C. (2012). Spherical k-Means Clustering. Journal of Statistical Software, 50(10), 1–22. https://doi.org/10.18637/jss.v050.i10
-11
View File
@@ -1,11 +0,0 @@
cluster_id,ion_count
0,112
1,20
2,91
3,118
4,19
5,27
6,36
7,33
8,16
9,116
1 cluster_id ion_count
2 0 112
3 1 20
4 2 91
5 3 118
6 4 19
7 5 27
8 6 36
9 7 33
10 8 16
11 9 116
+1
View File
@@ -7,3 +7,4 @@ matplotlib>=3.5.0
pandas>=1.4.0
scipy>=1.7.0
psutil>=5.9.0
plotly>=6.8.0

Before

Width:  |  Height:  |  Size: 161 KiB

After

Width:  |  Height:  |  Size: 161 KiB

Before

Width:  |  Height:  |  Size: 394 KiB

After

Width:  |  Height:  |  Size: 394 KiB

Before

Width:  |  Height:  |  Size: 359 KiB

After

Width:  |  Height:  |  Size: 359 KiB

Before

Width:  |  Height:  |  Size: 341 KiB

After

Width:  |  Height:  |  Size: 341 KiB

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 210 KiB

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Before

Width:  |  Height:  |  Size: 273 KiB

After

Width:  |  Height:  |  Size: 273 KiB

Before

Width:  |  Height:  |  Size: 349 KiB

After

Width:  |  Height:  |  Size: 349 KiB

Before

Width:  |  Height:  |  Size: 364 KiB

After

Width:  |  Height:  |  Size: 364 KiB

Before

Width:  |  Height:  |  Size: 363 KiB

After

Width:  |  Height:  |  Size: 363 KiB

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 128 KiB

Before

Width:  |  Height:  |  Size: 617 KiB

After

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 241 KiB

After

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

After

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 KiB

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 247 KiB

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

@@ -1,63 +0,0 @@
filename,mz,similarity
ion_304.0.png,304.0,0.9995666
ion_304.33.png,304.33,0.9995666
ion_120.31.png,120.31,0.9977955
ion_371.63.png,371.63,0.995764
ion_286.12.png,286.12,0.99534976
ion_261.09.png,261.09,0.99487245
ion_238.0.png,238.0,0.9945407
ion_335.21.png,335.21,0.99350333
ion_69.27.png,69.27,0.99221265
ion_186.31.png,186.31,0.99207246
ion_228.25.png,228.25,0.991964
ion_133.64.png,133.64,0.9919308
ion_227.92.png,227.92,0.9915842
ion_244.18.png,244.18,0.99153364
ion_239.95.png,239.95,0.99102235
ion_232.15.png,232.15,0.98982406
ion_97.23.png,97.23,0.9894692
ion_167.78.png,167.78,0.9894244
ion_355.05.png,355.05,0.98924905
ion_255.23.png,255.23,0.98897374
ion_196.71.png,196.71,0.988899
ion_229.88.png,229.88,0.9877535
ion_240.93.png,240.93,0.9871814
ion_105.68.png,105.68,0.98697543
ion_144.37.png,144.37,0.9862776
ion_256.21.png,256.21,0.9862302
ion_329.04.png,329.04,0.9860908
ion_391.14.png,391.14,0.98531795
ion_242.88.png,242.88,0.98493713
ion_169.73.png,169.73,0.9846555
ion_279.94.png,279.94,0.98348063
ion_124.54.png,124.54,0.98188335
ion_245.16.png,245.16,0.9808812
ion_194.76.png,194.76,0.98059267
ion_246.13.png,246.13,0.9799091
ion_144.69.png,144.69,0.97790337
ion_217.85.png,217.85,0.9767251
ion_225.97.png,225.97,0.97520435
ion_257.19.png,257.19,0.9733879
ion_234.1.png,234.1,0.9733616
ion_198.66.png,198.66,0.9730791
ion_104.7.png,104.7,0.971887
ion_214.27.png,214.27,0.9714562
ion_252.96.png,252.96,0.9714364
ion_249.06.png,249.06,0.9709189
ion_146.64.png,146.64,0.9706471
ion_81.62.png,81.62,0.97054136
ion_372.93.png,372.93,0.9699422
ion_269.21.png,269.21,0.96917
ion_263.04.png,263.04,0.96838164
ion_202.24.png,202.24,0.9664346
ion_205.82.png,205.82,0.9639652
ion_216.22.png,216.22,0.9632674
ion_222.72.png,222.72,0.9614939
ion_132.66.png,132.66,0.96099925
ion_174.28.png,174.28,0.96078146
ion_74.79.png,74.79,0.95929277
ion_251.01.png,251.01,0.9586576
ion_371.3.png,371.3,0.9537004
ion_230.2.png,230.2,0.95332444
ion_278.64.png,278.64,0.95315814
ion_180.78.png,180.78,0.95183814
1 filename mz similarity
2 ion_304.0.png 304.0 0.9995666
3 ion_304.33.png 304.33 0.9995666
4 ion_120.31.png 120.31 0.9977955
5 ion_371.63.png 371.63 0.995764
6 ion_286.12.png 286.12 0.99534976
7 ion_261.09.png 261.09 0.99487245
8 ion_238.0.png 238.0 0.9945407
9 ion_335.21.png 335.21 0.99350333
10 ion_69.27.png 69.27 0.99221265
11 ion_186.31.png 186.31 0.99207246
12 ion_228.25.png 228.25 0.991964
13 ion_133.64.png 133.64 0.9919308
14 ion_227.92.png 227.92 0.9915842
15 ion_244.18.png 244.18 0.99153364
16 ion_239.95.png 239.95 0.99102235
17 ion_232.15.png 232.15 0.98982406
18 ion_97.23.png 97.23 0.9894692
19 ion_167.78.png 167.78 0.9894244
20 ion_355.05.png 355.05 0.98924905
21 ion_255.23.png 255.23 0.98897374
22 ion_196.71.png 196.71 0.988899
23 ion_229.88.png 229.88 0.9877535
24 ion_240.93.png 240.93 0.9871814
25 ion_105.68.png 105.68 0.98697543
26 ion_144.37.png 144.37 0.9862776
27 ion_256.21.png 256.21 0.9862302
28 ion_329.04.png 329.04 0.9860908
29 ion_391.14.png 391.14 0.98531795
30 ion_242.88.png 242.88 0.98493713
31 ion_169.73.png 169.73 0.9846555
32 ion_279.94.png 279.94 0.98348063
33 ion_124.54.png 124.54 0.98188335
34 ion_245.16.png 245.16 0.9808812
35 ion_194.76.png 194.76 0.98059267
36 ion_246.13.png 246.13 0.9799091
37 ion_144.69.png 144.69 0.97790337
38 ion_217.85.png 217.85 0.9767251
39 ion_225.97.png 225.97 0.97520435
40 ion_257.19.png 257.19 0.9733879
41 ion_234.1.png 234.1 0.9733616
42 ion_198.66.png 198.66 0.9730791
43 ion_104.7.png 104.7 0.971887
44 ion_214.27.png 214.27 0.9714562
45 ion_252.96.png 252.96 0.9714364
46 ion_249.06.png 249.06 0.9709189
47 ion_146.64.png 146.64 0.9706471
48 ion_81.62.png 81.62 0.97054136
49 ion_372.93.png 372.93 0.9699422
50 ion_269.21.png 269.21 0.96917
51 ion_263.04.png 263.04 0.96838164
52 ion_202.24.png 202.24 0.9664346
53 ion_205.82.png 205.82 0.9639652
54 ion_216.22.png 216.22 0.9632674
55 ion_222.72.png 222.72 0.9614939
56 ion_132.66.png 132.66 0.96099925
57 ion_174.28.png 174.28 0.96078146
58 ion_74.79.png 74.79 0.95929277
59 ion_251.01.png 251.01 0.9586576
60 ion_371.3.png 371.3 0.9537004
61 ion_230.2.png 230.2 0.95332444
62 ion_278.64.png 278.64 0.95315814
63 ion_180.78.png 180.78 0.95183814
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 617 KiB

After

Width:  |  Height:  |  Size: 369 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
+573 -573
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 KiB

-3
View File
@@ -39,9 +39,6 @@ class MSIAugmentations:
def __init__(self, size=256): # Enforce 256 dimension consistency
self.spatial_transform = transforms.Compose([
transforms.Resize((size, size)),
transforms.RandomRotation(15),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomVerticalFlip(p=0.5),
transforms.ToTensor()
])
+4 -1
View File
@@ -92,6 +92,8 @@ if __name__ == "__main__":
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
X_pca = pca.fit_transform(X)
# CRITICAL FIX: Re-normalize after PCA to restore unit hypersphere geometry for Spherical K-Means equivalent
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
inertias = []
silhouettes = []
@@ -105,7 +107,8 @@ if __name__ == "__main__":
labels = kmeans.fit_predict(X_pca)
inertias.append(kmeans.inertia_)
silhouettes.append(silhouette_score(X_pca, labels))
# CRITICAL FIX: Evaluate using cosine distance on the un-reduced features
silhouettes.append(silhouette_score(X, labels, metric='cosine'))
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
+35 -5
View File
@@ -12,6 +12,7 @@ from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import pandas as pd
import torch.nn.functional as F
import plotly.express as px
def set_seed(seed=42):
random.seed(seed)
@@ -111,22 +112,25 @@ if __name__ == "__main__":
# FIX: Slice out the first principal component (index 0)
# if it continues to hold the global brightness/intensity bias
features_pca_km = features_pca_all[:, 1:]
# CRITICAL FIX: Re-normalize strictly for K-Means to ensure objective Cosine geometry
features_pca_km_norm = features_pca_km / np.linalg.norm(features_pca_km, axis=1, keepdims=True)
# ENFORCE EXACTLY 10 METABOLIC DOMAINS
print(f"Executing K-Means clustering strictly constrained to K={TARGET_K}...")
clusterer = KMeans(n_clusters=TARGET_K, init='k-means++', n_init=20, random_state=42)
labels = clusterer.fit_predict(features_pca_km)
labels = clusterer.fit_predict(features_pca_km_norm)
# MANIFOLD PROJECTION ADJUSTMENT
print("Projecting t-SNE map...")
tsne = TSNE(
n_components=2,
perplexity=15, # Reduced from 25 to force local structural groupings
early_exaggeration=12.0, # Adjusted to optimize structural separation distance
perplexity=15,
early_exaggeration=24.0, # Boosted significantly to force tighter, more definitive visual clusters
learning_rate='auto',
init='pca', # Changed from 'random' to preserve global cluster seed stability
init='pca',
random_state=42
)
# Feed the unnormalized PCA vectors to t-SNE to allow intensity variance to separate the visual blobs
embeddings_2d = tsne.fit_transform(features_pca_km)
# Plotting
@@ -143,6 +147,32 @@ if __name__ == "__main__":
plt.savefig(os.path.join(BASE_DIR, "..", "msi_tsne_corregido.png"), dpi=300, bbox_inches='tight')
plt.close()
# INTERACTIVE PLOTLY EXPORT
print("Exporting Interactive Plotly t-SNE...")
mz_values = [float(n.replace("ion_", "").replace(".png", "")) for n in ion_names]
df_plot = pd.DataFrame({
't-SNE Dimension 1': embeddings_2d[:, 0],
't-SNE Dimension 2': embeddings_2d[:, 1],
'Cluster': [str(lbl) for lbl in labels],
'm/z': mz_values,
'Filename': ion_names
})
fig = px.scatter(
df_plot,
x='t-SNE Dimension 1',
y='t-SNE Dimension 2',
color='Cluster',
hover_data=['m/z', 'Filename'],
title="Interactive Segmented Leaf Manifold (Custom Encoder)",
category_orders={"Cluster": [str(i) for i in range(TARGET_K)]}
)
plotly_out = os.path.join(BASE_DIR, "..", "figures", "msi_tsne_interactive.html")
os.makedirs(os.path.dirname(plotly_out), exist_ok=True)
fig.write_html(plotly_out)
print(f"Interactive t-SNE saved to: {plotly_out}")
# Save outputs
print("Exporting synchronized cluster assignments...")
df_results = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
@@ -0,0 +1,117 @@
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
from PIL import Image
import numpy as np
from sklearn.manifold import TSNE
import pandas as pd
import plotly.express as px
# 1. CONFIGURACIÓN
IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai"
ENCODER_PATH = "Reporte/Model/msi_encoder_trained.pth"
CSV_PATH = "msi_clusters_results.csv" # Fuente de verdad
N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. CARGAR EL MODELO ENTRENADO
def load_trained_encoder(path):
if not os.path.exists(path):
raise FileNotFoundError(f"No se encontró el modelo en {path}")
model = models.efficientnet_b0()
model.classifier = nn.Identity()
state_dict = torch.load(path, map_location=DEVICE)
model.load_state_dict(state_dict)
model.to(DEVICE)
model.eval()
return model
# 3. DATASET BASADO EN EL CSV
class MSIDatasetFromCSV(Dataset):
def __init__(self, img_dir, img_names):
self.img_dir = img_dir
self.img_names = img_names
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
def __len__(self):
return len(self.img_names)
def __getitem__(self, idx):
img_path = os.path.join(self.img_dir, self.img_names[idx])
image = Image.open(img_path).convert("RGB")
return self.transform(image)
# --- PROCESO ---
if __name__ == "__main__":
# 4. CARGAR EL CSV DE RESULTADOS
print(f"Cargando datos desde {CSV_PATH}...")
df = pd.read_csv(CSV_PATH)
ion_names = df['ion_image'].tolist()
# Asegurarnos de que cluster sea categórico para Plotly
df['cluster'] = df['cluster'].astype(str)
print("Extrayendo características con el encoder...")
encoder = load_trained_encoder(ENCODER_PATH)
dataset = MSIDatasetFromCSV(IMG_DIR, ion_names)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
features = []
with torch.no_grad():
for i, img in enumerate(loader):
img = img.to(DEVICE)
feat = encoder(img)
# Normalización L2
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
features.append(feat.cpu().numpy().flatten())
if (i+1) % 100 == 0:
print(f"Iones procesados: {i+1}/{len(ion_names)}")
features = np.array(features)
# 5. t-SNE
print("Calculando t-SNE...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features)
# Agregar coordenadas t-SNE al DataFrame original
df['tsne_1'] = embeddings_2d[:, 0]
df['tsne_2'] = embeddings_2d[:, 1]
# 6. VISUALIZACIÓN INTERACTIVA CON PLOTLY
print("Generando gráfica interactiva con Plotly...")
# Usar escala de colores similar a tab10 o cualitativa estándar
fig = px.scatter(
df,
x='tsne_1',
y='tsne_2',
color='cluster',
hover_data={'ion_image': True, 'mz': True, 'cluster': True, 'tsne_1': False, 'tsne_2': False},
title=f"t-SNE Interactivo de Iones MSI (Consistente con {CSV_PATH})",
labels={'tsne_1': 't-SNE 1', 'tsne_2': 't-SNE 2'},
category_orders={"cluster": [str(i) for i in range(N_CLUSTERS)]},
color_discrete_sequence=px.colors.qualitative.Plotly # O T10 si está disponible
)
# Mejorar el diseño
fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey')))
fig.update_layout(
legend_title_text='Cluster ID',
font=dict(size=14),
hoverlabel=dict(bgcolor="white", font_size=16)
)
# Guardar como HTML
output_html = "msi_tsne_interactivo.html"
fig.write_html(output_html)
print(f"\n¡Éxito! Gráfica interactiva guardada en '{output_html}'.")
print("Puedes abrir este archivo en cualquier navegador para explorar los clusters.")
+84
View File
@@ -0,0 +1,84 @@
import os
import torch
import torch.nn.functional as F
import pandas as pd
import numpy as np
from PIL import Image
from torchvision import transforms
# Copy the exact encoder structure from your scripts
import torch.nn as nn
class MSI_Structural_Encoder(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
nn.GroupNorm(4, 32),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
nn.GroupNorm(8, 64),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
nn.GroupNorm(16, 128),
nn.ReLU(),
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
nn.GroupNorm(32, 256),
nn.ReLU(),
nn.AdaptiveAvgPool2d((1, 1))
)
def forward(self, x):
return self.features(x).squeeze(-1).squeeze(-1)
DEVICE = torch.device("cpu")
IMG_DIR = "datos_para_ai"
MODEL_PATH = "models/msi_encoder_trained.pth"
if not os.path.exists(MODEL_PATH):
print("Model not found. Please ensure you are in the correct directory.")
exit()
model = MSI_Structural_Encoder()
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.eval()
transform = transforms.Compose([transforms.Resize((256, 256)), transforms.ToTensor()])
def get_vector(mz_target):
# Find the file closest to mz_target
files = [f for f in os.listdir(IMG_DIR) if f.endswith('.png')]
mzs = [float(f.replace("ion_", "").replace(".png", "")) for f in files]
idx = np.argmin(np.abs(np.array(mzs) - mz_target))
closest_mz = mzs[idx]
if abs(closest_mz - mz_target) > 0.1:
return None, closest_mz
img_path = os.path.join(IMG_DIR, files[idx])
img = Image.open(img_path).convert("L")
tensor = transform(img).unsqueeze(0)
with torch.no_grad():
feat = model(tensor)
feat_norm = F.normalize(feat, p=2, dim=1)
return feat_norm.numpy().flatten(), closest_mz
print("--- INTERNAL VALIDATION: ISOTOPIC & STRUCTURAL COHERENCE ---")
# Test 1: Isotopic Coherence (Atropine and its +1 Isotope)
v1, mz1 = get_vector(290.02)
v2, mz2 = get_vector(291.00)
if v1 is not None and v2 is not None:
sim = np.dot(v1, v2)
print(f"Isotopic Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz2:.2f} (+1 Isotope): Cosine Similarity = {sim:.4f}")
# Test 2: Structural Coherence (Atropine and Scopolamine - both vascular)
v3, mz3 = get_vector(304.00)
if v1 is not None and v3 is not None:
sim = np.dot(v1, v3)
print(f"Biological Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz3:.2f} (Scopolamine): Cosine Similarity = {sim:.4f}")
# Test 3: Unrelated Coherence (Atropine vs random background or non-vascular)
v4, mz4 = get_vector(142.09) # Tropine (paravascular, should be lower than scopolamine)
if v1 is not None and v4 is not None:
sim = np.dot(v1, v4)
print(f"Divergent Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz4:.2f} (Tropine): Cosine Similarity = {sim:.4f}")