Subir archivos a "/"

This commit is contained in:
2026-09-04 19:42:55 +02:00
parent a2a62e67c3
commit b09bc47c62
+3 -19
View File
@@ -46,7 +46,7 @@ Previous benchmarks support this choice: Julia-based MSI architectures have been
**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 `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.** Mass slices are extracted within a user-defined *m/z* range (e.g., 50.0–700.0 for LD-LTP acquisitions), where the upper limit is determined by the instrument's mass range and the absence of significant signals beyond that threshold. To ensure inclusion of only chemically relevant signals and exclude background noise, a Region of Interest (ROI) mask derived from the optical image is applied when available. The average spectrum is computed exclusively from pixels within the tissue mask, and peaks are filtered using an intensity threshold of 2% relative to the base peak. 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 (e.g., $\sim0.08$–$0.09$ *m/z* per channel for ion trap instruments). The monoisotopic peak of a target analyte $[M+H]^+$ is detected at its corresponding binned channel, which is independently produced by the centroid-based peak-picking engine and corresponds to the same precursor selected for MS/MS structural confirmation. Adjacent bins 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.
@@ -58,23 +58,7 @@ To contextualize the performance of our Julia-based preprocessing within the cur
## Complete Hybrid Pipeline: From imzML to Metabolic Domains
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.
**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 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 2).
**Stage 4: t-SNE visualization.** Latent embeddings are projected to two dimensions and colored by the selected number of clusters (Figure 4).
**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 4).
**Stage 7: Mass spectra.** Mean spectra per cluster and the full average spectrum are plotted for biological interpretation.
In summary, the Julia layer performs all high-throughput binary parsing and image export, while the Python layer performs the representation learning and statistical validation. The design eliminates the traditional "two-language problem" by keeping the expensive preprocessing in a compiled language and the machine learning in the ecosystem where the AI tooling is mature, with a clean, file-based interface (normalized PNG images) between them.
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. In Stage 1, the imzML file is memory-mapped and parsed by the Julia engine, which computes the average spectrum across all pixels (restricted to the ROI mask when available), selects peaks above a 2% threshold of the base peak, extracts an ion image for every detected peak within a 0.05 Da tolerance, applies TrIQ normalization per ion map, spatially standardizes each map to a 256×256 grid by strict zero-padding, and exports each normalized ion image twice: a grayscale PNG reserved exclusively for the deep learning stage, and a viridis-colored PNG for visualization. For imzML variants that the Julia parser rejects, 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. In Stage 2, 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 (SimCLR), projecting each ion map into a 128-dimensional latent space. Stage 3 selects the optimal number of metabolic clusters via a multi-metric sweep (Silhouette, Davies-Bouldin, Calinski-Harabasz) over k = 2,…,20, computed per dataset from the learned latent space. Stage 4 projects latent embeddings to two dimensions via t-SNE for visualization. Stage 5 validates the clustering by testing spatial co-localization of isotopologue pairs against random ion pairs (Welch's t-test) and against a PCA baseline, including stability analysis via Adjusted Rand Index across seeds. Stage 6 assembles representative ion images per cluster to visually confirm anatomical domains, and Stage 7 plots mean spectra per cluster and the full average spectrum for biological interpretation. In summary, the Julia layer performs all high-throughput binary parsing and image export, while the Python layer performs representation learning and statistical validation. The design eliminates the traditional "two-language problem" by keeping the expensive preprocessing in a compiled language and the machine learning in the ecosystem where the AI tooling is mature, with a clean, file-based interface (normalized PNG images) between them.
## Self-Supervised Representation Learning (Python)
@@ -86,7 +70,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 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.
**Problem 4: dataset sizes are moderate but augmentation makes them effectively infinite.** The training corpus typically comprises hundreds to thousands of ion images that pass the 2% intensity threshold filter and ROI mask selection (e.g., 1,596 for the *Datura* leaf, 858 for the root, 775 for San Pedro). 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.