Subir archivos a "/"

This commit is contained in:
2026-08-13 03:57:20 +02:00
parent 913c99911f
commit d778ba6e79
2 changed files with 32 additions and 47 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 325 KiB

After

Width:  |  Height:  |  Size: 294 KiB

+32 -47
View File
@@ -18,13 +18,13 @@ The central objective of this paper is to show how this architecture scales with
## Multi-Dataset Benchmarking ## Multi-Dataset Benchmarking
To evaluate the scalability and robustness of the Julia-Python preprocessing pipeline, we assembled a diverse collection of seven publicly available MSI datasets covering a range of file sizes (0.07--4.4 GB), ionization sources, mass analyzers, and biological matrices (Table 1). The datasets comprise both centroid and profile acquisitions; all were processed using the same pipeline configuration described in Section \ref{sec:julia_preprocessing}. ROI masks derived from the optical image were applied wherever a tissue reference was available — the *Datura* leaf and root, the human colon, and the three mouse tissues — restricting peak picking to pixels inside the tissue; only San Pedro, which lacks an optical reference, was processed without a mask. Peaks were then filtered using the default intensity threshold of 2\% of the base peak. To evaluate the scalability and robustness of the Julia-Python preprocessing pipeline, we assembled a diverse collection of seven publicly available MSI datasets covering a range of file sizes (0.07--4.4 GB), ionization sources, mass analyzers, and biological matrices (Table 1). The datasets comprise both centroid and profile acquisitions; all were processed using the same pipeline configuration described in the section "High-Performance Processing and Data Normalization (Julia)". ROI masks derived from the optical image were applied wherever a tissue reference was available — the *Datura* leaf and root, the human colon, and the three mouse tissues — restricting peak picking to pixels inside the tissue; only San Pedro, which lacks an optical reference, was processed without a mask. Peaks were then filtered using the default intensity threshold of 2\% of the base peak.
**Table 1.** Benchmark datasets used in this study. **Table 1.** Benchmark datasets used in this study.
| Dataset | Ionization | Mass Analyzer | Organism | File Size | Pixels | | Dataset | Ionization | Mass Analyzer | Organism | File Size | Pixels |
|---------|------------|---------------|----------|-----------|--------| |---------|------------|---------------|----------|-----------|--------|
| Leaf (Datura) | LD-LTP | Ion Trap | *D. innoxia* | 2.0 GB | 17,066 | | Datura Leaf | LD-LTP | Ion Trap | *D. innoxia* | 2.0 GB | 17,066 |
| Datura Root | LD-LTP | Ion Trap | *D. innoxia* | 2.5 GB | 21,060 | | Datura Root | LD-LTP | Ion Trap | *D. innoxia* | 2.5 GB | 21,060 |
| San Pedro | MALDI | TOF | *E. pachanoi* | 1.1 GB | 19,600 | | San Pedro | MALDI | TOF | *E. pachanoi* | 1.1 GB | 19,600 |
| Mouse bladder | AP-SMALDI | Orbitrap | *M. musculus* | 778 MB | 34,840 | | Mouse bladder | AP-SMALDI | Orbitrap | *M. musculus* | 778 MB | 34,840 |
@@ -36,18 +36,17 @@ To evaluate the scalability and robustness of the Julia-Python preprocessing pip
All computational analyses — the high-performance data extraction in Julia, the cross-language benchmark, and the deep-learning representation learning and clustering in Python — were executed on a single workstation with the following specifications: Processor: Intel(R) Core(TM) i5-9400F CPU @ 2.90 GHz (6 cores, 6 threads), Memory: 22 GB DDR4 RAM, Graphics: NVIDIA GeForce RTX 2060 (used for CUDA-accelerated neural network training), and Operating System: Ubuntu 24.04. Both the preprocessing and the machine learning stages therefore ran on identical hardware, so the reported memory and wall-clock measurements are directly comparable. All computational analyses — the high-performance data extraction in Julia, the cross-language benchmark, and the deep-learning representation learning and clustering in Python — were executed on a single workstation with the following specifications: Processor: Intel(R) Core(TM) i5-9400F CPU @ 2.90 GHz (6 cores, 6 threads), Memory: 22 GB DDR4 RAM, Graphics: NVIDIA GeForce RTX 2060 (used for CUDA-accelerated neural network training), and Operating System: Ubuntu 24.04. Both the preprocessing and the machine learning stages therefore ran on identical hardware, so the reported memory and wall-clock measurements are directly comparable.
Reproducibility is a first-class design requirement of the workflow. The entire environment — Julia package set, Python virtual environment with pinned dependencies, R/Bioconductor stack, and system tools — is codified in a Docker image. Because MSI software stacks are notoriously version-sensitive (a change in a peak-picking or normalization library can silently alter every downstream result), the container pins all package versions and orchestrates the seven pipeline stages (Section \ref{sec:pipeline}) with a single entry point, so the analysis can be reproduced bit-for-bit on any machine with Docker, independent of the host operating system or pre-installed software. This containerized approach follows the reproducibility recommendations of the SMART protocol [@xi_smart_2023] and the MIAMSIE guidelines for metabolomics data and metadata [@gustafsson_balancing_2018]; we additionally adopt the REFORMS checklist for reporting machine learning in the life sciences [@kapoor_reforms_2024], disclosing model architecture, hyperparameters, data processing, and all evaluation metrics in this manuscript and the repository. The workflow is released as open source under the MIT License, in keeping with the open-science philosophy that reproducible computational methods should be re-usable and auditable by the community. Reproducibility is a first-class design requirement of the workflow. The entire environment — Julia package set, Python virtual environment with pinned dependencies, R/Bioconductor stack, and system tools — is codified in a Docker image. Because MSI software stacks are notoriously version-sensitive (a change in a peak-picking or normalization library can silently alter every downstream result), the container pins all package versions and orchestrates the seven pipeline stages (see the section "Complete Hybrid Pipeline: From imzML to Metabolic Domains") with a single entry point, so the analysis can be reproduced bit-for-bit on any machine with Docker, independent of the host operating system or pre-installed software. This containerized approach follows the reproducibility recommendations of the SMART protocol [@xi_smart_2023] and the MIAMSIE guidelines for metabolomics data and metadata [@gustafsson_balancing_2018]; we additionally adopt the REFORMS checklist for reporting machine learning in the life sciences [@kapoor_reforms_2024], disclosing model architecture, hyperparameters, data processing, and all evaluation metrics in this manuscript and the repository. The workflow is released as open source under the MIT License, in keeping with the open-science philosophy that reproducible computational methods should be re-usable and auditable by the community.
## High-Performance Processing and Data Normalization (Julia) ## High-Performance Processing and Data Normalization (Julia)
\label{sec:julia_preprocessing}
We conducted the preprocessing stage using the JuliaMSI framework [@sierra-alvarez_juliamsi_2025], a platform specifically engineered to address the computational bottlenecks found in other programming languages. By leveraging Julia's just-in-time (JIT) compilation and efficient memory-mapping capabilities, we facilitated the rapid ingestion and manipulation of massive imzML binary files. As demonstrated in previous benchmarks [@sierra-alvarez_juliamsi_2025], this architecture provides a significant performance advantage over interpreted environments such as Python or R [@rosas-roman_open_2020], enabling the high-throughput extraction of mass slices without compromising spectral precision. We conducted the preprocessing stage using the JuliaMSI framework [@sierra-alvarez_juliamsi_2025], a platform specifically engineered to address the computational bottlenecks found in other programming languages. By leveraging Julia's just-in-time (JIT) compilation and efficient memory-mapping capabilities, we facilitated the rapid ingestion and manipulation of massive imzML binary files. As demonstrated in previous benchmarks [@sierra-alvarez_juliamsi_2025], this architecture provides a significant performance advantage over interpreted environments such as Python or R [@rosas-roman_open_2020], enabling the high-throughput extraction of mass slices without compromising spectral precision.
Previous benchmarks support this choice: Julia-based MSI architectures have been reported up to 5.2-fold faster than R implementations such as RmsiGUI on Linux, and Julia's native parsing of binary spectral data up to 214 times faster than equivalent R code [@sierra-alvarez_juliamsi_2025; @rosas-roman_technical_2024]. This efficiency is what makes the high-throughput bridge to the Python deep learning ecosystem practical at scale. Previous benchmarks support this choice: Julia-based MSI architectures have been reported up to 5.2-fold faster than R implementations such as RmsiGUI on Linux, and Julia's native parsing of binary spectral data up to 214 times faster than equivalent R code [@sierra-alvarez_juliamsi_2025; @rosas-roman_technical_2024]. This efficiency is what makes the high-throughput bridge to the Python deep learning ecosystem practical at scale.
**Memory-mapped lazy loading.** The core of the Julia engine is a memory-mapped (via the native \texttt{Mmap} API) and lazy imzML parser that reads spectra on demand from the on-disk \texttt{.ibd} binary file, never materializing the full acquisition in RAM. Spectra are pulled per-pixel as the pipeline walks the pixel grid, and buffer pooling reuses the small working set. This design is what keeps peak resident memory in the tens of megabytes regardless of the on-disk file size (Section \ref{sec:benchmark}), directly addressing the RAM bottleneck that gates MSI analysis on commodity workstations. **Memory-mapped lazy loading.** The core of the Julia engine is a memory-mapped (via the native `Mmap` API) and lazy imzML parser that reads spectra on demand from the on-disk `.ibd` binary file, never materializing the full acquisition in RAM. Spectra are pulled per-pixel as the pipeline walks the pixel grid, and buffer pooling reuses the small working set. This design is what keeps peak resident memory in the tens of megabytes regardless of the on-disk file size (see the section "Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)"), directly addressing the RAM bottleneck that gates MSI analysis on commodity workstations.
**Ion extraction and filtering.** We extracted mass slices from the \texttt{Leaf.imzML} dataset within the *m/z* 50.0 to 700.0 range. This upper limit was selected because no significant signals were detected beyond this threshold using the LD-LTP-MSI technique for this specific sample, and its implementation allowed for a more computationally manageable dataset. To ensure the inclusion of only chemically relevant signals and to exclude background noise, we applied a Region of Interest (ROI) mask derived from the optical image of the leaf. The average spectrum was computed exclusively from pixels within the tissue mask, and peaks were filtered using an intensity threshold of 2% relative to the base peak, resulting in 1,596 ion images for downstream analysis. Owing to the spectral binning inherent to the instrument's data acquisition, a single molecular species may be distributed across adjacent *m/z* channels with a characteristic bin spacing of $\sim0.08$--$0.09$ *m/z* per channel. The monoisotopic peak of scopolamine $[M+H]^+$ (exact mass 304.1549) is detected at the binned channel *m/z* 304.17, which is independently produced by the centroid-based peak-picking engine and corresponds to the same precursor selected for MS/MS structural confirmation. The adjacent bins (*m/z* 304.00, 304.08, 304.25, 304.33, 304.42) capture the isotopic envelope and neighboring noise, illustrating that spectral discretization must be considered when comparing imaging clusters with tandem mass spectrometry identifications. **Ion extraction and filtering.** We extracted mass slices from the `Leaf.imzML` dataset within the *m/z* 50.0 to 700.0 range. This upper limit was selected because no significant signals were detected beyond this threshold using the LD-LTP-MSI technique for this specific sample, and its implementation allowed for a more computationally manageable dataset. To ensure the inclusion of only chemically relevant signals and to exclude background noise, we applied a Region of Interest (ROI) mask derived from the optical image of the leaf. The average spectrum was computed exclusively from pixels within the tissue mask, and peaks were filtered using an intensity threshold of 2% relative to the base peak, resulting in 1,596 ion images for downstream analysis. Owing to the spectral binning inherent to the instrument's data acquisition, a single molecular species may be distributed across adjacent *m/z* channels with a characteristic bin spacing of $\sim0.08$--$0.09$ *m/z* per channel. The monoisotopic peak of scopolamine $[M+H]^+$ (exact mass 304.1549) is detected at the binned channel *m/z* 304.17, which is independently produced by the centroid-based peak-picking engine and corresponds to the same precursor selected for MS/MS structural confirmation. The adjacent bins (*m/z* 304.00, 304.08, 304.25, 304.33, 304.42) capture the isotopic envelope and neighboring noise, illustrating that spectral discretization must be considered when comparing imaging clusters with tandem mass spectrometry identifications.
**TrIQ normalization (Threshold Intensity Quantization).** To mitigate the impact of "hotspots"—stochastic pixels with disproportionately high intensities that obscure lower-abundance metabolic distributions—we applied the dynamic Threshold Intensity Quantization (TrIQ) algorithm [@rosas-roman_contrast_2021]. For each ion map, TrIQ sets a signal threshold at the 98th percentile of its non-zero finite intensities (falling back to the maximum observed intensity when this percentile is zero) and clamps every pixel's intensity to the unit interval $[0, 1]$. This ensures that 98% of the chemical signal is represented within a standardized dynamic range, enhancing the contrast of parenchymal and vascular structures and preventing the neural network from over-fitting to instrumental artifacts. **TrIQ normalization (Threshold Intensity Quantization).** To mitigate the impact of "hotspots"—stochastic pixels with disproportionately high intensities that obscure lower-abundance metabolic distributions—we applied the dynamic Threshold Intensity Quantization (TrIQ) algorithm [@rosas-roman_contrast_2021]. For each ion map, TrIQ sets a signal threshold at the 98th percentile of its non-zero finite intensities (falling back to the maximum observed intensity when this percentile is zero) and clamps every pixel's intensity to the unit interval $[0, 1]$. This ensures that 98% of the chemical signal is represented within a standardized dynamic range, enhancing the contrast of parenchymal and vascular structures and preventing the neural network from over-fitting to instrumental artifacts.
@@ -55,25 +54,23 @@ Previous benchmarks support this choice: Julia-based MSI architectures have been
## Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R) ## Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)
\label{sec:benchmark} To contextualize the performance of our Julia-based preprocessing within the current MSI software landscape, we conducted a controlled, three-way benchmark against Cardinal 3.14.0, the standard R/Bioconductor package for MSI analysis [@bemis_cardinal_2015], and against MALDIquant [@gibb_maldiquant:_2012], the standard R package for MALDI spectral processing. All three tools processed the same seven datasets (Table 1) on identical hardware (Intel i5-9400F, 22 GB RAM, Ubuntu 24.04). We designed a strictly equalized per-stage workload restricted to the steps that all three tools perform: (1) imzML file loading, and (2) in-memory extraction of a single target ion image at each dataset's canonical reference *m/z* (a biologically informative ion per sample: 304.17 for the *Datura* leaf and root, 885.5 for the human colon, 716.05 for the mouse bladder, 796.18 for the mouse liver, 804.3 for the mouse stomach, and 500.0 for San Pedro; tolerance 0.1 Da), plus the average spectrum and peak detection used to select the slice. The Julia engine runs the JuliaMSI `MSI_src` implementation, whose memory-mapped (`Mmap`) lazy loader and buffer pooling read spectra on demand from the on-disk `.ibd` file; for Cardinal, which stores centroid-mode spectra per-pixel as a list, the average spectrum was computed by binning pixel-wise m/z values onto a common 0.01 Da grid and the target ion image was extracted with the native 3.x API (`bin()` + `sliceImage()`); for MALDIquant, spectra were read into `MassSpectrum` objects and processed with `reduceIntensity`/`detectPeaks`, and the ion image was recovered from the aligned spectrum objects. Load memory (VmRSS delta) and wall-clock time were measured per stage via `/proc/self/status`, with each tool run in isolation. This apples-to-apples design deliberately excludes Julia-only steps (TrIQ normalization and PNG export) so that the comparison reflects identical computational work.
To contextualize the performance of our Julia-based preprocessing within the current MSI software landscape, we conducted a controlled, three-way benchmark against Cardinal 3.14.0, the standard R/Bioconductor package for MSI analysis [@bemis_cardinal_2015], and against MALDIquant [@gibb_maldiquant:_2012], the standard R package for MALDI spectral processing. All three tools processed the same seven datasets (Table 1) on identical hardware (Intel i5-9400F, 22 GB RAM, Ubuntu 24.04). We designed a strictly equalized per-stage workload restricted to the steps that all three tools perform: (1) imzML file loading, and (2) in-memory extraction of a single target ion image at each dataset's canonical reference *m/z* (a biologically informative ion per sample: 304.17 for the *Datura* leaf and root, 885.5 for the human colon, 716.05 for the mouse bladder, 796.18 for the mouse liver, 804.3 for the mouse stomach, and 500.0 for San Pedro; tolerance 0.1 Da), plus the average spectrum and peak detection used to select the slice. The Julia engine runs the JuliaMSI \texttt{MSI\_src} implementation, whose memory-mapped (\texttt{Mmap}) lazy loader and buffer pooling read spectra on demand from the on-disk \texttt{.ibd} file; for Cardinal, which stores centroid-mode spectra per-pixel as a list, the average spectrum was computed by binning pixel-wise m/z values onto a common 0.01 Da grid and the target ion image was extracted with the native 3.x API (\texttt{bin()} + \texttt{sliceImage()}); for MALDIquant, spectra were read into \texttt{MassSpectrum} objects and processed with \texttt{reduceIntensity}/\texttt{detectPeaks}, and the ion image was recovered from the aligned spectrum objects. Load memory (VmRSS delta) and wall-clock time were measured per stage via `/proc/self/status`, with each tool run in isolation. This apples-to-apples design deliberately excludes Julia-only steps (TrIQ normalization and PNG export) so that the comparison reflects identical computational work.
## Complete Hybrid Pipeline: From imzML to Metabolic Domains ## Complete Hybrid Pipeline: From imzML to Metabolic Domains
\label{sec:pipeline} The full workflow is orchestrated by a single entry point, `run_full_pipeline.sh`, which chains seven stages that consume only the raw imzML/ibd file pair and produce the final metabolic segmentation. This end-to-end integration — from binary ingestion to trained convolutional embeddings — is the central differentiation of the framework.
The full workflow is orchestrated by a single entry point, \texttt{run\_full\_pipeline.sh}, which chains seven stages that consume only the raw imzML/ibd file pair and produce the final metabolic segmentation. This end-to-end integration — from binary ingestion to trained convolutional embeddings — is the central differentiation of the framework.
**Stage 1 — Data ingestion and preprocessing (Julia, with Python fallback).** The imzML file is memory-mapped and parsed by the Julia engine, which (i) computes the average spectrum across all pixels (restricted to the ROI mask when available), (ii) selects peaks above a 2\% threshold of the base peak, (iii) extracts an ion image for every detected peak within a 0.05 Da tolerance, (iv) applies the TrIQ normalization per ion map, (v) spatially standardizes each map to a $256\times 256$ grid by strict zero-padding, and (vi) exports each normalized ion image twice: a grayscale PNG (\texttt{ion\_<mz>.png}) reserved exclusively for the deep learning stage, and a viridis-colored PNG of the same map (\texttt{outputs/ion\_images\_viridis/}) built with the native Julia \texttt{ViridisPalette}. For imzML variants that the Julia parser rejects (e.g., certain vendor-encoded name spaces), the stage transparently falls back to an equivalent Python preprocessor, guaranteeing robustness across instrument formats. Because each ion image is exported as a small PNG, the file-based interface between Julia and Python is also a natural memory bound: neither layer ever needs to hold the whole acquisition in RAM simultaneously. **Stage 1 — Data ingestion and preprocessing (Julia, with Python fallback).** The imzML file is memory-mapped and parsed by the Julia engine, which (i) computes the average spectrum across all pixels (restricted to the ROI mask when available), (ii) selects peaks above a 2\% threshold of the base peak, (iii) extracts an ion image for every detected peak within a 0.05 Da tolerance, (iv) applies the TrIQ normalization per ion map, (v) spatially standardizes each map to a $256\times 256$ grid by strict zero-padding, and (vi) exports each normalized ion image twice: a grayscale PNG (`ion_<mz>.png`) reserved exclusively for the deep learning stage, and a viridis-colored PNG of the same map (`outputs/ion_images_viridis/`) built with the native Julia `ViridisPalette`. For imzML variants that the Julia parser rejects (e.g., certain vendor-encoded name spaces), the stage transparently falls back to an equivalent Python preprocessor, guaranteeing robustness across instrument formats. Because each ion image is exported as a small PNG, the file-based interface between Julia and Python is also a natural memory bound: neither layer ever needs to hold the whole acquisition in RAM simultaneously.
**Stage 2 — Contrastive representation learning (Python, SimCLR).** The exported ion images form the training corpus of a custom 4-layer Group-Normalized fully convolutional encoder trained with the NT-Xent contrastive loss, projecting each ion map into a 128-dimensional latent space. The algorithmic details — and how they make this tractable on big data and consumer GPUs — are given in Section \ref{sec:simclr}. **Stage 2 — Contrastive representation learning (Python, SimCLR).** The exported ion images form the training corpus of a custom 4-layer Group-Normalized fully convolutional encoder trained with the NT-Xent contrastive loss, projecting each ion map into a 128-dimensional latent space. The algorithmic details — and how they make this tractable on big data and consumer GPUs — are given in the section "Self-Supervised Representation Learning (Python)".
**Stage 3 — Clustering evaluation.** The optimal number of metabolic clusters is selected via a multi-metric sweep (Silhouette, Davies-Bouldin, Calinski-Harabasz) over $k = 2,\dots,20$, computed per dataset from the learned latent space (Figure \ref{fig:clustering}). **Stage 3 — Clustering evaluation.** The optimal number of metabolic clusters is selected via a multi-metric sweep (Silhouette, Davies-Bouldin, Calinski-Harabasz) over $k = 2,\dots,20$, computed per dataset from the learned latent space (Figure 2).
**Stage 4 — t-SNE visualization.** Latent embeddings are projected to two dimensions and colored by the selected number of clusters (Figure \ref{fig:tsne_clusters}). **Stage 4 — t-SNE visualization.** Latent embeddings are projected to two dimensions and colored by the selected number of clusters (Figure 3).
**Stage 5 — Quantitative validation.** The clustering is validated by testing the spatial co-localization of isotopologue pairs against random ion pairs (Welch's t-test), and against a PCA baseline, including stability analysis (Adjusted Rand Index across seeds). **Stage 5 — Quantitative validation.** The clustering is validated by testing the spatial co-localization of isotopologue pairs against random ion pairs (Welch's t-test), and against a PCA baseline, including stability analysis (Adjusted Rand Index across seeds).
**Stage 6 — Cluster galleries.** Representative ion images are assembled per cluster to visually confirm the anatomical domains (Figure \ref{fig:tsne_clusters}). **Stage 6 — Cluster galleries.** Representative ion images are assembled per cluster to visually confirm the anatomical domains (Figure 3).
**Stage 7 — Mass spectra.** Mean spectra per cluster and the full average spectrum are plotted for biological interpretation. **Stage 7 — Mass spectra.** Mean spectra per cluster and the full average spectrum are plotted for biological interpretation.
@@ -81,7 +78,6 @@ In summary, the Julia layer performs all high-throughput binary parsing and imag
## Self-Supervised Representation Learning (Python) ## Self-Supervised Representation Learning (Python)
\label{sec:simclr}
We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorch_2019], adapting the framework to the unique properties of mass spectrometry imaging. This section details the algorithm and the specific hardware- and data-related problems each design choice solves. We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorch_2019], adapting the framework to the unique properties of mass spectrometry imaging. This section details the algorithm and the specific hardware- and data-related problems each design choice solves.
**Problem 1 — zero-padded background biases normalization statistics.** A custom Fully Convolutional Contrastive Network was engineered to replace standard heavy computer vision backbones. Crucially, all standard batch normalization blocks were replaced with Group Normalization (GroupNorm) layers (8 groups per layer). In datasets characterized by massive empty, zero-padded backgrounds, standard Batch Normalization calculates running statistics that become overwhelmingly biased by the blank space, leading to gradient instability and the artificial clustering of the background mask. Group Normalization computes statistics per individual image slice, mathematically neutralizing the static background and forcing the network to optimize strictly on the high-variance internal biological structures. The network concludes with an Adaptive Average Pooling layer and a 2-layer MLP to project the spatial features into a 128-dimensional latent space (Table 2). **Problem 1 — zero-padded background biases normalization statistics.** A custom Fully Convolutional Contrastive Network was engineered to replace standard heavy computer vision backbones. Crucially, all standard batch normalization blocks were replaced with Group Normalization (GroupNorm) layers (8 groups per layer). In datasets characterized by massive empty, zero-padded backgrounds, standard Batch Normalization calculates running statistics that become overwhelmingly biased by the blank space, leading to gradient instability and the artificial clustering of the background mask. Group Normalization computes statistics per individual image slice, mathematically neutralizing the static background and forcing the network to optimize strictly on the high-variance internal biological structures. The network concludes with an Adaptive Average Pooling layer and a 2-layer MLP to project the spatial features into a 128-dimensional latent space (Table 2).
@@ -90,7 +86,7 @@ We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorc
**Problem 3 — spatial augmentations corrupt the co-localization signal.** Standard computer vision augmentation libraries (e.g., Torchvision) apply spatial transformations—random rotations, horizontal/vertical flips, and random crops—as a default strategy to promote translation and rotation invariance. This practice is explicitly and deliberately incompatible with our co-localization objective and was therefore completely prohibited. In spatial metabolomics, the absolute $(x, y)$ pixel grid of a single-slice acquisition is the immutable biological ground truth [@alexandrov_maldi_2012]. Our framework operates strictly within the paradigm of Camp A (Single-Experiment Co-localization): the goal is not to learn features that are invariant to spatial position, but precisely to learn which ions share the same position. A random 90° flip applied to two different views of the same image would teach the encoder that the top-left quadrant is equivalent to the bottom-right quadrant, destroying the spatial registration matrix and corrupting the co-localization signal. The exclusive use of chemical-noise augmentations (which simulate detector artifacts while leaving the coordinate grid untouched) is therefore a deliberate, foundational design choice, consistent with established best practices in MSI deep learning [@hu_deepion_2021]. **Problem 3 — spatial augmentations corrupt the co-localization signal.** Standard computer vision augmentation libraries (e.g., Torchvision) apply spatial transformations—random rotations, horizontal/vertical flips, and random crops—as a default strategy to promote translation and rotation invariance. This practice is explicitly and deliberately incompatible with our co-localization objective and was therefore completely prohibited. In spatial metabolomics, the absolute $(x, y)$ pixel grid of a single-slice acquisition is the immutable biological ground truth [@alexandrov_maldi_2012]. Our framework operates strictly within the paradigm of Camp A (Single-Experiment Co-localization): the goal is not to learn features that are invariant to spatial position, but precisely to learn which ions share the same position. A random 90° flip applied to two different views of the same image would teach the encoder that the top-left quadrant is equivalent to the bottom-right quadrant, destroying the spatial registration matrix and corrupting the co-localization signal. The exclusive use of chemical-noise augmentations (which simulate detector artifacts while leaving the coordinate grid untouched) is therefore a deliberate, foundational design choice, consistent with established best practices in MSI deep learning [@hu_deepion_2021].
**Problem 4 — dataset sizes are moderate but augmentation makes them effectively infinite.** The training corpus comprises 1,596 ion images for the *Datura* leaf that passed the 2% intensity threshold filter and ROI mask selection. This number is mathematically sufficient for this self-supervised task for two compounding reasons. First, the custom 4-layer fully convolutional architecture is a lightweight, low-dimensional feature extractor. Unlike overparameterized ImageNet backbones such as EfficientNet-B0 [@tan_efficientnet_2019] (which carry over 5 million parameters trained for 1,000 natural image categories), our encoder is purpose-built to extract a compact morphological fingerprint; it requires far fewer samples to converge on a meaningful manifold. Second, the \texttt{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. **Problem 4 — dataset sizes are moderate but augmentation makes them effectively infinite.** The training corpus comprises 1,596 ion images for the *Datura* leaf that passed the 2% intensity threshold filter and ROI mask selection. This number is mathematically sufficient for this self-supervised task for two compounding reasons. First, the custom 4-layer fully convolutional architecture is a lightweight, low-dimensional feature extractor. Unlike overparameterized ImageNet backbones such as EfficientNet-B0 [@tan_efficientnet_2019] (which carry over 5 million parameters trained for 1,000 natural image categories), our encoder is purpose-built to extract a compact morphological fingerprint; it requires far fewer samples to converge on a meaningful manifold. Second, the `apply_msi_chemical_noise` augmentation pipeline functions as a stochastic, infinite data generator. Because intensity scaling factors, Poisson noise seeds, and dropout masks are sampled randomly at each epoch, the network never encounters the exact same image representation twice, exponentially expanding the effective training pool and providing robust protection against overfitting.
**Table 2.** Training hyperparameters and model configuration for the SimCLR-MSI workflow. **Table 2.** Training hyperparameters and model configuration for the SimCLR-MSI workflow.
@@ -108,7 +104,7 @@ We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorc
**Clustering on the hypersphere.** The SimCLR objective (NT-Xent Loss) trains the encoder to project features onto a unit $L_2$ hypersphere, where semantic proximity is defined by directional cosine angles rather than Euclidean distances. The application of Principal Component Analysis (PCA) prior to clustering is a dimensionality reduction step that, as a side effect, breaks this hypersphere geometry by altering the magnitudes of the latent vectors. To restore geometric integrity, every feature vector was re-normalized to unit length after PCA transformation and before K-Means assignment. This converts standard Euclidean K-Means into a functional Spherical K-Means [@hornik_spherical_2012], ensuring that cluster centroids are determined by cosine similarity rather than arbitrary vector magnitudes—a critical requirement for correctly grouping ions with identical spatial silhouettes but different absolute intensities. **Clustering on the hypersphere.** The SimCLR objective (NT-Xent Loss) trains the encoder to project features onto a unit $L_2$ hypersphere, where semantic proximity is defined by directional cosine angles rather than Euclidean distances. The application of Principal Component Analysis (PCA) prior to clustering is a dimensionality reduction step that, as a side effect, breaks this hypersphere geometry by altering the magnitudes of the latent vectors. To restore geometric integrity, every feature vector was re-normalized to unit length after PCA transformation and before K-Means assignment. This converts standard Euclidean K-Means into a functional Spherical K-Means [@hornik_spherical_2012], ensuring that cluster centroids are determined by cosine similarity rather than arbitrary vector magnitudes—a critical requirement for correctly grouping ions with identical spatial silhouettes but different absolute intensities.
**Selecting the number of clusters.** To determine the optimal number of clusters (k), we performed a multi-metric systematic sweep from k = 2 to k = 20, evaluating the Silhouette Score, Davies-Bouldin Index, and Calinski-Harabasz Index at each value. Because k = 2 conflates an entire tissue into a single "tissue vs background" split and fails to resolve any internal anatomical compartment, the number of metabolic clusters is adopted from the joint optimum of the Davies-Bouldin and Calinski-Harabasz indices, which trade cluster compactness against anatomical resolution. This multi-metric, data-driven selection is applied independently per dataset, because the optimal number of metabolic domains is a property of each tissue architecture. The seven datasets returned optima ranging from k = 2 (San Pedro) to k = 20 (human colon), as summarized in Figure \ref{fig:clustering} and discussed in Section \ref{sec:clustering_results}. **Selecting the number of clusters.** To determine the optimal number of clusters (k), we performed a multi-metric systematic sweep from k = 2 to k = 20, evaluating the Silhouette Score, Davies-Bouldin Index, and Calinski-Harabasz Index at each value. Because k = 2 conflates an entire tissue into a single "tissue vs background" split and fails to resolve any internal anatomical compartment, the number of metabolic clusters is adopted from the joint optimum of the Davies-Bouldin and Calinski-Harabasz indices, which trade cluster compactness against anatomical resolution. This multi-metric, data-driven selection is applied independently per dataset, because the optimal number of metabolic domains is a property of each tissue architecture. The seven datasets returned optima ranging from k = 2 (San Pedro) to k = 20 (human colon), as summarized in Figure 2 and discussed in the section "Clustering Validation Across the Seven Datasets".
## Application Dataset: LD-LTP-MSI of *Datura innoxia* ## Application Dataset: LD-LTP-MSI of *Datura innoxia*
@@ -118,46 +114,36 @@ To demonstrate the biological utility of the workflow, we acquired an MSI datase
## Computational Benchmark: Julia vs Cardinal and MALDIquant Across Seven Datasets ## Computational Benchmark: Julia vs Cardinal and MALDIquant Across Seven Datasets
\label{sec:benchmark_results} The controlled three-way benchmark (Figure 1) evaluates the identical preprocessing workload — imzML load plus one in-memory ion slice at each dataset's canonical reference *m/z* (see the section "Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)", tolerance 0.1 Da) — on seven datasets spanning two orders of magnitude in file size (0.07--4.4 GB). Load memory (VmRSS delta) and wall-clock time were measured on the same hardware (Intel i5-9400F, 22 GB RAM). The results establish three findings, all consistent across every dataset in the benchmark figures, which show the Julia engine ahead in both memory and ion-slice throughput on all seven samples.
The controlled three-way benchmark (Figure \ref{fig:benchmark}) evaluates the identical preprocessing workload — imzML load plus one in-memory ion slice at each dataset's canonical reference *m/z* (Section \ref{sec:benchmark}, tolerance 0.1 Da) — on seven datasets spanning two orders of magnitude in file size (0.07--4.4 GB). Load memory (VmRSS delta) and wall-clock time were measured on the same hardware (Intel i5-9400F, 22 GB RAM). The results establish three findings, all consistent across every dataset in the benchmark figures, which show the Julia engine ahead in both memory and ion-slice throughput on all seven samples.
First, the Julia ion-slice operation is one to two orders of magnitude faster than Cardinal on every dataset (0.00009--0.32 s vs 6.3--19.5 s) and materially faster than MALDIquant (1.3--3.9 s) — 54- to 79,949-fold faster than Cardinal depending on the dataset (Figure \ref{fig:benchmark}A). This is the dominant per-ion cost when exporting a full ion corpus, and therefore the step that decides whether processing a full MSI dataset is feasible in reasonable wall-clock time: at Cardinal's per-slice cost, exporting the 1,596-ion *Datura* leaf corpus would take hours, whereas the Julia engine completes the export in minutes within a single pass. First, the Julia ion-slice operation is one to two orders of magnitude faster than Cardinal on every dataset (0.00009--0.32 s vs 6.3--19.5 s) and materially faster than MALDIquant (1.3--3.9 s) — 54- to 79,949-fold faster than Cardinal depending on the dataset (Figure 1A). This is the dominant per-ion cost when exporting a full ion corpus, and therefore the step that decides whether processing a full MSI dataset is feasible in reasonable wall-clock time: at Cardinal's per-slice cost, exporting the 1,596-ion *Datura* leaf corpus would take hours, whereas the Julia engine completes the export in minutes within a single pass.
Second, peak load resident memory (VmRSS) favors Julia unconditionally (Figure \ref{fig:benchmark}B): the memory-mapped loader keeps the working set at 7--84 MB, below Cardinal's ~120 MB on all seven datasets and far below MALDIquant (up to 4.0 GB on the Datura root), which ran out of memory on the two heaviest samples (mouse liver and mouse stomach). Because the memory-mapped parser never materializes the full acquisition, peak RAM is decoupled from on-disk file size: the largest dataset (mouse stomach, 4.4 GB) is processed at 83 MB of resident RAM. This is the property that makes the pipeline runnable on commodity workstations and laptops. Second, peak load resident memory (VmRSS) favors Julia unconditionally (Figure 1B): the memory-mapped loader keeps the working set at 7--84 MB, below Cardinal's ~120 MB on all seven datasets and far below MALDIquant (up to 4.0 GB on the Datura root), which ran out of memory on the two heaviest samples (mouse liver and mouse stomach). Because the memory-mapped parser never materializes the full acquisition, peak RAM is decoupled from on-disk file size: the largest dataset (mouse stomach, 4.4 GB) is processed at 83 MB of resident RAM. This is the property that makes the pipeline runnable on commodity workstations and laptops.
Third, the differentiation is not universal raw wall-clock speed — Cardinal's fully in-memory load is faster in wall time than the Julia lazy mapping on the larger files (0.9--2.0 s vs 0.006--1.1 s), because it reads the whole file eagerly — but that eager scheme is precisely what drives its larger resident set. The value of the Julia-Python pipeline is therefore its ability to complete the *entire* analytical job — ion extraction, TrIQ normalization, and PNG export of every ion image in a deep-learning-ready format — within the same measured RAM envelope, in a single memory-mapped pass that requires no staged intermediate files and no manual memory management. We report the measurements transparently in the benchmark repository, including those that favor the R ecosystem. Third, the differentiation is not universal raw wall-clock speed — Cardinal's fully in-memory load is faster in wall time than the Julia lazy mapping on the larger files (0.9--2.0 s vs 0.006--1.1 s), because it reads the whole file eagerly — but that eager scheme is precisely what drives its larger resident set. The value of the Julia-Python pipeline is therefore its ability to complete the *entire* analytical job — ion extraction, TrIQ normalization, and PNG export of every ion image in a deep-learning-ready format — within the same measured RAM envelope, in a single memory-mapped pass that requires no staged intermediate files and no manual memory management. We report the measurements transparently in the benchmark repository, including those that favor the R ecosystem.
## Clustering Validation Across the Seven Datasets ## Clustering Validation Across the Seven Datasets
\label{sec:clustering_results} Because the deep learning stage is a core contribution of this workflow, we report its behavior across all seven benchmark datasets rather than on a single tissue. For each dataset, Stage 3 (see the section "Complete Hybrid Pipeline: From imzML to Metabolic Domains") evaluated the learned latent space with a K-sweep (k = 2--20) and three internal metrics — Silhouette, Davies-Bouldin, and Calinski-Harabasz (Figure 2 shows the sweeps for the two *Datura* demonstration datasets). The optimal K is a property of each tissue's architecture and varies strongly across datasets: the two-zone tissues (San Pedro stem, *Datura* root) converge at low k (k = 2 and k = 3, with all three metrics in agreement), whereas the histologically complex tissues saturate at the upper bound of the sweep (human colon at k = 20, mouse bladder at k = 19--20), and the *Datura* leaf and the two mouse tissues fall between (k = 5 and k = 7--12 by the Davies-Bouldin/Calinski-Harabasz optima). The multi-metric sweep is therefore not cosmetic: it is required to scale the workflow to arbitrary tissues without manual tuning, and the pipeline adopts the joint Davies-Bouldin/Calinski-Harabasz optimum as the metabolic cluster count, since the Silhouette optimum of k = 2 merely reproduces the trivial tissue-versus-background split.
Because the deep learning stage is a core contribution of this workflow, we report its behavior across all seven benchmark datasets rather than on a single tissue. For each dataset, Stage 3 (Section \ref{sec:pipeline}) evaluated the learned latent space with a K-sweep (k = 2--20) and three internal metrics — Silhouette, Davies-Bouldin, and Calinski-Harabasz (Figure \ref{fig:clustering} shows the sweeps for the two \textit{Datura} demonstration datasets). The optimal K is a property of each tissue's architecture and varies strongly across datasets: the two-zone tissues (San Pedro stem, *Datura* root) converge at low k (k = 2 and k = 3, with all three metrics in agreement), whereas the histologically complex tissues saturate at the upper bound of the sweep (human colon at k = 20, mouse bladder at k = 19--20), and the *Datura* leaf and the two mouse tissues fall between (k = 5 and k = 7--12 by the Davies-Bouldin/Calinski-Harabasz optima). The multi-metric sweep is therefore not cosmetic: it is required to scale the workflow to arbitrary tissues without manual tuning, and the pipeline adopts the joint Davies-Bouldin/Calinski-Harabasz optimum as the metabolic cluster count, since the Silhouette optimum of k = 2 merely reproduces the trivial tissue-versus-background split.
The learned embeddings systematically outperform a PCA baseline on the same features (Section \ref{sec:simclr}) for every dataset, and cluster assignments are stable across random seeds (Adjusted Rand Index $\geq 0.9$). Isotope co-localization validation — a natural ground truth requiring no annotation — is positive across datasets and reaches high significance where the ion corpus is large enough to support the statistical test (Welch's t-test, $p < 10^{-6}$ for the human colon, $p < 10^{-300}$ for the *Datura* leaf). These results show that the deep learning stage scales from the smallest (69 MB, 682 ions) to the largest (4.4 GB) datasets in the benchmark without parameter changes, and that the file-based Julia-to-Python handoff keeps the whole analysis reproducible in a single container. The learned embeddings systematically outperform a PCA baseline on the same features (see the section "Self-Supervised Representation Learning (Python)") for every dataset, and cluster assignments are stable across random seeds (Adjusted Rand Index $\geq 0.9$). Isotope co-localization validation — a natural ground truth requiring no annotation — is positive across datasets and reaches high significance where the ion corpus is large enough to support the statistical test (Welch's t-test, $p < 10^{-6}$ for the human colon, $p < 10^{-300}$ for the *Datura* leaf). These results show that the deep learning stage scales from the smallest (69 MB, 682 ions) to the largest (4.4 GB) datasets in the benchmark without parameter changes, and that the file-based Julia-to-Python handoff keeps the whole analysis reproducible in a single container.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{Figure1_benchmark.png}
\caption{Equalized three-way benchmark of JuliaMSI vs Cardinal (R) and MALDIquant (R) preprocessing under an identical per-stage workload (load + average spectrum + peaks + one ion slice at each dataset's canonical reference *m/z*, tolerance 0.1 Da) across seven public datasets ordered by file size (lightest to heaviest). (A) Slice-generation throughput (slices per second, log scale): the Julia engine generates ion slices one to two orders of magnitude faster than Cardinal on every dataset (54- to 79,949-fold) and materially faster than MALDIquant, a difference that dominates the cost of exporting a full ion corpus. (B) Peak load resident RAM (VmRSS, MB, log scale): the memory-mapped lazy loader keeps the working set at 7--84 MB — below Cardinal's ~120 MB on every dataset and far below MALDIquant (up to 4.0 GB). Red X markers indicate the datasets that MALDIquant could not process (mouse liver and mouse stomach), which exhausted the 22 GB reference machine.}
\label{fig:benchmark}
\end{figure}
\begin{figure}[htbp] **Figure 1.** Equalized three-way benchmark of JuliaMSI vs Cardinal (R) and MALDIquant (R) preprocessing under an identical per-stage workload (load + average spectrum + peaks + one ion slice at each dataset's canonical reference *m/z*, tolerance 0.1 Da) across seven public datasets ordered by file size (lightest to heaviest). (A) Slice-generation throughput (slices per second, log scale): the Julia engine generates ion slices one to two orders of magnitude faster than Cardinal on every dataset (54- to 79,949-fold) and materially faster than MALDIquant, a difference that dominates the cost of exporting a full ion corpus. (B) Peak load resident RAM (VmRSS, MB, log scale): the memory-mapped lazy loader keeps the working set at 7--84 MB — below Cardinal's ~120 MB on every dataset and far below MALDIquant (up to 4.0 GB). Red X markers indicate the datasets that MALDIquant could not process (mouse liver and mouse stomach), which exhausted the 22 GB reference machine.
\centering
\includegraphics[width=\textwidth]{Figure2_clustering_validation.png} ![Figure 1 — Benchmark of JuliaMSI vs Cardinal and MALDIquant.](Figure1_benchmark.png)
\caption{Clustering validation of the two \textit{Datura innoxia} demonstration datasets. For each dataset, the SimCLR latent space (Section \ref{sec:simclr}) was evaluated over a K-sweep (k = 2--20) with four panels: Elbow method (inertia), Silhouette score, Davies-Bouldin index, and Calinski-Harabasz index. The joint Davies-Bouldin/Calinski-Harabasz optimum is adopted as the number of metabolic clusters, since the Silhouette optimum of k = 2 always reproduces the trivial tissue-versus-background split. This selects k = 5 for the leaf (Davies-Bouldin 0.9124; Calinski-Harabasz 1304.29) and k = 3 for the root (0.8518; 868.21), reflecting the distinct metabolic architecture of the two tissues.}
\label{fig:clustering} **Figure 2.** Clustering validation of the two *Datura innoxia* demonstration datasets. For each dataset, the SimCLR latent space (see the section "Self-Supervised Representation Learning (Python)") was evaluated over a K-sweep (k = 2--20) with four panels: Elbow method (inertia), Silhouette score, Davies-Bouldin index, and Calinski-Harabasz index. The joint Davies-Bouldin/Calinski-Harabasz optimum is adopted as the number of metabolic clusters, since the Silhouette optimum of k = 2 always reproduces the trivial tissue-versus-background split. This selects k = 5 for the leaf (Davies-Bouldin 0.9124; Calinski-Harabasz 1304.29) and k = 3 for the root (0.8518; 868.21), reflecting the distinct metabolic architecture of the two tissues.
\end{figure}
![Figure 2 — K-sweep clustering validation for the Datura leaf and root.](Figure2_clustering_validation.png)
## Multi-Dataset Unsupervised Segmentation ## Multi-Dataset Unsupervised Segmentation
The segmentations of the two most architecturally demanding benchmark tissues are shown in Figure \ref{fig:tsne_clusters}: the learned 128-dimensional embeddings projected with t-SNE and colored by the K-Means assignment at each dataset's adopted K, alongside individual representative ion images for the four largest clusters of each tissue. For both the mouse bladder (AP-SMALDI) and the human colon (DESI), the workflow recovers spatially coherent, interpretable metabolic domains without any manual annotation or dataset-specific parameter tuning, resolving 20 domains per tissue. The t-SNE projections consistently display the continuous, gradient-like geometry discussed below, which reflects the underlying anatomical continuum rather than clustering failure. The segmentations of the two most architecturally demanding benchmark tissues are shown in Figure 3: the learned 128-dimensional embeddings projected with t-SNE and colored by the K-Means assignment at each dataset's adopted K, alongside individual representative ion images for the four largest clusters of each tissue. For both the mouse bladder (AP-SMALDI) and the human colon (DESI), the workflow recovers spatially coherent, interpretable metabolic domains without any manual annotation or dataset-specific parameter tuning, resolving 20 domains per tissue. The t-SNE projections consistently display the continuous, gradient-like geometry discussed below, which reflects the underlying anatomical continuum rather than clustering failure.
\begin{figure}[htbp] **Figure 3.** Unsupervised segmentation of the two fine-grained benchmark tissues, the mouse bladder (AP-SMALDI) and the human colon (DESI). For each dataset, the left panel is the t-SNE projection of the SimCLR latent space colored by K-Means cluster assignment at the adopted K; the right panels show individual representative ion images (viridis, *m/z* annotated) from the four largest clusters of each tissue, illustrating the distinct spatial morphology of each recovered metabolic domain. The workflow resolves the histologically complex architecture of both tissues — 20 metabolic domains for each — with the same Julia preprocessing, the same SimCLR encoder, and the same K-selection logic, requiring no manual tuning.
\centering
\includegraphics[width=\textwidth]{Figure3_tsne_galleries.png} ![Figure 3 — t-SNE segmentations and representative ion images for the mouse bladder and human colon.](Figure3_tsne_galleries.png)
\caption{Unsupervised segmentation of the two fine-grained benchmark tissues, the mouse bladder (AP-SMALDI) and the human colon (DESI). For each dataset, the left panel is the t-SNE projection of the SimCLR latent space colored by K-Means cluster assignment at the adopted K; the right panels show individual representative ion images (viridis, \textit{m/z} annotated) from the four largest clusters of each tissue, illustrating the distinct spatial morphology of each recovered metabolic domain. The workflow resolves the histologically complex architecture of both tissues — 20 metabolic domains for each — with the same Julia preprocessing, the same SimCLR encoder, and the same K-selection logic, requiring no manual tuning.}
\label{fig:tsne_clusters}
\end{figure}
### Interpreting the Continuous Latent Manifold ### Interpreting the Continuous Latent Manifold
@@ -171,16 +157,15 @@ While PCA relies on magnitude-dependent variance—essentially grouping ions bas
## Case Study: *Datura innoxia* Segmentation ## Case Study: *Datura innoxia* Segmentation
\label{sec:case_study}
The unsupervised decomposition of the latent space of the *Datura innoxia* leaf yielded five distinct molecular domains (Clusters 0--4), each representing a reproducible and spatially resolved chemical pattern across the leaf surface. These clusters capture the heterogeneity of ion distributions and reveal a structured organization of metabolites at the tissue level. The key tropane alkaloids scopolamine (*m/z* 304.0), atropine/hyoscyamine (*m/z* 290.08), and 6-hydroxyhyoscyamine (*m/z* 306.25) are co-localized in a single domain (Cluster 2), while the biosynthetic precursors tropinone (*m/z* 140.17), tropine (*m/z* 142.08), and cuscohygrine (*m/z* 225.92) occupy three distinct domains (Clusters 0, 3, and 4). This co-localization is consistent with acropetal transport of the alkaloids through the vascular system and their distribution across the leaf mesophyll [@ziegler_alkaloid_2008; @schlesinger_tropane_2021]. The unsupervised decomposition of the latent space of the *Datura innoxia* leaf yielded five distinct molecular domains (Clusters 0--4), each representing a reproducible and spatially resolved chemical pattern across the leaf surface. These clusters capture the heterogeneity of ion distributions and reveal a structured organization of metabolites at the tissue level. The key tropane alkaloids scopolamine (*m/z* 304.0), atropine/hyoscyamine (*m/z* 290.08), and 6-hydroxyhyoscyamine (*m/z* 306.25) are co-localized in a single domain (Cluster 2), while the biosynthetic precursors tropinone (*m/z* 140.17), tropine (*m/z* 142.08), and cuscohygrine (*m/z* 225.92) occupy three distinct domains (Clusters 0, 3, and 4). This co-localization is consistent with acropetal transport of the alkaloids through the vascular system and their distribution across the leaf mesophyll [@ziegler_alkaloid_2008; @schlesinger_tropane_2021].
To confirm the identity of the tropane alkaloids *in situ*, we subjected the precursor ion at *m/z* 304.17 to tandem mass spectrometry (MS/MS) at a collision energy of 20 eV. The resulting fragmentation pattern from the leaf surface showed an excellent spectral match with the commercial scopolamine reference standard, and the diagnostic product ions across the *m/z* 80--320 range confirm the unambiguous structural identification of scopolamine directly from the plant surface without the need for extensive sample preparation [@garcia-rojas_identification_2024]. Critically, the MS/MS precursor at *m/z* 304.17 corresponds exactly to one of the centroid bins independently generated by the pipeline's peak-picking algorithm, producing the ion image \texttt{ion\_304.17.png}. The adjacent bins (*m/z* 304.00--304.42) capture the isotopic envelope of scopolamine and are also structurally consistent with this assignment, as confirmed by their shared vascular-related spatial patterns. To confirm the identity of the tropane alkaloids *in situ*, we subjected the precursor ion at *m/z* 304.17 to tandem mass spectrometry (MS/MS) at a collision energy of 20 eV. The resulting fragmentation pattern from the leaf surface showed an excellent spectral match with the commercial scopolamine reference standard, and the diagnostic product ions across the *m/z* 80--320 range confirm the unambiguous structural identification of scopolamine directly from the plant surface without the need for extensive sample preparation [@garcia-rojas_identification_2024]. Critically, the MS/MS precursor at *m/z* 304.17 corresponds exactly to one of the centroid bins independently generated by the pipeline's peak-picking algorithm, producing the ion image `ion_304.17.png`. The adjacent bins (*m/z* 304.00--304.42) capture the isotopic envelope of scopolamine and are also structurally consistent with this assignment, as confirmed by their shared vascular-related spatial patterns.
Quantitatively, the leaf validation signature is strong: a global statistical analysis across 1,394 discovered isotopic pairs yielded a mean latent distance of $0.2687$, compared to $0.5715$ for random ion pairs, achieving profound statistical significance (Welch's t-test, $p < 10^{-300}$). Of these, 1,353 pairs (97.1\%) passed strict structural validation (Cosine Similarity $\geq 0.80$), including Atropine (*m/z* 290.08) and its $+1$ isotope (*m/z* 291.17) with a cosine similarity of 0.9959. The pipeline was applied identically to the *Datura innoxia* root dataset (2.5 GB, 21,060 pixels, 858 ion images), where all three metrics agree on k = 3 and the segmentation separates the biosynthetic-site domains: tropinone (*m/z* 140.17) and tropine (*m/z* 142.08) are co-localized in one domain, while cuscohygrine (*m/z* 225.92) and atropine/hyoscyamine (*m/z* 290.08) are co-localized in a second domain. Scopolamine is absent from the root ion corpus because the root spectrum is dominated by the biosynthetic precursors (the base peak is tropine, *m/z* 142.08), so the scopolamine channel reaches only 1.5% of the base-peak intensity and falls below the 2% cutoff — consistent with the classical model in which scopolamine is produced in the root but accumulates distally in the shoot [@schlesinger_tropane_2021]. The root result demonstrates that the workflow generalizes across tissues without any parameter change. Quantitatively, the leaf validation signature is strong: a global statistical analysis across 1,394 discovered isotopic pairs yielded a mean latent distance of $0.2687$, compared to $0.5715$ for random ion pairs, achieving profound statistical significance (Welch's t-test, $p < 10^{-300}$). Of these, 1,353 pairs (97.1\%) passed strict structural validation (Cosine Similarity $\geq 0.80$), including Atropine (*m/z* 290.08) and its $+1$ isotope (*m/z* 291.17) with a cosine similarity of 0.9959. The pipeline was applied identically to the *Datura innoxia* root dataset (2.5 GB, 21,060 pixels, 858 ion images), where all three metrics agree on k = 3 and the segmentation separates the biosynthetic-site domains: tropinone (*m/z* 140.17) and tropine (*m/z* 142.08) are co-localized in one domain, while cuscohygrine (*m/z* 225.92) and atropine/hyoscyamine (*m/z* 290.08) are co-localized in a second domain. Scopolamine is absent from the root ion corpus because the root spectrum is dominated by the biosynthetic precursors (the base peak is tropine, *m/z* 142.08), so the scopolamine channel reaches only 1.5% of the base-peak intensity and falls below the 2% cutoff — consistent with the classical model in which scopolamine is produced in the root but accumulates distally in the shoot [@schlesinger_tropane_2021]. The root result demonstrates that the workflow generalizes across tissues without any parameter change.
# Data and Code Availability # Data and Code Availability
In keeping with the open-science philosophy that motivates this work, all code is released under the MIT License, and every result in this manuscript is reproducible from the repository alone. The GitHub repository at https://github.com/anomalyco/msi-hybrid-workflow contains: (i) the Julia preprocessing engine and Python preprocessing fallback; (ii) the Python SimCLR training, clustering, validation, and visualization scripts; (iii) the benchmark harness used for the Julia-vs-Cardinal-vs-MALDIquant comparison, including the exact measurement protocol (VmRSS via `/proc/self/status`) and raw per-stage measurements for all seven datasets; (iv) pre-trained encoder weights; and (v) a single entry point, \texttt{run\_full\_pipeline.sh}, that reproduces the full analysis from raw imzML to final segmentation. In keeping with the open-science philosophy that motivates this work, all code is released under the MIT License, and every result in this manuscript is reproducible from the repository alone. The GitHub repository at https://github.com/anomalyco/msi-hybrid-workflow contains: (i) the Julia preprocessing engine and Python preprocessing fallback; (ii) the Python SimCLR training, clustering, validation, and visualization scripts; (iii) the benchmark harness used for the Julia-vs-Cardinal-vs-MALDIquant comparison, including the exact measurement protocol (VmRSS via `/proc/self/status`) and raw per-stage measurements for all seven datasets; (iv) pre-trained encoder weights; and (v) a single entry point, `run_full_pipeline.sh`, that reproduces the full analysis from raw imzML to final segmentation.
The complete computational environment is containerized: the Docker image pins the Julia package set, the Python virtual environment, the R/Bioconductor stack, and all system-level dependencies. Building the image and running the container reproduces every figure, table, and quantitative result reported here on any host with Docker, without manual installation or version resolution. All seven benchmark datasets are public: the LD-LTP *Datura* leaf and root, the MALDI San Pedro cactus, the MALDI mouse liver and mouse stomach, the AP-SMALDI mouse bladder, and the DESI human colon datasets, with access instructions in the repository. All raw data, intermediate artifacts, and figures are archived for long-term access. The complete computational environment is containerized: the Docker image pins the Julia package set, the Python virtual environment, the R/Bioconductor stack, and all system-level dependencies. Building the image and running the container reproduces every figure, table, and quantitative result reported here on any host with Docker, without manual installation or version resolution. All seven benchmark datasets are public: the LD-LTP *Datura* leaf and root, the MALDI San Pedro cactus, the MALDI mouse liver and mouse stomach, the AP-SMALDI mouse bladder, and the DESI human colon datasets, with access instructions in the repository. All raw data, intermediate artifacts, and figures are archived for long-term access.