Compare commits

12 Commits
92 changed files with 13383 additions and 63783 deletions
+15
View File
@@ -0,0 +1,15 @@
.git
.gitignore
.dockerignore
ai_data
outputs
models.zip
figures
venv
*.pdf
*.aux
*.bbl
*.blg
*.log
*.out
*.toc
+5 -2
View File
@@ -2,8 +2,11 @@ data/Leaf.imzML
data/Leaf.ibd data/Leaf.ibd
data/Leaf.imzML.cache data/Leaf.imzML.cache
JuliaMSI/ JuliaMSI/
environment/Manifest.toml # environment/Manifest.toml is intentionally tracked (reproducible Julia lock)
datos_para_ai/* ai_data/*
outputs/
venv/
.ipynb_checkpoints/
# LaTeX build files # LaTeX build files
*.aux *.aux
-30
View File
@@ -1,30 +0,0 @@
# Digital Object Identifiers (DOIs) of Cited Articles
- MALDI imaging mass spectrometry: statistical data analysis and current computational challenges (2012) — <https://doi.org/10.1186/1471-2105-13-S16-S11>
- Cardinal: an R package for statistical analysis of mass spectrometry-based imaging experiments (2015) — <https://doi.org/10.1093/bioinformatics/btv146>
- Identification of Plant Compounds with Mass Spectrometry Imaging (MSI) (2024) — <https://doi.org/10.3390/metabo14080419>
- MALDIquant: a versatile R package for the analysis of mass spectrometry data (2012) — <https://doi.org/10.1093/bioinformatics/bts447>
- Balancing sufficiency and impact in reporting standards for mass spectrometry imaging experiments (2018) — <https://doi.org/10.1093/gigascience/giy102>
- Low-Temperature Plasma Probe for Ambient Desorption Ionization (2008) — <https://doi.org/10.1021/ac801641a>
- Spherical k-Means Clustering (2012) — <https://doi.org/10.18637/jss.v050.i10>
- DeepION: A Deep Learning-Based Framework for Mass Spectrometry Imaging Data Analysis (2021) — <https://doi.org/10.48550/ARXIV.2106.01582>
- Gradient Accumulation for Large Batch Training (2025) — <https://huggingface.co/docs/transformers/training#gradient-accumulation>
- REFORMS: Consensus-based Recommendations for Machine-learning-based Science (2024) — <https://doi.org/10.1126/sciadv.adk3452>
- Low-temperature plasma (LTP) jets for mass spectrometry (MS): Ion processes, instrumental set-ups, and application examples (2017) — <https://doi.org/10.1016/j.trac.2017.01.013>
- Visualizing structure and transitions in high-dimensional biological data (2019) — <https://doi.org/10.1038/s41587-019-0336-3>
- Elucidating the Distribution of Plant Metabolites from Native Tissues with Laser Desorption Low-Temperature Plasma Mass Spectrometry Imaging (2019) — <https://doi.org/10.1021/acs.analchem.8b04406>
- Benchmark datasets for 3D MALDI- and DESI-imaging mass spectrometry (2015) — <https://doi.org/10.1186/s13742-015-0059-4>
- PyTorch: An Imperative Style, High-Performance Deep Learning Library (2019) — <https://doi.org/10.48550/ARXIV.1912.01703>
- Laser Desorption Low-Temperature Plasma Mass Spectrometry Imaging (LD-LTP MSI) of San Pedro cactus (2020) — <https://doi.org/10.5281/zenodo.3625054>
- Histology by Mass Spectrometry: Label-Free Tissue Characterization Obtained from High-Accuracy Bioanalytical Imaging (2010) — <https://doi.org/10.1002/anie.200905559>
- ProteomeXchange Dataset PXD001283 (2014) — <http://proteomecentral.proteomexchange.org/cgi/GetDataset?ID=PXD001283>
- Contrast optimization of mass spectrometry imaging (MSI) data visualization by threshold intensity quantization (TrIQ) (2021) — <https://doi.org/10.7717/peerj-cs.585>
- Open LabBot and RmsiGUI: Community development kit for sampling automation and ambient imaging (2020) — <https://doi.org/10.1016/j.microc.2019.104343>
- Technical Note: mzML and imzML Libraries for Processing Mass Spectrometry Data with the High-Performance Programming Language Julia (2024) — <https://doi.org/10.1021/acs.analchem.3c05853>
- Tropane alkaloid biosynthesis in Datura innoxia Mill. roots and their differential transport to shoots (2021) — <https://doi.org/10.1016/j.phytol.2021.04.012>
- imzML — A common data format for the flexible exchange and processing of mass spectrometry imaging data (2012) — <https://doi.org/10.1016/j.jprot.2012.07.026>
- MSInet: A Self-Supervised CNN Framework Integrating Global and Local Context for Robust Mass Spectrometry Imaging Segmentation (2025) — <https://doi.org/10.1021/acs.analchem.5c04885>
- JuliaMSI: A high-performance graphical platform for mass spectrometry imaging data analysis (2025) — <https://doi.org/10.1016/j.aca.2025.344613>
- EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (2019) — <https://doi.org/10.48550/ARXIV.1905.11946>
- SMART: A data reporting standard for mass spectrometry imaging (2023) — <https://doi.org/10.1002/jms.4904>
- Alkaloid Biosynthesis: Metabolism and Trafficking (2008) — <https://doi.org/10.1146/annurev.arplant.59.032607.092730>
+11 -5
View File
@@ -1,4 +1,6 @@
FROM nvidia/cuda:12.4.1-runtime-ubuntu22.04 # Fully-qualified base image (docker.io/...) so Podman/Buildah never prompts for a
# short-name registry. See "Troubleshooting" in README.md.
FROM docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04
ENV DEBIAN_FRONTEND=noninteractive ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=UTC ENV TZ=UTC
@@ -18,9 +20,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# ============================================================ # ============================================================
# Julia 1.12 (pins the Manifest.jl julia_version = "1.12.6") # Julia 1.11 (matches environment/Manifest.toml julia_version = "1.11.7")
# ============================================================ # ============================================================
RUN curl -fsSL https://julialang-s3.julialang.org/bin/linux/x64/1.12/julia-1.12.6-linux-x86_64.tar.gz \ RUN curl -fsSL https://julialang-s3.julialang.org/bin/linux/x64/1.11/julia-1.11.7-linux-x86_64.tar.gz \
| tar -xz -C /usr/local --strip-components=1 | tar -xz -C /usr/local --strip-components=1
# ============================================================ # ============================================================
@@ -40,12 +42,16 @@ COPY . .
# ============================================================ # ============================================================
# Julia environment # Julia environment
# ============================================================ # ============================================================
RUN julia --project=/app/environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate(); Pkg.precompile()' # Instantiate from the committed Manifest.toml (no resolve: the lock is complete,
# and resolving against a fresh registry is fragile). No explicit precompile:
# GLMakie is a GUI-only dependency that fails to precompile headlessly, but the
# pipeline never loads it, so it must not fail the build.
RUN julia --project=/app/environment -e 'using Pkg; Pkg.instantiate()'
# ============================================================ # ============================================================
# Environment variables # Environment variables
# ============================================================ # ============================================================
ENV PYTHONPATH="/app/scripts/python:${PYTHONPATH}" ENV PYTHONPATH="/app/scripts_python:${PYTHONPATH}"
ENV DISPLAY=:99 ENV DISPLAY=:99
LABEL maintainer="MSI Julia-Python CNN" LABEL maintainer="MSI Julia-Python CNN"
+60
View File
@@ -0,0 +1,60 @@
# Fully-qualified base image (docker.io/...) so Podman/Buildah never prompts for a
# short-name registry. See "Troubleshooting" in README.md.
FROM docker.io/library/ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=UTC
SHELL ["/bin/bash", "-c"]
# ============================================================
# System dependencies
# ============================================================
RUN apt-get update && apt-get install -y --no-install-recommends \
wget curl ca-certificates gnupg \
python3 python3-pip python3-venv \
git build-essential gfortran \
zlib1g-dev libpng-dev libjpeg-dev libfreetype6-dev \
xvfb libgl1-mesa-glx libglfw3 \
libxrandr2 libxinerama1 libxcursor1 libxi6 \
libssl-dev libcurl4-openssl-dev libxml2-dev \
&& rm -rf /var/lib/apt/lists/*
# ============================================================
# Julia 1.11 (matches environment/Manifest.toml julia_version = "1.11.7")
# ============================================================
RUN curl -fsSL https://julialang-s3.julialang.org/bin/linux/x64/1.11/julia-1.11.7-linux-x86_64.tar.gz \
| tar -xz -C /usr/local --strip-components=1
# ============================================================
# Python ML packages (CPU build)
# ============================================================
RUN pip3 install --no-cache-dir \
torch torchvision --index-url https://download.pytorch.org/whl/cpu \
&& pip3 install --no-cache-dir \
Pillow numpy scikit-learn matplotlib pandas scipy psutil plotly
# ============================================================
# Project code
# ============================================================
WORKDIR /app
COPY . .
# ============================================================
# Julia environment
# ============================================================
# Instantiate from the committed Manifest.toml (no resolve: the lock is complete,
# and resolving against a fresh registry is fragile). No explicit precompile:
# GLMakie is a GUI-only dependency that fails to precompile headlessly, but the
# pipeline never loads it, so it must not fail the build.
RUN julia --project=/app/environment -e 'using Pkg; Pkg.instantiate()'
# ============================================================
# Environment variables
# ============================================================
ENV PYTHONPATH="/app/scripts_python:${PYTHONPATH}"
ENV DISPLAY=:99
LABEL maintainer="MSI Julia-Python CNN"
LABEL description="Julia preprocessing + Python SimCLR - MSI CNN Pipeline (CPU)"
CMD ["/bin/bash"]
-214
View File
@@ -1,214 +0,0 @@
---
title: "A scalable deep learning workflow for mass spectrometry imaging: benchmarking Julia-Python hybrid processing across multi-instrument datasets"
bibliography: zotero.bib
abstract: |
Mass spectrometry imaging (MSI) generates terabyte-scale datasets whose analysis is increasingly bottlenecked by software rather than instrumentation. Most MSI processing pipelines are written in interpreted languages whose memory and speed limits scale poorly with next-generation instruments, and the deep learning ecosystem needed for modern unsupervised analysis lives almost entirely in Python. We present an open-source hybrid Julia-Python workflow that resolves this: a Julia engine performs all high-throughput preprocessing (memory-mapped imzML parsing, peak picking, ion image extraction, TrIQ normalization, and PNG export of every ion map in a single pass) and hands a clean, file-based corpus to a Python self-supervised (SimCLR) convolutional encoder for representation learning and clustering. We benchmark the Julia preprocessing stage on an equalized per-stage workload (imzML load and one ion slice generation at each dataset's reference *m/z*) against Cardinal (R/Bioconductor) and MALDIquant (R) on seven public datasets spanning 0.61–4.4 GB (LD-LTP, AP-SMALDI, MALDI, DESI), covering both centroid and profile acquisitions. Under this equalized workload, the Julia engine generates an ion slice up to two orders of magnitude faster than Cardinal on every dataset and materially faster than MALDIquant, while its memory-mapped loader keeps peak load RAM at only 7–84 MB (lower than Cardinal's lazy loader on all seven datasets) and it completes the additional normalization and export steps within the same memory envelope, all orchestrated by a single reproducible entry point. The Python layer learns a 128-dimensional latent space from the exported ion corpus and clusters the ions into spatially coherent metabolic domains; we detail the algorithmic choices (Group Normalization, gradient accumulation for consumer GPUs, chemical-noise augmentation, and spherical K-Means) that make the deep learning stage tractable on big, zero-padded MSI data. The complete environment is containerized with Docker and released under a permissive license, so the entire analysis (from raw imzML to trained embeddings) is fully reproducible on any hardware. As a demonstration of the workflow's biological utility, we apply it to *Datura innoxia* leaves and roots (2.0 GB and 2.5 GB): self-supervised segmentation recovers spatially coherent metabolic domains that resolve the tropane alkaloid biosynthetic and transport architecture of the tissue.
keywords: mass spectrometry imaging, Julia, Python, SimCLR, hybrid pipeline
---
# Introduction
Mass spectrometry imaging (MSI) produces spatially resolved molecular maps of biological tissue, and advances in ionization sources and mass analyzers have made it possible to record these maps routinely at increasingly fine spatial resolution and mass range. The consequence is a software bottleneck: a single high-resolution acquisition can generate datasets of tens to thousands of gigabytes, and next-generation instruments push the burden of analysis onto the compute stack rather than the instrumentation itself [@alexandrov_maldi_2012]. Most established MSI tooling (both commercial and academic) is written in interpreted languages whose parsing speed, peak RAM consumption, and scalability degrade as file sizes grow into the multi-gigabyte range [@rosas-roman_technical_2024]. Meanwhile, the deep learning ecosystem needed for modern unsupervised analysis of ion images lives almost entirely in Python. At the heart of current MSI software engineering lies the problem: no single ecosystem offers both the throughput required for high-performance binary ingestion and the machine learning maturity required for representation learning.
We address this problem with an open-source hybrid Julia-Python workflow. Julia combines execution speeds comparable to compiled languages with a scientific computing environment [@rosas-roman_open_2020], making it well suited to the memory-mapped parsing and high-throughput ion image extraction that dominate MSI preprocessing; Python contributes the mature artificial intelligence stack (PyTorch) that the representation learning stage requires [@paszke_pytorch_2019]. The two layers are separated by a clean, file-based interface: Julia ingests the raw imzML [@schramm_imzml_2012] binary files, extracts and normalizes every ion image, and exports a deep-learning-ready corpus, which Python consumes for self-supervised learning and clustering. Because the entire pipeline is containerized and released under a permissive license, the full analysis (from raw binary data to trained embeddings) is reproducible on any hardware with the container image alone, which pins every package version and removes manual installation and dependency resolution.
The central objective of this paper is to show how this architecture scales with the two dimensions that dominate modern MSI data: file size and ion count. To evaluate the design honestly, we benchmark the Julia preprocessing stage against Cardinal 3.14.0 [@bemis_cardinal_2015], the standard R/Bioconductor MSI package, and MALDIquant [@gibb_maldiquant:_2012], a widely used R package for MALDI spectra processing, across seven public datasets spanning 0.61–4.4 GB from multiple ionization platforms (LD-LTP, AP-SMALDI, MALDI, DESI) and biological matrices, in both centroid and profile acquisition modes. All three tools run the identical per-stage workload (load, average spectrum, peak detection, ion extraction) on the same hardware, and we report memory and wall-clock transparently, including where the R-based tools are superior. We then describe the algorithmic core of the deep learning stage in detail (the contrastive (SimCLR) objective, the Group-Normalized fully convolutional encoder, gradient accumulation for consumer GPUs, chemical-noise augmentation, and spherical K-Means) and explain how these choices keep a big-data representation-learning workload tractable in RAM and on consumer hardware. As a demonstration of the workflow's biological utility, we apply it to a leaf and root of *Datura innoxia*, a medicinal plant rich in tropane alkaloids [@schlesinger_tropane_2021], and interpret the recovered metabolic domains in terms of alkaloid biosynthesis and transport [@ziegler_alkaloid_2008; @garcia-rojas_identification_2024]. The remainder of this paper details the acquisition parameters, the hybrid implementation, the multi-dataset benchmark, the deep learning workflow, and the unsupervised segmentation of the demonstration datasets.
# Materials and Methods
## 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.61–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 and was processed without a mask, is an LD-LTP MSI dataset from *Echinopsis pachanoi* cactus stem cross-section (Moreno-Pedraza et al., 2019, Anal. Chem. 10.1021/acs.analchem.8b04406). Peaks were then filtered using the default intensity threshold of 2\% of the base peak.
**Table 1.** Benchmark datasets used in this study.
| Dataset | Ionization | Mass Analyzer | Organism | File Size | Pixels | Polarity | Spatial Res. (µm) | Spectrum Type |
|---------|------------|---------------|----------|-----------|--------|----------|-------------------|---------------|
| Datura Leaf | LD-LTP | Ion Trap (LCQ-Fleet) | *D. innoxia* | 2.0 GB | 17,066 | Positive | 100 | Profile |
| Datura Root | LD-LTP | Ion Trap (LCQ-Fleet) | *D. innoxia* | 2.5 GB | 21,060 | Positive | 100 | Profile |
| San Pedro | LD-LTP | Ion Trap (LCQ-Fleet) | *E. pachanoi* | 1.1 GB | 19,072 | Positive | 300 | Profile |
| Mouse bladder | AP-SMALDI | Orbitrap | *M. musculus* | 833 MB | 34,860 | Positive | 10 | Centroid |
| Human colon | DESI | Orbitrap | *H. sapiens* | 610 MB | 4,288 | Negative | 100 | Centroid |
| Mouse liver | MALDI (neoFlex) | TOF | *M. musculus* | 2.2 GB | 28,587 | Positive | 20 | Profile |
| Mouse stomach | MALDI (neoFlex) | TOF | *M. musculus* | 4.4 GB | 54,245 | Positive | 20 | Profile |
## Computational Environment and Reproducibility
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 (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)
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.
**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.
**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.
**Spatial standardization (pristine coordinate mapping).** To ensure compatibility with the deep learning backbone, each normalized ion map was spatially embedded into a standardized 256 $\times$ 256 pixel matrix using strict Zero-Padding, completely avoiding any sub-pixel interpolation. In MSI, the physical laser ablation grid (the native pixel dimensions, e.g., $161 \times 106$ for the *Datura* leaf or $351 \times 60$ for the root) serves as an absolute spatial ground truth. Standard computational interpolation (such as bilinear resizing) forces anisotropic stretching (disproportionately warping the tissue morphology) and introduces artificial floating-point values at the sharp boundaries of the tissue mask. By mapping the raw pixel coordinates directly into the center of a zero-matrix, we preserved the true, undistorted anatomical geometry of each sample while achieving the uniform dimensionality required by the convolutional layers.
## Multi-Dataset Benchmark: Julia-Python vs Cardinal (R) and MALDIquant (R)
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 212.14 for San Pedro (mescaline [M+H]⁺, LD-LTP reference ion [@moreno-pedraza_elucidating_2019]); 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.
## 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.
## Self-Supervised Representation Learning (Python)
We implemented a Contrastive Learning (SimCLR) scheme in PyTorch [@paszke_pytorch_2019], adapting the framework to the unique properties of mass spectrometry imaging. 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 2: consumer GPU memory is insufficient for large batches.** To enable training on consumer-grade hardware (NVIDIA RTX 2060 / RTX 3050 Mobile, 4–6 GB VRAM), a gradient accumulation strategy was employed. Rather than fitting an effective batch of 32 images simultaneously into GPU memory (which would trigger a CUDA out-of-memory error), the engine processes 8 images physically per step and accumulates gradients over 4 consecutive forward passes before executing a single optimizer update, as described in the Hugging Face documentation [@huggingface_gradient_2025]. This is mathematically equivalent to training with a true batch size of 32 while using only a quarter of the VRAM.
**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.
**Table 2.** Training hyperparameters and model configuration for the SimCLR-MSI workflow.
| Parameter | Value / Configuration |
|-----------|------------------------|
| Backbone Architecture | Custom 4-Layer CNN with Group Normalization |
| Projection Head | 2-layer MLP (Linear 256-ReLU-Linear 128) |
| Input Image Resolution | 256 × 256 pixels (Zero-Padded) |
| Optimization Algorithm | AdamW Optimizer |
| Learning Rate | $3 \times 10^{-4}$ with Cosine Annealing |
| Physical Batch Size / Accumulation Steps | 8 / 4 (Effective Batch Size: 32) |
| Temperature ($\tau$) | 0.5 (NT-Xent Loss) |
| Training Duration | 60 Epochs |
| Data Augmentations | Intensity Scaling (0.8×–1.2×), Poisson Shot Noise, Low-Signal Dropout |
**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 2 and discussed in the section "Clustering Validation Across the Seven Datasets".
## Application Dataset: LD-LTP-MSI of *Datura innoxia*
To demonstrate the biological utility of the workflow, we acquired an MSI dataset from a *Datura innoxia* leaf, a medicinal plant whose root-biosynthesized tropane alkaloids are transported to the shoot [@schlesinger_tropane_2021], and whose imaging has previously been pursued with laser desorption low-temperature plasma (LD-LTP) techniques [@moreno-pedraza_elucidating_2019]. We performed imaging using an LD-LTP-MSI system coupled to an LCQ Fleet Ion Trap mass spectrometer (Thermo Scientific). The custom ionization source consisted of a Low-Temperature Plasma (LTP) probe [@harper_low-temperature_2008] and a continuous-wave violet laser (400–450 nm, 1.0 W). The LTP probe was operated with helium (0.1 L/min) at 3.3 kV and ~13 kHz, positioned at a 45° angle and 4 mm from the ion transfer capillary [@martinez-jarquin_low-temperature_2017]. The laser was oriented at 90° to the sample surface at a focal distance of 9 cm, producing a spot size of ~22 µm. We acquired data in positive ion mode (*m/z* 50–700) with a spatial resolution of 150 µm for the leaf sample.
## Benchmark Dataset: LD-LTP-MSI of San Pedro Cactus (*Echinopsis pachanoi*)
The San Pedro cactus (1.1 GB) dataset was acquired using the same LD-LTP-MSI platform described in Moreno-Pedraza et al. [@moreno-pedraza_elucidating_2019] at CINVESTAV Irapuato. A cactus cross-section (41.70 × 42.00 mm², 2.5 cm thick) was dissected with a scalpel, cleaned with a paper towel, and a wet filter paper was placed underneath to avoid dehydration during analysis. The LD-LTP system used a CW 405 nm UV diode laser (Fermion III Series, Micro Laser Systems Inc., up to 450 mW output) with a plano-convex lens (f = 50 mm) focused perpendicular to the sample, and a 3D-printed LTP probe operated at 0.1 L/min helium, 7 kV, 10 kHz, positioned at 45° and 2 mm from the MS inlet. An LCQ-Fleet ion trap MS (Thermo Scientific) was used in positive mode, *m/z* 50–500, full scan continuous mode (capillary voltage 55 V, capillary temperature 200 °C, tube lens 25 V, max injection time 300 ms, 2 microscans, AGC enabled). Imaging was performed with a RepRap-based stage in a meandering pattern at 300 × 300 µm step width (pixel size), acquiring 19,072 pixels over 164 min. Laser intensity was set to 317.86 MW cm⁻². Mescaline was detected at *m/z* 212.14 [M+H]⁺ and confirmed by MS² fragmentation and GC/EIMS of dissected chlorenchyma/parenchyma.
## Benchmark Datasets: MALDI-TOF MSI of Mouse Liver and Stomach on Bruker neoFlex
The mouse liver (2.2 GB) and mouse stomach (4.4 GB) datasets were acquired on a Bruker neoFlex MALDI-TOF mass spectrometer (Bruker Daltonics) at the Biomolecular Analysis Facility Core, W.M. Keck Biomedical Mass Spectrometry Laboratory, University of Virginia School of Medicine. Liver and stomach tissues were obtained from mice and, after being washed with 1× PBS, were embedded in a mold with 20% fish gelatin and frozen on dry ice. They were subsequently transferred to −20 °C for one hour and stored at −80 °C until use. Sectioning was performed on a microtome cryostat equipped with a blade holder (Epredia CryoStar NX50 OP 957250), and the sections were carefully mounted using a fine paintbrush to pull the tissues onto an Intelligent Slide previously cooled to −15 °C.
The DHB matrix (2,5-dihydroxybenzoic acid) was applied to both tissues using the Bruker method on an HTX Imaging M3+ Sprayer. Briefly, the method consists of dissolving 15 mg/mL of DHB in 90% ACN / 0.1% TFA, with a flow rate of 125 µL/min, 14 passes in a criss-cross pattern, and a pressure of 10 psi. Subsequently, the slides were dried in a vacuum desiccator for 40 minutes before data acquisition on the neoFlex.
The parameters used on the neoFlex for data acquisition were as follows:
- Laser power: 35%
- Laser shots per pixel: 2000
- Laser frequency: 10,000 Hz
- Acquisition mode: Reflector
- Polarity: Positive
- Mass range: 400–1400 *m/z*
- Spatial resolution: 20 µm
- External calibration: Red phosphorus using the Bruker method RedP_Positive_0_to_2000
- Acquisition method: Bruker Imaging_Lipids_pos_R.par
# Results and Discussion
## Computational Benchmark: Julia vs Cardinal and MALDIquant Across Seven Datasets
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 an order of magnitude in file size (0.61–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 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 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.
## Clustering Validation Across the Seven Datasets
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.
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 (610 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.
**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.
![Figure 1: Benchmark of JuliaMSI vs Cardinal and MALDIquant.](figure1.png){width=16cm}
**Figure 2.** Clustering validation of the two *Datura innoxia* demonstration datasets via K-sweep (k = 2–20). Panels A–D show the *Datura* leaf; panels E–H show the *Datura* root. (A, E) Elbow method (inertia); (B, F) Silhouette score; (C, G) Davies-Bouldin index; (D, H) 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.
![Figure 2: K-sweep clustering validation for the Datura leaf (A–D) and root (E–H).](figure2.png){width=16cm}
## *Datura innoxia* Ion Image Gallery
**Figure 3.** Ion images of key tropane alkaloids and precursors in *Datura innoxia*. (A) *Datura* leaf: photograph with 1 cm scale bar, followed by ion slices of scopolamine (*m/z* 304.17), atropine/hyoscyamine (*m/z* 290.08), cuscohygrine (*m/z* 225.92), 6-hydroxyhyoscyamine (*m/z* 306.25), tropine (*m/z* 142.08), and tropinone (*m/z* 140.17). (B) *Datura* root: photograph with 5 mm scale bar, followed by ion slices of atropine/hyoscyamine (*m/z* 290.08), tropanone (*m/z* 140.17), tropine (*m/z* 142.08), and cuscohygrine (*m/z* 225.92). All ion images are TrIQ-normalized, zero-padded to 256 × 256, and displayed with the viridis colormap.
![Figure 3: Datura leaf and root photographs and key ion images.](figure3.png){width=16cm}
## Multi-Dataset Unsupervised Segmentation
The segmentations of the two most architecturally demanding benchmark tissues are shown in Figure 4: the learned 128-dimensional embeddings projected with t-SNE and colored by the K-Means assignment at each dataset's adopted K, alongside biologically interpretable ion images from distinct metabolic domains 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 display the clearly separated, tissue-specific cluster geometries discussed below (circular arrangements for the bladder and colon) confirming that the recovered clusters are discrete metabolic compartments rather than arbitrary bands of a continuum.
**Figure 4.** 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 biologically interpretable ion images (viridis, putative compound and adduct) from four distinct metabolic domains of each tissue (the sphingomyelin SM(34:1) (d18:1/16:0, [M+H]+ and [M+Na]+), the phosphatidylcholine PC(34:1), and the reference phospholipid for the bladder; the phosphatidylinositols PI(38:4) (18:0/20:4) and PI(36:2), the phosphatidylglycerol PG(34:1), and the phosphatidylserine PS(36:1) (18:0/18:1) for the colon) 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.
![Figure 4: t-SNE segmentations and representative ion images for the mouse bladder and human colon.](figure4.png){width=16cm}
The recovered domains are not only computationally validated but also biologically interpretable in every benchmark tissue, without any tissue-specific tuning. In the San Pedro cactus stem (*Echinopsis pachanoi*), the joint Davies-Bouldin/Calinski-Harabasz optimum selects k = 2, partitioning the 775-ion corpus into two metabolic domains (Clusters 0 and 1, with 358 and 417 ions, respectively). The cactus stem is anatomically organized as a two-compartment structure (the photosynthetically active cortex with the underlying vascular system and the inner water-storage pith) and the mescaline region (m/z ≈ 212.1) falls in Cluster 0, consistent with the star-like mescaline distribution around the vascular bundles originally reported for this specimen [@robert_winkler_laser_2020; @moreno-pedraza_elucidating_2019]. This star-like patterning, where mescaline concentrates around vascular bundles in the cortical region, reflects the plant's metabolic zonation and has been previously documented in the literature [@moreno-pedraza_elucidating_2019]. In the mouse liver (MALDI-TOF), the k = 7–8 optimum resolves the lobular architecture of hepatic zonation, in which periportal and pericentral hepatocytes differ in their metabolic programs, and the reference ion at m/z 796.18 is placed in Cluster 2. The mouse stomach (MALDI-TOF, DHB matrix) is segmented into k = 12 domains, consistent with the regional organization of the gastric mucosa (forestomach, corpus, and antrum) with the reference ion m/z 804.3 distributed between Clusters 7 and 10. For the two high-resolution benchmark specimens, the workflow resolves 20 domains each. In the mouse urinary bladder (AP-SMALDI [@rompp_histology_2010; @rompp_proteomexchange_2014]), the domains follow the layered histology of the bladder wall (urothelium, lamina propria, detrusor muscle), and the reference phospholipid at m/z 716.05 falls in Cluster 4. In the human colorectal adenocarcinoma (DESI [@oetjen_benchmark_2015]), the 20 domains recover the molecular heterogeneity of the tumor and its surrounding stroma, and the anion at m/z 885.55 (consistent with the glycerophospholipid PI(18:0/20:4) signature commonly observed in malignant colon epithelium) is confined to Cluster 2.
### Interpreting the t-SNE Embedding Shapes
Reviewers from a computer vision background may expect an optimal unsupervised result to yield discrete, well-separated "blobs" in the t-SNE projection (and this is exactly what the workflow produces on all seven datasets). The K-Means domains appear as clearly separated, self-contained groups in every projection, with no overlapping or interleaved clusters, so the discretization into metabolic domains does not depend on any arbitrary threshold along a continuous gradient. Beyond this clean separation, each tissue imprints a characteristic global geometry onto its learned embedding, and these shapes are consistent and reproducible: the human colon and the mouse bladder organize into closed, roughly circular arrangements; the *Datura* leaf resolves into a donut-shaped (annular) structure; the mouse liver, the *Datura* root, and the San Pedro cactus fold into ear-shaped configurations; and the mouse stomach extends into an elongated, fish-shaped topology. Because the same encoder and the same K-selection logic were applied to every sample, these consistent, dataset-specific geometries indicate that the contrastive stage captures genuine tissue-level structure rather than dataset-specific artifacts [@moon_visualizing_2019]. The application of K-Means onto each of these well-separated manifolds is therefore interpreted as the identification of independent, biologically meaningful chemical compartments, not as the arbitrary banding of an amorphous continuum.
## Advantages of Contrastive Learning over Linear Decomposition
Furthermore, the superiority of the self-supervised contrastive learning approach over traditional linear methods, such as Principal Component Analysis (PCA), lies in its fundamental shift from intensity-driven variance to morphological feature extraction [@shah_msinet_2025]. To establish a fair quantitative baseline, we compared SimCLR and PCA embeddings under identical conditions: both feature sets were projected to the same dimensionality via PCA and clustered using standard k-means at the pipeline-selected k. For the leaf (k = 5), the SimCLR pipeline achieved a Silhouette Score of 0.3703, compared to the PCA baseline of 0.1641, while the Calinski-Harabasz Index rose from 351.56 to 1304.29. The Davies-Bouldin Index for SimCLR was 0.9124 versus 1.7096 for PCA, confirming that the combination of contrastive feature learning produces substantial improvements in spatial separation. Furthermore, the SimCLR embeddings exhibited exceptional stability across multiple random seeds, with a mean Silhouette Score of 0.3703 $\pm$ 0.0000 and an Adjusted Rand Index (ARI) of 0.9959 between runs, indicating that the learned representations are highly reproducible and independent of stochastic initialization. The same superiority holds for the root at its pipeline-selected k = 3 (Silhouette 0.4716 vs 0.2871; Davies-Bouldin 0.8518 vs 1.2417; Calinski-Harabasz 868.21 vs 626.25; mean Silhouette 0.4716 $\pm$ 0.0000; ARI 1.0000), showing that the advantage is not specific to a single tissue.
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.
## Case Study: *Datura innoxia* Segmentation
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 (Figure 3A). 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 `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 reflects the longitudinal architecture of the root rather than a single biosynthetic site (Figure 3B). The three recovered domains differ in their spatial polarity: Cluster 2 (the largest domain, 351 ions) concentrates its ion presence close to the stem junction; Cluster 1 is enriched at the root apex and markedly weaker at the stem connection; and Cluster 0 combines both features, presenting signal both at the root apex and at the stem junction. These domains partition the alkaloid biosynthetic machinery accordingly: tropinone (*m/z* 140.17) and tropine (*m/z* 142.08) fall in Cluster 0, the both-zones domain, while cuscohygrine (*m/z* 225.92) and atropine/hyoscyamine (*m/z* 290.08) fall in Cluster 1, the apex-enriched 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
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.
# Funding
This work was supported by the University of Virginia's School of Medicine grant to the Biomolecular Analysis Facility Core and W.M. Keck Biomedical Mass Spectrometry Laboratory (RRID:SCR_025476).
# Conclusion
The equalized benchmark against Cardinal (R/Bioconductor) and MALDIquant (R) (identical per-stage workloads on the same hardware across seven public datasets spanning 0.61 to 4.4 GB) shows that the Julia engine generates ion slices one to two orders of magnitude faster than Cardinal on every dataset (0.00009–0.32 s vs 6.3–19.5 s, 54- to 79,949-fold) while keeping peak load resident memory (VmRSS) at 7–84 MB (lower than Cardinal's ~120 MB and far below MALDIquant's up to 4.0 GB) and it completes the additional normalization and export steps within the same memory envelope. We report the per-stage timings transparently, including where the R ecosystem is competitive (Cardinal's eager load is faster in wall time on the larger files), and we note that MALDIquant exhausted the reference machine on the two heaviest datasets. This decoupling of peak RAM from on-disk file size is what makes the workflow scale from commodity laptops to GPU-equipped workstations, and the containerized environment and permissive open-source license allow any researcher to rebuild the entire analysis (from raw imzML to trained embeddings and final segmentation) on any hardware.
On the deep learning side, we have shown how the Python stage is engineered for big, zero-padded MSI data: Group Normalization to neutralize the background mask, gradient accumulation to fit large effective batches on consumer GPUs, chemical-noise-only augmentation to preserve the spatial co-localization signal, and spherical K-Means to respect the latent hypersphere geometry. Applied across all seven benchmark datasets, the workflow selects its own number of metabolic domains per tissue, systematically outperforms a PCA baseline, and produces stable, biologically coherent segmentations. As a demonstration of biological utility, application to *Datura innoxia* recovered five spatially coherent metabolic domains in the leaf and three in the root, resolving the spatial organization of tropane alkaloid metabolism without manual annotation: the leaf co-localizes the full scopolamine envelope with atropine/hyoscyamine and 6-hydroxyhyoscyamine in a single transport domain, with the precursors tropinone, tropine, and cuscohygrine compartmentalized in three separate domains. Together, the computational benchmark, the algorithmic treatment of the deep learning stage, and the containerized reproducibility establish the workflow as a scalable, democratized foundation for MSI analysis (lowering the memory and setup barriers that currently gate the analysis of next-generation imaging datasets).
# Acknowledgments
We thank Dr. Nicholas E. Sherman, Dr. Ana Oliveira, and Yulica Santos Ortega for providing the mouse liver (2.2 GB) and mouse stomach (4.4 GB) imaging datasets. The datasets were generated at the Biomolecular Analysis Facility Core, W.M. Keck Biomedical Mass Spectrometry Laboratory, University of Virginia School of Medicine, Charlottesville, VA. This facility is funded by a grant from the University of Virginia's School of Medicine (RRID:SCR_025476). All investigators are asked to acknowledge the Biomolecular Analysis Facility Core and W.M. Keck Biomedical Mass Spectrometry Laboratory personnel and funding sources in any publications using these data.
+24 -10
View File
@@ -1,8 +1,11 @@
.PHONY: build build-cpu run run-cpu shell shell-cpu \ .PHONY: build build-cpu run run-cpu run-gpu shell shell-cpu \
pipeline run-dataset \ pipeline run-dataset run-dataset-cpu run-dataset-gpu \
step1 step2 step3 step4 step5 step6 step7 \ step1 step2 step3 step4 step5 step6 step7 \
plot-spectra clean clean-all plot-spectra clean clean-all
# Opt-in NVIDIA GPU: layer the override file (see README "Troubleshooting").
GPU_COMPOSE = docker compose -f docker-compose.yml -f docker-compose.gpu.yml
# ============================================================ # ============================================================
# Build # Build
# ============================================================ # ============================================================
@@ -21,6 +24,9 @@ run:
run-cpu: run-cpu:
docker compose run --rm msi-pipeline-cpu bash run_full_pipeline.sh docker compose run --rm msi-pipeline-cpu bash run_full_pipeline.sh
run-gpu:
$(GPU_COMPOSE) run --rm msi-pipeline-gpu bash run_full_pipeline.sh
# ============================================================ # ============================================================
# Run single dataset # Run single dataset
# ============================================================ # ============================================================
@@ -28,6 +34,14 @@ run-dataset:
@if [ -z "$(D)" ]; then echo "Usage: make run-dataset D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make run-dataset D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu bash run_full_pipeline.sh $(D) docker compose run --rm msi-pipeline-gpu bash run_full_pipeline.sh $(D)
run-dataset-cpu:
@if [ -z "$(D)" ]; then echo "Usage: make run-dataset-cpu D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-cpu bash run_full_pipeline.sh $(D)
run-dataset-gpu:
@if [ -z "$(D)" ]; then echo "Usage: make run-dataset-gpu D=Datura_leaf"; exit 1; fi
$(GPU_COMPOSE) run --rm msi-pipeline-gpu bash run_full_pipeline.sh $(D)
# ============================================================ # ============================================================
# Interactive shell # Interactive shell
# ============================================================ # ============================================================
@@ -47,32 +61,32 @@ pipeline:
step1: # Julia preprocessing step1: # Julia preprocessing
@if [ -z "$(D)" ]; then echo "Usage: make step1 D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step1 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu julia --threads auto --project=/app/environment \ docker compose run --rm msi-pipeline-gpu julia --threads auto --project=/app/environment \
/app/scripts/julia/julia_msi_bridge.jl /app/datasets/$(D) $(D) /app/scripts_julia/julia_msi_bridge.jl /app/ai_data/$(D) $(D)
step2: # SimCLR training step2: # SimCLR training
@if [ -z "$(D)" ]; then echo "Usage: make step2 D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step2 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu python3 /app/scripts/python/CNN_proof_1.py $(D) docker compose run --rm msi-pipeline-gpu python3 /app/scripts_python/CNN_proof_1.py $(D)
step3: # Clustering evaluation step3: # Clustering evaluation
@if [ -z "$(D)" ]; then echo "Usage: make step3 D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step3 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu python3 /app/scripts/python/evaluate_clustering.py $(D) docker compose run --rm msi-pipeline-gpu python3 /app/scripts_python/evaluate_clustering.py $(D)
step4: # t-SNE step4: # t-SNE
@if [ -z "$(D)" ]; then echo "Usage: make step4 D=Datura_leaf K=5"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step4 D=Datura_leaf K=5"; exit 1; fi
docker compose run --rm msi-pipeline-gpu python3 /app/scripts/python/graph_tsne_msi.py $(D) $(K) docker compose run --rm msi-pipeline-gpu python3 /app/scripts_python/graph_tsne_msi.py $(D) $(K)
step5: # Validation step5: # Validation
@if [ -z "$(D)" ]; then echo "Usage: make step5 D=Datura_leaf K=5"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step5 D=Datura_leaf K=5"; exit 1; fi
docker compose run --rm msi-pipeline-gpu python3 /app/scripts/python/quantitative_validation.py $(D) $(K) docker compose run --rm msi-pipeline-gpu python3 /app/scripts_python/quantitative_validation.py $(D) $(K)
step6: # Galleries step6: # Galleries
@if [ -z "$(D)" ]; then echo "Usage: make step6 D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step6 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu python3 /app/scripts/python/visualize_clusters.py $(D) docker compose run --rm msi-pipeline-gpu python3 /app/scripts_python/visualize_clusters.py $(D)
step7: # Mass spectra step7: # Mass spectra
@if [ -z "$(D)" ]; then echo "Usage: make step7 D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make step7 D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu julia --project=/app/environment \ docker compose run --rm msi-pipeline-gpu julia --project=/app/environment \
/app/scripts/julia/plot_mass_spectra.jl $(D) /app/scripts_julia/plot_mass_spectra.jl $(D) /app/ai_data/$(D)
# ============================================================ # ============================================================
# Plots # Plots
@@ -80,7 +94,7 @@ step7: # Mass spectra
plot-spectra: plot-spectra:
@if [ -z "$(D)" ]; then echo "Usage: make plot-spectra D=Datura_leaf"; exit 1; fi @if [ -z "$(D)" ]; then echo "Usage: make plot-spectra D=Datura_leaf"; exit 1; fi
docker compose run --rm msi-pipeline-gpu julia --project=/app/environment \ docker compose run --rm msi-pipeline-gpu julia --project=/app/environment \
/app/scripts/julia/plot_mass_spectra.jl $(D) /app/scripts_julia/plot_mass_spectra.jl $(D) /app/ai_data/$(D)
# ============================================================ # ============================================================
# Cleanup (outputs only; datasets are symlinked and never removed) # Cleanup (outputs only; datasets are symlinked and never removed)
+285 -95
View File
@@ -6,61 +6,42 @@ normalization, and per-ion PNG export in a single pass; a **Python SimCLR** enco
learns a 128-dimensional latent space from the exported ion corpus and clusters the ions learns a 128-dimensional latent space from the exported ion corpus and clusters the ions
into spatially coherent metabolic domains. into spatially coherent metabolic domains.
This repository is the self-contained, reproducible home of the manuscript This repository is self-contained: it ships the pinned environments, the full seven-stage
*"A scalable deep learning workflow for mass spectrometry imaging"* — the manuscript pipeline, and a **vendored copy of the JuliaMSI engine** (`src/`, MIT). Raw MSI datasets
(`MSI_julia-python_mapping.md`), all of its figures, the pinned environment, and the are supplied by the user (see [Datasets](#datasets)).
pipeline that produces every result are here. It ships the **renderable manuscript and its
figures**, plus all seven pipeline stages.
> This clone is a **standalone repository**: the raw MSI datasets are supplied by the user ## Repository layout
> (see [Datasets](#datasets)); everything else is self-contained. The earlier "functional
> copy / symlink into the canonical workspace" layout has been replaced by the standalone
> setup described below.
## Contents
``` ```
msi-julia-python-cnn/ .
├── README.md # this document ├── README.md
├── LICENSE # MIT ├── Dockerfile # GPU image (CUDA 12.4 + Julia + Python/SimCLR)
├── MSI_julia-python_mapping.md # manuscript (pandoc/biblatex, references zotero.bib)
├── zotero.bib # manuscript bibliography
├── figure1.png / figure2.png / figure3.png # manuscript figures, Pandoc style, 16 cm, 400 dpi (see below)
├── run_full_pipeline.sh # single entry point: 7-stage pipeline (one or many datasets)
├── run_pipeline.sh # legacy per-stage driver (native)
├── run_pipeline_wrapper.sh # activates a repo-local venv, then calls run_full_pipeline.sh
├── Makefile # build/run + step1..step7 targets (Docker)
├── Dockerfile # GPU image (CUDA 12.4 + Julia 1.12 + Python/SimCLR)
├── Dockerfile.cpu # CPU image (Ubuntu 22.04 + Julia + Python/SimCLR) ├── Dockerfile.cpu # CPU image (Ubuntu 22.04 + Julia + Python/SimCLR)
├── docker-compose.yml # msi-pipeline-gpu / msi-pipeline-cpu services ├── docker-compose.yml # msi-pipeline-gpu / msi-pipeline-cpu services
├── .dockerignore ├── .dockerignore
├── .gitignore ├── Makefile # build/run + step1..step7 targets (Docker)
├── run_full_pipeline.sh # single entry point: 7 stages (one or many datasets)
├── environment/ # pinned dependencies ├── environment/ # pinned dependencies
│ ├── Project.toml # Julia package set (incl. julia_mzML_imzML engine) │ ├── Project.toml # Julia package set
│ ├── Manifest.toml # locked Julia environment (julia 1.12.6) │ ├── Manifest.toml # locked Julia environment (julia 1.11.7)
│ └── requirements.txt # Python deps (torch, sklearn, Pillow, …) │ └── requirements.txt # Python deps (torch, sklearn, Pillow, …)
├── src/ ├── src/ # vendored JuliaMSI engine (MIT) — see below
│ └── MSI_src.jl # core Julia engine module (memory-mapped imzML, TrIQ, slices) │ └── MSI_src.jl + 14 modules # memory-mapped imzML, TrIQ, slicing, masks
├── scripts/ ├── scripts_julia/
│ ├── setup_datasets.sh # add a new imzML dataset via symlinks │ ├── julia_msi_bridge.jl # Stage 1: preprocess + PNG export (grayscale + viridis)
│ ├── julia/ │ ├── plot_mass_spectra.jl # Stage 7: mean + per-cluster spectra
│ │ ├── julia_msi_bridge.jl # Stage 1: preprocess + PNG export (grayscale + viridis) │ └── graph_cluster_spectra.jl # dev helper (spectrum figure with cluster mapping)
│ │ ├── plot_mass_spectra.jl # Stage 7: mean + per-cluster spectra ├── scripts_python/
│ │ └── graph_cluster_spectra.jl # spectrum figure with cluster mapping
│ └── python/
│ ├── msi_preprocess_python.py # Stage 1 Python fallback (vendor imzML)
│ ├── CNN_proof_1.py # Stage 2: SimCLR contrastive training │ ├── CNN_proof_1.py # Stage 2: SimCLR contrastive training
│ ├── evaluate_clustering.py # Stage 3: K sweep (2..20, 3 metrics) │ ├── evaluate_clustering.py # Stage 3: K sweep (2..20, 3 metrics)
│ ├── graph_tsne_msi.py # Stage 4: t-SNE + K-Means (*_k5 variants for k=5 runs) │ ├── graph_tsne_msi.py # Stage 4: t-SNE + K-Means
│ ├── quantitative_validation.py# Stage 5: isotope colocalization, PCA baseline, ARI │ ├── quantitative_validation.py # Stage 5: isotope co-localization, PCA baseline, ARI
│ ├── visualize_clusters.py # Stage 6: per-cluster galleries │ ├── visualize_clusters.py # Stage 6: per-cluster galleries
│ ├── plot_mass_spectra_python.py # Stage 7 Python fallback │ ├── plot_mass_spectra_python.py # Stage 7 Python fallback
│ ├── make_ion_carpet.py # standalone ion-carpet exporter (manuscript figures) │ ├── msi_preprocess_python.py # Stage 1 Python fallback (vendor imzML)
│ └── (test_grouping, verify_coherence, guided_vascular) # dev/analysis helpers │ ├── make_ion_carpet.py # standalone ion-carpet mosaics (figure panels)
├── datasets/ # user-provided data (see Datasets below) │ └── build_figure_panels.py # composite figure panels
│ ├── datasets.csv # registry of the 7 manuscript datasets (+ mask flags) ├── ai_data/ # user-provided datasets (git-ignored)
│ ├── Datura_leaf/ Datura_root/ San_pedro/
│ └── Mouse_bladder/ Mouse_Liver/ Mouse_Stomach/ Human_colon/
└── outputs/ # generated (git-ignored): ion images, models, figures └── outputs/ # generated (git-ignored): ion images, models, figures
``` ```
@@ -68,80 +49,289 @@ msi-julia-python-cnn/
| Stage | Script | Input → Output | | Stage | Script | Input → Output |
|-------|--------|----------------| |-------|--------|----------------|
| 1 | `scripts/julia/julia_msi_bridge.jl` (Python fallback: `msi_preprocess_python.py`) | imzML/ibd → avg spectrum, 2%-peak pick, per-ion extraction, TrIQ, zero-pad 256×256, PNG export (grayscale for DL + viridis corpus) | | 1 | `scripts_julia/julia_msi_bridge.jl` (fallback: `msi_preprocess_python.py`) | imzML/ibd → avg spectrum, 2%-peak pick, per-ion extraction, TrIQ, resize to ≤256 px, PNG export (grayscale for DL + viridis corpus) |
| 2 | `scripts/python/CNN_proof_1.py` | grayscale PNGs → SimCLR 4-layer GroupNorm encoder → 128-dim latents (`outputs/models/<ds>/`) | | 2 | `scripts_python/CNN_proof_1.py` | grayscale PNGs → SimCLR 4-layer GroupNorm encoder → 128-dim latents (`outputs/models/<ds>/`) |
| 3 | `scripts/python/evaluate_clustering.py` | latents → K sweep k=2..20 (Silhouette, Davies-Bouldin, Calinski-Harabasz) → best K | | 3 | `scripts_python/evaluate_clustering.py` | latents → K sweep k=2..20 (Silhouette, Davies-Bouldin, Calinski-Harabasz) → best K (`outputs/<ds>/best_k_results.csv`) |
| 4 | `scripts/python/graph_tsne_msi.py <ds> <K>` | latents → t-SNE colored by K-Means (best K) | | 4 | `scripts_python/graph_tsne_msi.py <ds> <K>` | latents → t-SNE colored by K-Means |
| 5 | `scripts/python/quantitative_validation.py <ds> <K>` | latents → isotope co-localization, PCA baseline, ARI stability | | 5 | `scripts_python/quantitative_validation.py <ds> <K>` | latents → isotope co-localization, PCA baseline, ARI stability |
| 6 | `scripts/python/visualize_clusters.py <ds>` | clusters → representative ion-image galleries per cluster | | 6 | `scripts_python/visualize_clusters.py <ds>` | clusters → representative ion-image galleries per cluster |
| 7 | `scripts/julia/plot_mass_spectra.jl <ds>` (Python fallback) | spectra → mean spectrum + per-cluster annotated spectra | | 7 | `scripts_julia/plot_mass_spectra.jl <ds> [data_dir]` (fallback: `plot_mass_spectra_python.py`) | spectra → mean + per-cluster annotated spectra |
| — | `scripts/python/make_ion_carpet.py <ds> [--clusters]` (standalone) | Stage-1 viridis corpus → full-dataset & per-cluster ion-carpet mosaics (manuscript Fig. carpet / carpet-root) | | — | `scripts_python/make_ion_carpet.py <ds> [--clusters]` (standalone) | Stage-1 viridis corpus → full-dataset & per-cluster ion-carpet mosaics |
## Run ## Quick start (Docker, recommended)
### Native (venv + system Julia)
```bash ```bash
# one-time setup: Python environment with pinned deps # 1) build (GPU image; `make build-cpu` for the smaller CPU-only image)
make build
# 2) put each dataset in its own folder, e.g.
# ai_data/Datura_leaf/<name>.imzML (+ <name>.ibd, optional ROI .png)
# 3) run — works on CPU out of the box (torch falls back when there is no GPU)
make run # every dataset under ai_data/
make run-dataset D=Datura_leaf # a single dataset
# with an NVIDIA GPU (needs the Container Toolkit / a CDI spec — see Troubleshooting):
make run-gpu
make run-dataset-gpu D=Datura_leaf
```
Equivalent raw container, if you prefer not to use `make`:
```bash
docker build -t msi-pipeline-gpu .
# CPU (no GPU flags):
docker run --rm --shm-size=2g -it \
-v "$PWD/ai_data:/app/ai_data" \
-v "$PWD/outputs:/app/outputs" \
msi-pipeline-gpu bash
# add `--gpus all` (Docker) or `--device nvidia.com/gpu=all` (Podman + CDI) for a GPU.
# then, inside the container:
bash run_full_pipeline.sh # all datasets under ai_data/
bash run_full_pipeline.sh Datura_leaf # a single dataset
```
The pipeline runs fine **without a GPU** (SimCLR trains on CPU, just slower). The pure
`Dockerfile.cpu` image (`make build-cpu`, `make run-cpu`) is smaller if you never need CUDA.
In VS Code the bundled `.devcontainer/` requests a GPU.
## Native run (venv + system Julia)
```bash
# one-time setup
python3 -m venv venv && venv/bin/pip install -r environment/requirements.txt python3 -m venv venv && venv/bin/pip install -r environment/requirements.txt
julia --project=environment -e 'using Pkg; Pkg.instantiate()'
# run everything (or a single dataset) # run everything, or a single dataset
bash run_full_pipeline.sh # all 7 manuscript datasets bash run_full_pipeline.sh
bash run_full_pipeline.sh Datura_leaf # single dataset bash run_full_pipeline.sh Datura_leaf
# optional: regenerate the ion-carpet mosaics after Stage 1
venv/bin/python scripts/python/make_ion_carpet.py Datura_leaf --clusters
``` ```
`run_pipeline_wrapper.sh` automatically activates a local `venv/` if present. Requires **Julia 1.11.x** (matching `environment/Manifest.toml`) and **Python 3.10+**.
`run_full_pipeline.sh` automatically uses a repo-local `venv/` when present.
### Docker ## Running individual stages
`run_full_pipeline.sh` chains the stages below. To re-run a single one (native form):
```bash ```bash
make build # GPU image (NVIDIA Container Toolkit required to run) julia --threads auto --project=environment scripts_julia/julia_msi_bridge.jl ai_data/<ds> <ds>
make build-cpu # CPU-only image python scripts_python/CNN_proof_1.py <ds>
make run # full pipeline on all datasets python scripts_python/evaluate_clustering.py <ds> # writes outputs/<ds>/best_k_results.csv
make run-dataset D=Datura_leaf python scripts_python/graph_tsne_msi.py <ds> <K>
make step1..step7 D=... # re-run a single stage (steps 4–5 need K=) python scripts_python/quantitative_validation.py <ds> <K>
python scripts_python/visualize_clusters.py <ds>
julia --project=environment scripts_julia/plot_mass_spectra.jl <ds> ai_data/<ds>
``` ```
### Add a custom dataset Docker equivalents: `make step1 D=<ds>` … `make step7 D=<ds>`, with
`make step4 D=<ds> K=5` and `make step5 D=<ds> K=5`. Stages 4–5 need the cluster
```bash count `K`; Stage 3 prints and stores the best value (Silhouette optimum by default).
bash scripts/setup_datasets.sh /path/to/your_data.imzML my_dataset
```
## Datasets ## Datasets
All seven benchmark datasets are **public** and listed in `datasets/datasets.csv` The pipeline reads **any valid imzML** (profile or centroid) — it is **not** restricted to
(LD-LTP *Datura* leaf and root, MALDI San Pedro cactus, MALDI mouse liver and stomach, a fixed set of datasets.
AP-SMALDI mouse bladder, DESI human colon; 0.07–4.4 GB, centroid and profile). Access
instructions: **TODO — add accession DOI/URL per dataset**. Download each raw **Each dataset must live in its own subfolder of `ai_data/`.** The folder name *is*
imzML/ibd pair and place it (or symlink it) into `datasets/<name>/`, matching the the dataset name, and it becomes the `outputs/<name>/` directory. Files placed directly in
`imzml_file` column. ROI masks (`region_of_interest.png` / `region_of_interest_<tissue>.png`) `ai_data/` — **not inside a subfolder — are ignored** by `run_full_pipeline.sh`, so a
are already expected there for the masked datasets (all except San Pedro). dataset dropped loose at the root will not be detected.
```
ai_data/
├── Mouse_bladder/ # folder name = dataset name
│ ├── HR2MSImouseurinarybladderS096.imzML # exactly one .imzML
│ ├── HR2MSImouseurinarybladderS096.ibd # its sibling .ibd (matching basename)
│ └── region_of_interest.png # optional ROI mask
└── Datura_leaf/
├── Leaf.imzML
└── Leaf.ibd
```
Rules for each dataset folder:
- exactly one `.imzML` file, and
- its sibling `.ibd` binary — the imzML references the `.ibd` by basename, so both must sit
in the same folder with matching basenames.
**ROI masks are optional.** If present in the same folder, the first match wins:
`region_of_interest.png`, otherwise any `*.png` whose filename contains `roi`, `mask`, or
`region` (case-insensitive) — e.g. `region.png`, `MyData_mask.png`. Masks are resized to the
dataset dimensions; without one the full image is used.
## JuliaMSI engine (`src/`)
The Julia core used by Stages 1 and 7 is **vendored** into `src/` from the MIT-licensed
[JuliaMSI](https://codeberg.org/LabABI/JuliaMSI) project (© LabABI, Cinvestav Irapuato,
Mexico), pinned at commit `6aa76fc` (2026-08-25). Mirrors / GUI:
- <https://codeberg.org/LabABI/JuliaMSI> (upstream)
- <https://codeberg.org/pixelguy14/JuliaMSI>
- <https://github.com/Pixelguy14/Julia_msi_GUI>
- <https://git.nube-gran.de/Julian/MSI_Julia_CNN>
It is vendored (≈400 KB) so the pipeline is reproducible and does not break when upstream
APIs change. To update the engine, replace the contents of `src/` from a newer upstream
commit and re-run Stage 1. The MIT license of the vendored code is in `src/LICENSE`.
## Configuration knobs
`run_full_pipeline.sh` and the scripts honour these environment variables:
| Variable | Default | Meaning |
|----------|---------|---------|
| `MSI_PEAK_FRAC` | `0.02` | peak-pick threshold as a fraction of the base peak |
| `MSI_PEAK_MIN_MZ_GAP` | `0` | minimum m/z separation between picked ions (0 disables) |
| `MSI_BIN_AVG` | unset | average-spectrum bin width in Da (needed for high-resolution ToF data) |
| `MSI_MEM_MAX` | unset | cgroup memory ceiling |
| `MSI_DATA_ROOT` | `ai_data` | override the dataset root directory |
| `MSI_K` | auto | force a cluster count instead of the Stage-3 Silhouette choice |
## Prerequisites ## Prerequisites
- **Julia 1.12.x** (instantiate against `environment/`; first run resolves the depot) - **Julia 1.11.x** — instantiate against `environment/Manifest.toml`.
- **Python 3.10+** (`environment/requirements.txt`; torch builds for your GPU/CPU) - **Python 3.10+** — `environment/requirements.txt` (torch builds for your GPU/CPU).
- Optional: **Docker 24+** with NVIDIA Container Toolkit for the GPU image - Optional: **Docker 24+** with NVIDIA Container Toolkit (GPU image) and Compose v2 (`make`).
- Disk: datasets are 0.07–4.4 GB; outputs/models add a few GB. RAM: ~8 GB+ for larger sets.
Pipeline configuration knobs (see `run_full_pipeline.sh`): `MSI_PEAK_FRAC`, ## Troubleshooting
`MSI_PEAK_MIN_MZ_GAP`, `MSI_BIN_AVG`, `MSI_MEM_MAX` (cgroup memory ceiling).
## Manuscript figures ### `? Please select an image:` at `STEP 1/15` (Podman / Buildah)
The manuscript (`MSI_julia-python_mapping.md`, biblatex bibliography `zotero.bib`) When a `FROM` uses a short image name (e.g. `nvidia/cuda:12.4.1-runtime-ubuntu22.04`),
Docker resolves it against Docker Hub automatically, but **Podman/Buildah enforces
short-name resolution**: if more than one registry is configured it stops and asks which
one to pull from. A typical prompt (the list depends on your registry configuration):
``` ```
figure1.png # JuliaMSI vs Cardinal vs MALDIquant: slice throughput + peak load RAM, red X on failed MALDIquant runs (Fig. \ref{fig:benchmark}) ? Please select an image:
figure2.png # K-sweep clustering validation for the Datura leaf + root demonstration datasets (Fig. \ref{fig:clustering}) ▸ registry.fedoraproject.org/nvidia/cuda:12.4.1-runtime-ubuntu22.04
figure3.png # t-SNE + biologically interpretable ion galleries, mouse bladder over human colon (Fig. \ref{fig:tsne_clusters}) registry.access.redhat.com/nvidia/cuda:12.4.1-runtime-ubuntu22.04
docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04
``` ```
The three manuscript figures are composite panels assembled by **Choose `docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04`** — NVIDIA publishes these
`scripts/python/build_manuscript_figures.py` from the per-dataset outputs of the pipeline images on Docker Hub.
(`outputs/<ds>/msi_tsne_plot.png`, `outputs/<ds>/figures/cluster_validation_detailed_plot.png`,
`outputs/<ds>/galleries/`, and the benchmark CSV under `Benchmark_recommendation/results/`). To avoid the prompt entirely (recommended, works on every OS): use the **fully-qualified**
Re-run that script after any pipeline or benchmark change to regenerate them. name. This repository's Dockerfiles already do this, so no prompt should appear:
```dockerfile
FROM docker.io/nvidia/cuda:12.4.1-runtime-ubuntu22.04 # Dockerfile (GPU)
FROM docker.io/library/ubuntu:22.04 # Dockerfile.cpu (CPU)
```
If you maintain a fork with short names and cannot change the Dockerfile, you can allow
short names globally instead. Edit the Containers registry config:
- Linux/macOS (rootless): `~/.config/containers/registries.conf`
- Linux (root): `/etc/containers/registries.conf`
- Windows: `%APPDATA%\containers\registries.conf`
```toml
unqualified-search-registries = ["docker.io"]
short-name-mode = "permissive"
```
- **Docker Desktop (Windows/macOS) and Docker Engine (Linux):** no prompt — `nvidia/cuda`
resolves to Docker Hub by default.
- **Podman (Linux/macOS/Windows):** prompted unless the name is fully qualified or the
config above is set.
### Clean rebuild / remove a failed build
A **failed build usually leaves no tagged project image** — only intermediary layers and
build cache. Clearing the cache is therefore the important step; there is often nothing to
`rmi`.
Docker (Linux/Windows/macOS):
```bash
docker compose down --rmi all --volumes --remove-orphans # project-scoped reset
docker rmi -f msi-pipeline-gpu msi-pipeline-cpu 2>/dev/null || true
docker builder prune -af # clear BuildKit cache
docker image prune -f # drop dangling <none> images
docker compose build --no-cache msi-pipeline-gpu # rebuild from scratch
```
Podman / `podman-compose`:
```bash
podman-compose down --rmi all -v
podman rmi -f $(podman images --format '{{.ID}} {{.Repository}}' \
| awk 'tolower($0) ~ /msi-pipeline/ {print $1}') 2>/dev/null || true
podman builder prune -af
podman-compose build --no-cache msi-pipeline-gpu
```
Notes:
- `docker builder prune -af` / `podman builder prune -af` affect this project's cache
safely; the `system prune -a` commands are host-wide.
- A normal `make build` reuses cached `apt`/Julia/pip layers. For a genuine
reproducibility test, clear the cache (`builder prune -af`) or build with `--no-cache`.
### `make run` fails with `unresolvable CDI devices nvidia.com/gpu=all`
The base `docker-compose.yml` does **not** request a GPU, so `make run` / `make run-dataset`
work on CPU-only machines. Requesting a GPU is opt-in via `docker-compose.gpu.yml`:
```bash
make run-gpu
make run-dataset-gpu D=Datura_leaf
```
On **Podman**, a GPU reservation becomes the CDI device `nvidia.com/gpu=all`, which must
exist first:
```bash
# one-time, on the host (needs the NVIDIA driver + nvidia-container-toolkit):
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
nvidia-ctk cdi list # should show nvidia.com/gpu=all
```
Docker Desktop / Docker Engine handle the `deploy` GPU reservation without a manual CDI
spec. If you have no NVIDIA GPU, ignore `*-gpu` targets entirely — the CPU fallback works.
### If the Julia step of the build fails
- The images install Julia strictly from the committed `environment/Manifest.toml` and run
`Pkg.instantiate()` only (no `resolve()`). If you see
`… is a direct dependency, but does not appear in the manifest`, the lock is out of sync
with `Project.toml` — run `julia --project=environment -e 'using Pkg; Pkg.resolve()'`
locally and commit the regenerated `Manifest.toml`.
- `GLMakie` fails to precompile in a headless build
(`GLFWError … X11: The DISPLAY environment variable is missing`). This is expected and
**non-fatal**: GLMakie is a GUI-only dependency and the pipeline never loads it. The
images intentionally do not run an explicit `Pkg.precompile()`.
## Data availability
**TODO — add accession DOI/URL per dataset.**
The seven reference datasets are all **public**: LD-LTP *Datura* leaf and root, MALDI San
Pedro cactus, MALDI mouse liver and stomach, AP-SMALDI mouse bladder, DESI human colon
(0.07–4.4 GB, centroid and profile).
Related dataset DOIs:
- San Pedro Cactus: <https://doi.org/10.5281/zenodo.3625054>
- Human Colon & Mouse Bladder: <https://doi.org/10.5281/zenodo.10084132>
- Datura Leaf & Datura Root: pending.
- Mouse Stomach & Mouse Liver: pending.
## Trained models
`models.zip` (pending link) contains the trained SimCLR encoders for the seven reference
datasets. Unzip it into `outputs/` (`unzip models.zip -d outputs/`) to reuse
`outputs/models/<ds>/msi_encoder_trained.pth` and skip Stage 2 for those datasets.
## License
MIT — see `LICENSE`. The vendored `src/` retains its own MIT license (`src/LICENSE`).
## Citation
Once the article/DOI is published...
-289
View File
@@ -1,289 +0,0 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% This is a "template" model document for submission to the
%% American Chemical Society (ACS).
%%
%% The guidance here contains information about how you may wish to
%% modify it to match the requirements of various ACS journals. The
%% ACS do *not* typeset accepted articles using LaTeX, so there is
%% no specific class required.
%%
%% This template deliberately does *not* seek to reproduce
%% the layout of the typeset journal: this is explicitly not
%% required by the ACS for LaTeX submissions.
%%
%% Please report any issues with the template at
%% https://github.com/josephwright/acs-template/issues
%%
%% Released under the Creative Commons 0 license
%% https://creativecommons.org/public-domain/cc0/
%%
%% Copyight (c) 2025 Joseph Wright
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[letterpaper]{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Font setup - delete if you are using LuaLaTeX
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T1]{fontenc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Adjust the margins and allow for line spacing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{geometry}
\geometry{margin = 1in}
\usepackage{setspace}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Reference support
%%
%% The recommended method for producing the reference section is
%% to use biblatex. If you wish to use a classical BibTeX
%% approach, this is easiest to achieve using the achemso package.
%% In that case, you should remove the biblatex lines.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% You can adjust the printing of DOI, article title, etc. using
% package options, e.g. "doi = true"; see the biblatex manual for
% details of adjusting the number of authors printed, e.g.
% "maxnames = 15" to print no more than 15 authors.
\usepackage[style = chem-acs]{biblatex}
\addbibresource{acs-template.bib}
% If you are using classical BibTeX, remove the above lines and
% uncomment:
%\usepackage{achemso}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Graphic inclusion and scheme and chart support
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{graphicx}
\usepackage{float}
\newfloat{scheme}{htbp}{los}
\floatname{scheme}{Scheme}
\floatname{chart}{Chart}
\newfloat{graph}{htbp}{loh}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Common support packages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{chemformula} % Formulas using \ch{}
% or
\usepackage[version = 4]{mhchem} % Formulas using \ce{}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Many journals require that sections are unnumbered: this
%% is activated here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\setcounter{secnumdepth}{-1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Place any additional macros here. Please use \newcommand* where
%% possible, and avoid layout-changing macros (which are not used
%% when typesetting).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand*\mycommand[1]{\texttt{\emph{#1}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Author and title data:
%% the authblk package is currently the simplest way to provide this
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{authblk}
\author[1]{Andrew N. Other}
\author[1]{Fred T. Secondauthor}
\author[1]{I. Ken Groupleader*}
\affil[1]{Department of Chemistry, Unknown University, Unknown Town}
\author[2]{Susanne K. Laborator}
\affil[2]{Lead Discovery, BigPharma, Big Town, USA}
\author[1]{Kay T. Finally}
\title{A ``template'' model document for submission to the
American Chemical Society (ACS)}
% Use the \date command for email address(s) of corresponding authors
\date{*Email: i.k.groupleader@unknown.uu}
\begin{document}
\maketitle
\begin{abstract}
This is an example document for creating \LaTeX{} submissions to the American
Chemical Society (ACS) for publication. As ACS does not use \LaTeX{} for
typesetting accepted manuscripts, this template does not seek to
reproduce the appearance of a published paper.
\end{abstract}
\section*{Keywords}
Some journals require keywords: these normally should be given immediately
after the abstract.
\section*{Abbreviations}
Some journals require a list of abbreviations: these normally should be given
immediately after the keyswords (if required).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Start the main part of the manuscript here.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Introduction}
This is a paragraph of text to fill the introduction of the demonstration file.
\section{Results and discussion}
\subsection{Outline}
The document layout should follow the style of the journal concerned. Where
appropriate, sections and subsections should be added in the normal way.
\subsection{References}
References should be given in the normal way in \LaTeX{}. If you are using
\textsf{biblatex} (as recommended) then you can use the full range of citation
commands it provides. If you choose to use classical Bib\TeX{}, the
\textsf{natbib} package will be loaded and you can use it's commands.
\subsection{Floats}
New float types are set up in the preamble. The means graphics are included as
follows (Scheme~\ref{sch:example}). As illustrated, the float is ``here'' if
possible.
\begin{scheme}
\centering
Your scheme graphic would go here: PDF graphics are recommended.
%\includegraphics{graphic}
\caption{An example scheme}
\label{sch:example}
\end{scheme}
\begin{figure}
\centering
A standard figure environment.
\label{fgr:example}
\end{figure}
The use of the different floating environments is not required, but it is
intended to make document preparation easier for authors. In general, you
should place your graphics where they make logical sense; the production
process will move them if needed.
\subsection{Math}
If packages such as \textsf{amsmath} are required, they should be loaded in the
preamble. However, the basic \LaTeX\ math(s) input should work correctly
without this. Some inline material $1 + 1 = 2$ followed by some display. \[ A =
\pi r^2 \]
It is possible to label equations in the usual way (Eq.~\ref{eqn:example}).
\begin{equation}
\frac{\mathrm{d}}{\mathrm{d}x} \, r^2 = 2r \label{eqn:example}
\end{equation}
This can also be used to have equations containing graphical content. To align
the equation number with the middle of the graphic, rather than the bottom, a
minipage may be used.
\begin{equation}
\begin{minipage}[c]{0.80\linewidth}
\centering
As illustrated here, the width of \\
the minipage needs to allow some \\
space for the number to fit in to.
%\includegraphics{graphic}
\end{minipage}
\label{eqn:graphic}
\end{equation}
\section{Experimental}
The usual experimental details should appear here. This could include a table,
which can be referenced as Table~\ref{tbl:example}. Notice that the caption is
positioned at the top of the table.
\begin{table}
\caption{An example table}
\label{tbl:example}
\centering
\begin{tabular}{ll}
\hline
Header one & Header two \\
\hline
Entry one & Entry two \\
Entry three & Entry four \\
Entry five & Entry five \\
Entry seven & Entry eight \\
\hline
\end{tabular}
\end{table}
Adding notes to tables can be complicated. Perhaps the easiest method is to
generate these using the basic \texttt{\textbackslash textsuperscript} and
\texttt{\textbackslash emph} macros, as illustrated (Table~\ref{tbl:notes}).
\begin{table}
\caption{A table with notes}
\label{tbl:notes}
\centering
\begin{tabular}{ll}
\hline
Header one & Header two \\
\hline
Entry one\textsuperscript{\emph{a}} & Entry two \\
Entry three\textsuperscript{\emph{b}} & Entry four \\
\hline
\end{tabular}
\textsuperscript{\emph{a}} Some text;
\textsuperscript{\emph{b}} Some more text.
\end{table}
The example file also loads the optional \textsf{chemformula} and
\textsf{mhchem} packages, so that formulas are easy to input:
\texttt{\textbackslash ce\{H2SO4\}} gives \ce{H2SO4}. The two have similar
syntax but authors may prefer one or the other.
The use of new commands should be limited to simple things which will not
interfere with the production process. For example, \texttt{\textbackslash
mycommand} has been defined in this example, to give italic, mono-spaced text:
\mycommand{some text}.
\section*{Acknowledgements}
Please use ``The authors thank \ldots'' rather than ``The authors would like to
thank \ldots''.
\section*{Supporting information}
A listing of the contents of each file supplied as Supporting Information
should be included. For instructions on what should be included in the
Supporting Information as well as how to prepare this material for
publications, refer to the journal's Instructions for Authors.
The following files are available free of charge.
\begin{itemize}
\item Filename-1: brief description
\item Filename-2: brief description
\end{itemize}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% If you are using classical BibTeX rather than biblatex,
%% remove the \printbibliography and uncomment the \bibliograpy one
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\printbibliography
%\bibliography{acs-template.bib}
\newpage
\rule{0.05in}{1.75in}%
\begin{minipage}[b][1.75in]{3.25in}
\sffamily
\frenchspacing
Some journals require a graphical entry for the Table of Contents. This
should be laid out ``print ready'' so that the sizing of the text is correct.
The space available depends on the journal: J. Am. Chem. Soc. allows 3.25 in
by 1.75 in and requires sanserif text. Some journals want different sizes:
you can easily adjust here.
The two rules either side of the content are there to help judge the height
of your material: they may be deleted once not required.
\end{minipage}%
\rule{0.05in}{1.75in}
\end{document}
+22
View File
@@ -0,0 +1,22 @@
# Opt-in GPU override. The base docker-compose.yml does NOT request a GPU, so
# `make run` works on CPU-only machines. To use an NVIDIA GPU, layer this file:
#
# docker compose -f docker-compose.yml -f docker-compose.gpu.yml \
# run --rm msi-pipeline-gpu bash run_full_pipeline.sh
# (or: make run-gpu / make run-dataset-gpu D=<name>)
#
# Requirements: an NVIDIA GPU + NVIDIA Container Toolkit.
# On Podman, first generate the CDI spec, otherwise you get
# "unresolvable CDI devices nvidia.com/gpu=all":
#
# sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
#
services:
msi-pipeline-gpu:
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
+26
View File
@@ -0,0 +1,26 @@
services:
msi-pipeline-gpu:
build:
context: .
dockerfile: Dockerfile
image: msi-pipeline-gpu
working_dir: /app
shm_size: "2gb"
volumes:
# `:z` relabels the bind mount for SELinux hosts (Fedora/RHEL + Podman).
# It is ignored by Docker. Remove it if your host has no SELinux.
- ./ai_data:/app/ai_data:z
- ./outputs:/app/outputs:z
msi-pipeline-cpu:
build:
context: .
dockerfile: Dockerfile.cpu
image: msi-pipeline-cpu
working_dir: /app
shm_size: "2gb"
volumes:
# `:z` relabels the bind mount for SELinux hosts (Fedora/RHEL + Podman).
# It is ignored by Docker. Remove it if your host has no SELinux.
- ./ai_data:/app/ai_data:z
- ./outputs:/app/outputs:z
-73
View File
@@ -1,73 +0,0 @@
# Technical Documentation & Experimental Rationale
This document provides a detailed technical overview of the computational choices, hyperparameter tuning, and validation strategies implemented in the hybrid Julia-Python MSI workflow.
## Docker Maintenance & Disk Space
If you encounter disk space issues due to failed builds or unused images, use these commands:
- **Safe Clean (Dangling layers only):** `docker image prune`
- **Deep Clean (Everything unused):** `docker system prune -a --volumes`
- **Clear Build Cache:** `docker builder prune`
## 1. Hyperparameter Tuning Rationale (SimCLR)
The training configuration in `scripts_python/CNN_proof_1.py` follows the standard SimCLR framework (Chen et al., 2020) while being optimized for the morphological characteristics of Mass Spectrometry Imaging (MSI) data.
| Hyperparameter | Value | Rationale |
| :--- | :--- | :--- |
| **Temperature ($\tau$)** | 0.5 | **Selected via grid search.** We tested $\tau \in \{0.1, 0.5, 1.0\}$. A value of 0.1 led to unstable gradients and collapsed representations, while 1.0 was too permissive. $\tau=0.5$ provided the most stable convergence and distinct cluster boundaries. |
| **Projection Dim** | 128 | Standard for SimCLR. Reducing to 64 lost anatomical detail; increasing to 256 did not improve Silhouette scores but increased computational overhead. |
| **Training Epochs** | 50 | Observed convergence of NT-Xent loss between epochs 40-50. Further training (tested up to 200 epochs) led to minor overfitting to instrumental artifacts. |
| **Batch Size** | 32 | Optimized for the i5 CPU environment to balance memory usage and gradient stability. |
## 2. Advanced Validation Strategies
To satisfy rigorous peer review, we implemented three quantitative validation layers in `scripts_python/quantitative_validation.py`:
### 2.1 Baseline Comparison (PCA vs. SimCLR)
* **Method:** We compared our self-supervised approach against a traditional baseline where PCA is applied directly to raw pixel vectors (flattened ion images).
* **Result:** SimCLR consistently yields higher Silhouette scores and lower Davies-Bouldin indices. This proves that the neural network's non-linear feature extraction captures anatomical "shapes" better than linear variance-based methods.
### 2.2 Stability & Reproducibility Analysis
* **Metric:** Adjusted Rand Index (ARI).
* **Method:** We ran the clustering pipeline across 10 different random seeds. By computing the ARI between all pairs of runs, we demonstrate that the metabolic domains identified (Clusters 0-9) are stable and not artifacts of k-means initialization.
### 2.3 Isotope Co-localization (Natural Ground Truth)
* **Scientific Anchor:** Isotopes ($[M+H]^+$ and $[M+H+1]^+$) must co-localize perfectly in tissue.
* **Validation:** We measure the Euclidean distance of isotopic pairs in the latent manifold. A t-test confirms that these distances are significantly smaller than those of random ion pairs, providing objective evidence that the model has learned chemical-biological reality.
## 3. Biological & Mathematical Rationale for $k=10$
While mathematical metrics (Elbow method, Silhouette) often suggest $k=2$ or $k=3$ (tissue vs. background), we selected **$k=10$** based on:
1. **Anatomical Fidelity:** This threshold is required to resolve the hierarchy between the primary midrib, secondary veins, and apical accumulation zones.
2. **Stability:** Metric stabilization was observed in the $k=8$ to $k=12$ range.
3. **Metabolic Heatmaps:** Average ion intensities per cluster for scopolamine ($m/z$ 304.1) and atropine ($m/z$ 290.1) show clear sequestration in Clusters 9 (Vascular) and 7 (Apical), validating the biological relevance of the segmentation.
## 4. Technical Specifications & Citations
### 4.1 Data Augmentations
We implemented **Additive Gaussian Noise ($\sigma=0.01$)**. This is critical for MSI to simulate detector background noise.
* *Citation:* DeepION (2024) and Hu et al. (2022, Table S1).
### 4.2 Model Backbone
**EfficientNet-B0** with ImageNet weights was used for transfer learning. The MBConv blocks are highly efficient for CPU-based inference.
* *Citation:* Tan & Le (2019).
### 4.3 Preprocessing (JuliaMSI)
* **Spectral Averaging:** Done via `MSI_src.get_average_spectrum`.
* **Tolerance:** $\pm 0.05$ Da window for mass slices. This is standard for low-resolution Ion Trap instruments (LCQ Fleet) to ensure all isotopic signal is captured.
* *Citation:* Sierra-Álvarez et al. (2025).
### 4.4 Dimensionality Reduction
PCA was used to reduce the 1280-dim (EfficientNet) or 128-dim (Projector) features to **50 components** before k-means. This heuristic stabilizes clustering by removing noise and redundant dimensions.
* *Citation:* Jolliffe (2002).
## Benchmarking & Hardware Realism
The pipeline is optimized for efficiency on consumer-grade hardware.
- **Julia Stage**: Uses `BenchmarkTools.jl` to profile binary parsing.
- **Python Stage**: Uses `psutil` and `CUDA` monitoring to track hardware overhead.
- **Determinism**: All stochastic steps are locked with `seed=42`.
## Julia-Python Bridge Details
The "two-language problem" is solved by an intermediate file-system bridge. Julia performs binary MSI parsing and **Threshold Intensity Quantization (TrIQ)**. The resulting data is saved as high-contrast 224x224 grayscale PNG images, allowing the Python PyTorch pipeline to consume it efficiently.
File diff suppressed because it is too large Load Diff
-8
View File
@@ -11,9 +11,6 @@ ContinuousWavelets = "96eb917e-2868-4417-9cb6-27e7ff17528f"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
GLMakie = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a"
Genie = "c43c736e-a2d1-11e8-161f-af95117fbd1e"
GenieFramework = "a59fdf5c-6bf0-4f5d-949c-a137c9e2f353"
HistogramThresholding = "2c695a8d-9458-5d45-9878-1b8a99cf7853" HistogramThresholding = "2c695a8d-9458-5d45-9878-1b8a99cf7853"
ImageBinarization = "cbc4b850-ae4b-5111-9e64-df94c024a13d" ImageBinarization = "cbc4b850-ae4b-5111-9e64-df94c024a13d"
ImageComponentAnalysis = "d9b9e9a0-1569-11e9-2cb5-bbca914b0e89" ImageComponentAnalysis = "d9b9e9a0-1569-11e9-2cb5-bbca914b0e89"
@@ -30,11 +27,8 @@ Libz = "2ec943e9-cfe8-584d-b93d-64dcb6d567b7"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Loess = "4345ca2d-374a-55d4-8d30-97f9976e7612" Loess = "4345ca2d-374a-55d4-8d30-97f9976e7612"
Mmap = "a63ad114-7e13-5084-954f-fe012c677804" Mmap = "a63ad114-7e13-5084-954f-fe012c677804"
NativeFileDialog = "e1fe445b-aa65-4df4-81c1-2041507f0fd4"
NaturalSort = "c020b1a1-e9b0-503a-9c33-f039bfc54a85" NaturalSort = "c020b1a1-e9b0-503a-9c33-f039bfc54a85"
PackageCompiler = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d"
Parameters = "d96e819e-fc66-5662-9728-84c9c7592b0a" Parameters = "d96e819e-fc66-5662-9728-84c9c7592b0a"
PlotlyBase = "a03496cd-edff-5a9b-9e67-9cda94a718b5"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca" ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca"
@@ -44,7 +38,5 @@ Setfield = "efcf1570-3423-57d1-acb7-fd33fddbac46"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
StipplePlotly = "ec984513-233d-481d-95b0-a3b58b97af2b"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
julia_mzML_imzML = "38eb50d3-2fb6-4afa-992a-964ed8562ed9"
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 294 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 379 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 780 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 359 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 341 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 349 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 379 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

-794
View File
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 15 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

-134
View File
@@ -1,134 +0,0 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% This is a "template" model document for submission to the
%% American Chemical Society (ACS).
%%
%% The guidance here contains information about how you may wish to
%% modify it to match the requirements of various ACS journals. The
%% ACS do *not* typeset accepted articles using LaTeX, so there is
%% no specific class required.
%%
%% This template deliberately does *not* seek to reproduce
%% the layout of the typeset journal: this is explicitly not
%% required by the ACS for LaTeX submissions.
%%
%% Please report any issues with the template at
%% https://github.com/josephwright/acs-template/issues
%%
%% Released under the Creative Commons 0 license
%% https://creativecommons.org/public-domain/cc0/
%%
%% Copyight (c) 2025 Joseph Wright
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[letterpaper]{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Font setup - delete if you are using LuaLaTeX
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T1]{fontenc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Adjust the margins and allow for line spacing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{geometry}
\geometry{margin = 1in}
\usepackage{setspace}
\usepackage{textcomp}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Reference support
%%
%% The recommended method for producing the reference section is
%% to use biblatex. If you wish to use a classical BibTeX
%% approach, this is easiest to achieve using the achemso package.
%% In that case, you should remove the biblatex lines.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% You can adjust the printing of DOI, article title, etc. using
% package options, e.g. "doi = true"; see the biblatex manual for
% details of adjusting the number of authors printed, e.g.
% "maxnames = 15" to print no more than 15 authors.
\usepackage[style = chem-acs]{biblatex}
\addbibresource{zotero.bib}
% If you are using classical BibTeX, remove the above lines and
% uncomment:
%\usepackage{achemso}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Graphic inclusion and scheme and chart support
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{graphicx}
\setkeys{Gin}{width=17.1cm,keepaspectratio}
\usepackage{float}
\newfloat{scheme}{htbp}{los}
\floatname{scheme}{Scheme}
\floatname{chart}{Chart}
\newfloat{graph}{htbp}{loh}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Common support packages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{calc}
\usepackage{amsmath}
\usepackage{array}
\usepackage{booktabs}
%% Fix for pandoc-generated \real{} in table widths - define as pass-through macro
%% \unskip removes the space that pandoc inserts before \real
\newcommand{\real}[1]{\unskip#1}
%% Fix for pandoc-generated \pandocbounded for bounded images
\newcommand{\pandocbounded}[1]{\makebox[0pt][l]{#1}}
%% Fix for pandoc-generated \texorpdfstring (from hyperref)
\newcommand{\texorpdfstring}[2]{#1}
\usepackage{chemformula} % Formulas using \ch{}
% or
\usepackage[version = 4]{mhchem} % Formulas using \ce{}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Many journals require that sections are unnumbered: this
%% is activated here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\setcounter{secnumdepth}{-1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Place any additional macros here. Please use \newcommand* where
%% possible, and avoid layout-changing macros (which are not used
%% when typesetting).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand*\mycommand[1]{\texttt{\emph{#1}}}
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\usepackage{longtable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Author and title data:
%% the authblk package is currently the simplest way to provide this
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{authblk}
\author[1]{Carlos Daniel Sierra Álvarez}
\author[1]{Juan Francisco Moreno Luna}
\author[1]{José Julián Sierra Álvarez}
\author[1]{José Jovani Martínez}
\author[1,*]{Robert Winkler}
\affil[1]{Advanced Genomics Unit, Cinvestav, km 9.6 Libr. Nte. Irapuato-León, Irapuato, 36824, Gto., Mexico.}
\title{$title$}
% Use the \date command for email address(s) of corresponding authors
\date{*Email: robert.winkler@cinvestav.mx}
\begin{document}
\maketitle
\begin{abstract}
$abstract$
\end{abstract}
\section*{Keywords}
$keywords$
$body$
\printbibliography
\end{document}
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env bash
# =============================================================================
# run_full_pipeline.sh -- seven-stage MSI pipeline (one or many datasets)
#
# bash run_full_pipeline.sh # every dataset under ai_data/
# bash run_full_pipeline.sh Datura_leaf # a single dataset
# MSI_K=5 bash run_full_pipeline.sh Datura_leaf
#
# Each dataset lives in ai_data/<name>/ and must contain exactly one
# .imzML file and its sibling .ibd binary (optional ROI mask .png).
#
# Stages: 1 Julia preprocessing -> 2 SimCLR -> 3 K sweep -> 4 t-SNE + K-Means
# -> 5 quantitative validation -> 6 per-cluster galleries
# -> 7 mean / per-cluster mass spectra.
# =============================================================================
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DATA_ROOT="${MSI_DATA_ROOT:-$ROOT/ai_data}"
ENV_DIR="$ROOT/environment"
# Native runs: prefer a repo-local venv/ if one exists (ignored inside Docker).
if [ -x "$ROOT/venv/bin/python" ]; then
export PATH="$ROOT/venv/bin:$PATH"
fi
if [ ! -d "$DATA_ROOT" ]; then
echo "ERROR: dataset root '$DATA_ROOT' not found." >&2
echo " Create it and add ai_data/<name>/<file>.imzML (+ .ibd)." >&2
exit 1
fi
# Which datasets to run (explicit args, else every folder holding an .imzML)
if [ "$#" -gt 0 ]; then
DATASETS=("$@")
else
DATASETS=()
while IFS= read -r name; do
[ -n "$name" ] && DATASETS+=("$name")
done < <(for d in "$DATA_ROOT"/*/; do
[ -d "$d" ] || continue
# Case-insensitive match (.imzML / .imzml / .IMZML); `find -iname` avoids the
# glob-pair pitfall where a non-matching pattern makes `ls` return non-zero.
if [ -n "$(find "$d" -maxdepth 1 -type f -iname '*.imzml' -print -quit 2>/dev/null)" ]; then
basename "$d"
fi
done | sort)
fi
if [ "${#DATASETS[@]}" -eq 0 ]; then
echo "ERROR: no datasets with an .imzML found under '$DATA_ROOT'." >&2
echo " Each dataset must be in its own subfolder:" >&2
echo " $DATA_ROOT/<name>/<file>.imzML (+ <file>.ibd)" >&2
if [ -n "$(find "$DATA_ROOT" -maxdepth 1 -type f -iname '*.imzml' -print -quit 2>/dev/null)" ]; then
echo " Note: .imzML file(s) were found directly in '$DATA_ROOT' (loose files are ignored)." >&2
echo " Move each into its own subfolder, e.g.:" >&2
echo " mkdir -p $DATA_ROOT/<name> && mv $DATA_ROOT/*.imzML $DATA_ROOT/*.ibd $DATA_ROOT/<name>/" >&2
fi
exit 1
fi
echo "Data root: $DATA_ROOT"
echo "Datasets : ${DATASETS[*]}"
for ds in "${DATASETS[@]}"; do
ds_dir="$DATA_ROOT/$ds"
if [ ! -d "$ds_dir" ]; then
echo "ERROR: '$ds_dir' not found." >&2
exit 1
fi
echo ""
echo "########## $ds ##########"
echo "--- Stage 1/7: Julia preprocessing ---"
julia --threads auto --project="$ENV_DIR" \
"$ROOT/scripts_julia/julia_msi_bridge.jl" "$ds_dir" "$ds"
echo "--- Stage 2/7: SimCLR training ---"
python3 "$ROOT/scripts_python/CNN_proof_1.py" "$ds"
echo "--- Stage 3/7: clustering evaluation (K sweep 2..20) ---"
python3 "$ROOT/scripts_python/evaluate_clustering.py" "$ds"
# K for stages 4/5: explicit MSI_K wins, else the Silhouette optimum from Stage 3.
K="${MSI_K:-}"
if [ -z "$K" ]; then
kfile="$ROOT/outputs/$ds/best_k_results.csv"
K="$(awk -F, '$1=="best_k_silhouette"{print $2}' "$kfile" 2>/dev/null | tr -d '[:space:]')"
fi
if [ -n "$K" ]; then
echo "--- Stage 4/7: t-SNE + K-Means (K=$K) ---"
python3 "$ROOT/scripts_python/graph_tsne_msi.py" "$ds" "$K"
echo "--- Stage 5/7: quantitative validation (K=$K) ---"
python3 "$ROOT/scripts_python/quantitative_validation.py" "$ds" "$K"
echo "--- Stage 6/7: per-cluster galleries ---"
python3 "$ROOT/scripts_python/visualize_clusters.py" "$ds"
else
echo "WARNING: could not determine best K for '$ds'; skipping stages 4-6." >&2
fi
echo "--- Stage 7/7: mass spectra ---"
julia --project="$ENV_DIR" \
"$ROOT/scripts_julia/plot_mass_spectra.jl" "$ds" "$ds_dir"
echo "########## $ds done ##########"
done
echo ""
echo "All done. Outputs are under $ROOT/outputs/"
+1 -1
View File
@@ -1,6 +1,6 @@
using Pkg using Pkg
script_dir = @__DIR__ script_dir = @__DIR__
project_root = joinpath(script_dir, "..", "..") project_root = joinpath(script_dir, "..")
Pkg.activate(joinpath(project_root, "environment")) Pkg.activate(joinpath(project_root, "environment"))
ENV["GKSwstype"] = "100" ENV["GKSwstype"] = "100"
+7 -6
View File
@@ -1,6 +1,6 @@
using Pkg using Pkg
script_dir = @__DIR__ script_dir = @__DIR__
project_root = joinpath(script_dir, "..", "..") project_root = joinpath(script_dir, "..")
Pkg.activate(joinpath(project_root, "environment")) Pkg.activate(joinpath(project_root, "environment"))
@@ -8,7 +8,6 @@ push!(LOAD_PATH, joinpath(project_root, "src"))
include(joinpath(project_root, "src", "MSI_src.jl")) include(joinpath(project_root, "src", "MSI_src.jl"))
using .MSI_src using .MSI_src
using Statistics, Images, Interpolations, BenchmarkTools using Statistics, Images, Interpolations, BenchmarkTools
import julia_mzML_imzML
data_dir = length(ARGS) >= 1 ? ARGS[1] : joinpath(project_root, "data") data_dir = length(ARGS) >= 1 ? ARGS[1] : joinpath(project_root, "data")
dataset_name = length(ARGS) >= 2 ? ARGS[2] : splitdir(data_dir)[2] dataset_name = length(ARGS) >= 2 ? ARGS[2] : splitdir(data_dir)[2]
@@ -24,7 +23,9 @@ data_path = joinpath(data_dir, imzml_files[1])
mask_path = joinpath(data_dir, "region_of_interest.png") mask_path = joinpath(data_dir, "region_of_interest.png")
if !isfile(mask_path) if !isfile(mask_path)
alt_masks = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir)) alt_masks = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir))
mask_path = isempty(alt_masks) ? "" : joinpath(data_dir, alt_masks[1]) # `nothing` (not "") means "no mask": MSI_src treats nothing as unmasked, whereas
# an empty string is interpreted as a path and errors in load_and_prepare_mask.
mask_path = isempty(alt_masks) ? nothing : joinpath(data_dir, alt_masks[1])
end end
output_folder = joinpath(project_root, "outputs", "ion_images", dataset_name) output_folder = joinpath(project_root, "outputs", "ion_images", dataset_name)
@@ -35,7 +36,7 @@ mkpath(viridis_folder)
println("--- JULIA BATCH ENGINE: $dataset_name ---") println("--- JULIA BATCH ENGINE: $dataset_name ---")
println("Data: $data_path") println("Data: $data_path")
println("Mask: $(isempty(mask_path) ? "none" : mask_path)") println("Mask: $(mask_path === nothing ? "none" : mask_path)")
println("Output (grayscale): $output_folder") println("Output (grayscale): $output_folder")
println("Output (viridis): $viridis_folder") println("Output (viridis): $viridis_folder")
@@ -43,7 +44,7 @@ println("--- JULIA BATCH ENGINE ---")
# Apply Julia's native ViridisPalette (256-entry, 0xRRGGBB) to a 0..255 intensity map. # Apply Julia's native ViridisPalette (256-entry, 0xRRGGBB) to a 0..255 intensity map.
function apply_viridis(intensity_matrix::AbstractMatrix{Float32}) function apply_viridis(intensity_matrix::AbstractMatrix{Float32})
palette = julia_mzML_imzML.ViridisPalette palette = MSI_src.ViridisPalette
h, w = size(intensity_matrix) h, w = size(intensity_matrix)
rgb = Matrix{RGB{N0f8}}(undef, h, w) rgb = Matrix{RGB{N0f8}}(undef, h, w)
@inbounds for j in 1:w, i in 1:h @inbounds for j in 1:w, i in 1:h
@@ -186,7 +187,7 @@ function run_production_pipeline()
end end
println("Step 5+6: Batched Ion Extraction, TrIQ Normalization & 256x256 Zero-Padding...") println("Step 5+6: Batched Ion Extraction, TrIQ Normalization & 256x256 Zero-Padding...")
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2])) mask_matrix = mask_path === nothing ? nothing : MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
exported_count = Threads.Atomic{Int}(0) exported_count = Threads.Atomic{Int}(0)
target_size = (256, 256) target_size = (256, 256)
+24 -24
View File
@@ -1,7 +1,7 @@
using MSI_src using MSI_src
using Statistics, Plots, Images using Statistics, Plots, Images
# 1. Definir función de contraste (si no la tienes ya en la sesión) # 1. Define the contrast function (if you do not already have it in the session)
function apply_triq(img_matrix) function apply_triq(img_matrix)
vals = filter(x -> x > 0 && isfinite(x), img_matrix) vals = filter(x -> x > 0 && isfinite(x), img_matrix)
if isempty(vals) return img_matrix end if isempty(vals) return img_matrix end
@@ -10,45 +10,45 @@ function apply_triq(img_matrix)
return clamp.(img_matrix ./ q, 0.0, 1.0) return clamp.(img_matrix ./ q, 0.0, 1.0)
end end
# 2. Configuración de rutas # 2. Path configuration
path_data = "Hoja.imzML" path_data = "Leaf.imzML"
path_mask = "region_interes.png" path_mask = "region_of_interest.png"
output_folder = "resultados_expertos/batch_triq" output_folder = "expert_results/batch_triq"
mkpath(output_folder) mkpath(output_folder)
# 3. Carga de datos # 3. Data loading
data = OpenMSIData(path_data) data = OpenMSIData(path_data)
# 4. Obtener espectro promedio SOLO de la zona de la máscara (ROI) # 4. Get the average spectrum ONLY for the mask region (ROI)
println("Calculando espectro promedio en la ROI...") println("Computing average spectrum over the ROI...")
# Nota: Usamos la función de MSI_src para obtener el promedio filtrado # Note: We use the MSI_src function to obtain the filtered average
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=path_mask) mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=path_mask)
# 5. Identificar picos importantes (ej. > 2% del pico base) # 5. Identify important peaks (e.g. > 2% of the base peak)
max_int = maximum(avg_ints) max_int = maximum(avg_ints)
umbral = max_int * 0.02 # Ajusta este valor (0.01 para 1%, 0.05 para 5%) threshold = max_int * 0.02 # Adjust this value (0.01 for 1%, 0.05 for 5%)
indices_picos = findall(x -> x > umbral, avg_ints) peak_indices = findall(x -> x > threshold, avg_ints)
println("Se encontraron $(length(indices_picos)) iones que superan el umbral.") println("Found $(length(peak_indices)) ions above the threshold.")
# 6. Bucle para generar imágenes con TrIQ # 6. Loop to generate images with TrIQ
for idx in indices_picos for idx in peak_indices
mz_val = mzs[idx] mz_val = mzs[idx]
# Validar rango (ejemplo: m/z 50 a 700) # Validate range (example: m/z 50 to 700)
if mz_val < 50.0 || mz_val > 700.0 if mz_val < 50.0 || mz_val > 700.0
continue continue
end end
println("Procesando m/z: $(round(mz_val, digits=2))") println("Processing m/z: $(round(mz_val, digits=2))")
# A. Extraer los datos crudos con la máscara aplicada # A. Extract the raw data with the mask applied
raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=path_mask) raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=path_mask)
# B. Aplicar contraste TrIQ # B. Apply TrIQ contrast
enhanced_slice = apply_triq(raw_slice) enhanced_slice = apply_triq(raw_slice)
# C. Crear el mapa de calor (Heatmap) # C. Create the heatmap
p = heatmap(enhanced_slice, p = heatmap(enhanced_slice,
title="Ion m/z: $(round(mz_val, digits=2))", title="Ion m/z: $(round(mz_val, digits=2))",
color=:viridis, color=:viridis,
@@ -56,9 +56,9 @@ for idx in indices_picos
yflip=true, yflip=true,
xaxis=false, yaxis=false) xaxis=false, yaxis=false)
# D. Guardar # D. Save
nombre_archivo = "ion_$(round(mz_val, digits=2))_triq.png" filename = "ion_$(round(mz_val, digits=2))_triq.png"
savefig(p, joinpath(output_folder, nombre_archivo)) savefig(p, joinpath(output_folder, filename))
end end
println("--- Proceso completado. Revisa la carpeta: $output_folder ---") println("--- Process completed. Check the folder: $output_folder ---")
+1 -1
View File
@@ -4,7 +4,7 @@ using Statistics, Images, Interpolations
# 1. Configuration # 1. Configuration
data_path = "Leaf.imzML" data_path = "Leaf.imzML"
mask_path = "region_of_interest.png" mask_path = "region_of_interest.png"
output_folder = "datos_para_ai" output_folder = "ai_data"
img_size = (224, 224) # Standard size for CNN img_size = (224, 224) # Standard size for CNN
mkpath(output_folder) mkpath(output_folder)
+7 -4
View File
@@ -1,6 +1,6 @@
using Pkg using Pkg
script_dir = @__DIR__ script_dir = @__DIR__
project_root = joinpath(script_dir, "..", "..") project_root = joinpath(script_dir, "..")
Pkg.activate(joinpath(project_root, "environment")) Pkg.activate(joinpath(project_root, "environment"))
ENV["GKSwstype"] = "100" ENV["GKSwstype"] = "100"
@@ -13,7 +13,9 @@ using CSV, DataFrames, Statistics
using Plots.Measures using Plots.Measures
dataset_name = length(ARGS) >= 1 ? ARGS[1] : "leaf" dataset_name = length(ARGS) >= 1 ? ARGS[1] : "leaf"
data_dir = joinpath(project_root, "datasets", dataset_name) # Second positional arg (optional) overrides the dataset directory, e.g.
# `julia plot_mass_spectra.jl Datura_leaf /path/to/ai_data/Datura_leaf`.
data_dir = length(ARGS) >= 2 ? ARGS[2] : joinpath(project_root, "ai_data", dataset_name)
output_dir = joinpath(project_root, "outputs", dataset_name) output_dir = joinpath(project_root, "outputs", dataset_name)
figures_dir = joinpath(output_dir, "figures") figures_dir = joinpath(output_dir, "figures")
cluster_csv = joinpath(output_dir, "msi_clusters_results.csv") cluster_csv = joinpath(output_dir, "msi_clusters_results.csv")
@@ -26,7 +28,8 @@ data_path = joinpath(data_dir, imzml_files[1])
mask_path = joinpath(data_dir, "region_of_interest.png") mask_path = joinpath(data_dir, "region_of_interest.png")
if !isfile(mask_path) if !isfile(mask_path)
alt = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir)) alt = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir))
mask_path = isempty(alt) ? "" : joinpath(data_dir, alt[1]) # `nothing` means "no mask" (see julia_msi_bridge.jl); "" would be treated as a path.
mask_path = isempty(alt) ? nothing : joinpath(data_dir, alt[1])
end end
println("Loading data: $data_path") println("Loading data: $data_path")
@@ -50,7 +53,7 @@ if !isempty(bin_avg)
# Apply the ROI mask (if present) so off-tissue pixels are excluded, matching # Apply the ROI mask (if present) so off-tissue pixels are excluded, matching
# the masked get_average_spectrum path and the Stage 1 extraction policy. # the masked get_average_spectrum path and the Stage 1 extraction policy.
mask_mat = nothing mask_mat = nothing
if mask_path != "" && isfile(mask_path) if mask_path !== nothing && isfile(mask_path)
mask_mat = MSI_src.load_and_prepare_mask(mask_path, data.image_dims) mask_mat = MSI_src.load_and_prepare_mask(mask_path, data.image_dims)
end end
for i in 1:size(data.imzml_data, 2) for i in 1:size(data.imzml_data, 2)
+2 -2
View File
@@ -27,8 +27,8 @@ set_seed(42)
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf" dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name) IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images", dataset_name)
MODEL_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name) MODEL_DIR = os.path.join(BASE_DIR, "..", "outputs", "models", dataset_name)
MODEL_SAVE_PATH = os.path.join(MODEL_DIR, "msi_encoder_trained.pth") MODEL_SAVE_PATH = os.path.join(MODEL_DIR, "msi_encoder_trained.pth")
BATCH_SIZE = 8 BATCH_SIZE = 8
@@ -7,7 +7,7 @@ import matplotlib.pyplot as plt
import matplotlib.cm as cm import matplotlib.cm as cm
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BENCH_CSV = os.path.join(ROOT, "Benchmark_recommendation", "results", "cross_language_benchmark.csv") BENCH_CSV = os.path.join(ROOT, "Benchmark_recommendation", "results", "cross_language_benchmark.csv")
GAL = os.path.join(ROOT, "outputs") GAL = os.path.join(ROOT, "outputs")
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf" FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
+3 -3
View File
@@ -27,9 +27,9 @@ set_seed(42)
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf" dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name) IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images", dataset_name)
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth") MODEL_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name) OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs", dataset_name)
FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures") FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
K_RANGE = range(2, 21) # overridden per-dataset below to respect small corpora K_RANGE = range(2, 21) # overridden per-dataset below to respect small corpora
+3 -3
View File
@@ -24,9 +24,9 @@ def set_seed(seed=42):
set_seed(42) set_seed(42)
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth") MODEL_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", "msi_encoder_trained.pth")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs_k5") OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs_k5")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
K_RANGE = range(2, 21) K_RANGE = range(2, 21)
+4 -4
View File
@@ -30,9 +30,9 @@ dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
TARGET_K = int(sys.argv[2]) if len(sys.argv) > 2 else 10 TARGET_K = int(sys.argv[2]) if len(sys.argv) > 2 else 10
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name) IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images", dataset_name)
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth") ENCODER_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name) OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs", dataset_name)
FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures") FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -128,7 +128,7 @@ if __name__ == "__main__":
) )
embeddings_2d = tsne.fit_transform(features_pca) embeddings_2d = tsne.fit_transform(features_pca)
output_dir = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name) output_dir = os.path.join(BASE_DIR, "..", "outputs", dataset_name)
figures_dir = os.path.join(output_dir, "figures") figures_dir = os.path.join(output_dir, "figures")
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
os.makedirs(figures_dir, exist_ok=True) os.makedirs(figures_dir, exist_ok=True)
+3 -3
View File
@@ -25,8 +25,8 @@ def set_seed(seed=42):
set_seed(42) set_seed(42)
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth") ENCODER_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", "msi_encoder_trained.pth")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
TARGET_K = 5 TARGET_K = 5
@@ -121,7 +121,7 @@ if __name__ == "__main__":
) )
embeddings_2d = tsne.fit_transform(features_pca) embeddings_2d = tsne.fit_transform(features_pca)
output_dir = os.path.join(BASE_DIR, "..", "..", "outputs_k5") output_dir = os.path.join(BASE_DIR, "..", "outputs_k5")
figures_dir = os.path.join(output_dir, "figures") figures_dir = os.path.join(output_dir, "figures")
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
os.makedirs(figures_dir, exist_ok=True) os.makedirs(figures_dir, exist_ok=True)
+3 -3
View File
@@ -9,9 +9,9 @@ import torch.nn.functional as F
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth") ENCODER_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", "msi_encoder_trained.pth")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "figures", "guided_validation") OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs", "figures", "guided_validation")
os.makedirs(OUTPUT_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True)
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+28 -28
View File
@@ -12,24 +12,24 @@ from sklearn.manifold import TSNE
import pandas as pd import pandas as pd
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
# 1. CONFIGURACIÓN # 1. CONFIGURATION
IMG_DIR = "datos_para_ai" IMG_DIR = "ai_data"
OUTPUT_DIR = "pruebas_clusters" OUTPUT_DIR = "cluster_tests"
N_CLUSTERS = 10 N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
os.makedirs(OUTPUT_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True)
# 2. CARGAR MODELO PRE-ENTRENADO (Directo de PyTorch) # 2. LOAD PRETRAINED MODEL (Directly from PyTorch)
def get_pretrained_extractor(): def get_pretrained_extractor():
# Usamos los pesos por defecto de ImageNet # We use the default ImageNet weights
model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT) model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
model.classifier = nn.Identity() # Quitamos la capa de clasificación model.classifier = nn.Identity() # Remove the classification layer
model.to(DEVICE) model.to(DEVICE)
model.eval() model.eval()
return model return model
# 3. DATASET CON NORMALIZACIÓN ESTÁNDAR # 3. DATASET WITH STANDARD NORMALIZATION
class MSIDatasetDirect(Dataset): class MSIDatasetDirect(Dataset):
def __init__(self, img_dir): def __init__(self, img_dir):
self.img_dir = img_dir self.img_dir = img_dir
@@ -37,7 +37,7 @@ class MSIDatasetDirect(Dataset):
self.transform = transforms.Compose([ self.transform = transforms.Compose([
transforms.Resize((224, 224)), transforms.Resize((224, 224)),
transforms.ToTensor(), transforms.ToTensor(),
# Normalización obligatoria para modelos pre-entrenados # Normalization required for pretrained models
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
]) ])
@@ -50,7 +50,7 @@ class MSIDatasetDirect(Dataset):
return self.transform(image), self.img_names[idx] return self.transform(image), self.img_names[idx]
if __name__ == "__main__": if __name__ == "__main__":
print(f"Extrayendo características con red pre-entrenada en {DEVICE}...") print(f"Extracting features with the pretrained network on {DEVICE}...")
model = get_pretrained_extractor() model = get_pretrained_extractor()
dataset = MSIDatasetDirect(IMG_DIR) dataset = MSIDatasetDirect(IMG_DIR)
loader = DataLoader(dataset, batch_size=1, shuffle=False) loader = DataLoader(dataset, batch_size=1, shuffle=False)
@@ -62,55 +62,55 @@ if __name__ == "__main__":
for img, name in loader: for img, name in loader:
img = img.to(DEVICE) img = img.to(DEVICE)
feat = model(img) feat = model(img)
# Aplanar el vector de características (1280 dimensiones para EffNet-B0) # Flatten the feature vector (1280 dimensions for EffNet-B0)
features.append(feat.cpu().numpy().flatten()) features.append(feat.cpu().numpy().flatten())
ion_names.append(name[0]) ion_names.append(name[0])
features = np.array(features) features = np.array(features)
print(f"Características extraídas: {features.shape}") print(f"Extracted features: {features.shape}")
# 4. REDUCCIÓN DE DIMENSIONALIDAD (PCA) # 4. DIMENSIONALITY REDUCTION (PCA)
# Esto ayuda a que el clustering no se pierda en dimensiones irrelevantes # This helps clustering from getting lost in irrelevant dimensions
print("Reduciendo ruido con PCA...") print("Reducing noise with PCA...")
features_scaled = StandardScaler().fit_transform(features) features_scaled = StandardScaler().fit_transform(features)
pca = PCA(n_components=0.95) # Mantenemos el 95% de la varianza pca = PCA(n_components=0.95) # We keep 95% of the variance
features_pca = pca.fit_transform(features_scaled) features_pca = pca.fit_transform(features_scaled)
print(f"Dimensiones tras PCA: {features_pca.shape[1]}") print(f"Dimensions after PCA: {features_pca.shape[1]}")
# 5. CLUSTERING K-MEANS # 5. K-MEANS CLUSTERING
print(f"Agrupando en {N_CLUSTERS} clusters...") print(f"Grouping into {N_CLUSTERS} clusters...")
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42) km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
labels = km.fit_predict(features_pca) labels = km.fit_predict(features_pca)
# 6. VISUALIZACIÓN (t-SNE) # 6. VISUALIZATION (t-SNE)
print("Generando visualización t-SNE para verificar consistencia...") print("Generating t-SNE visualization to verify consistency...")
tsne = TSNE(n_components=2, random_state=42) tsne = TSNE(n_components=2, random_state=42)
features_tsne = tsne.fit_transform(features_pca) features_tsne = tsne.fit_transform(features_pca)
plt.figure(figsize=(10, 8)) plt.figure(figsize=(10, 8))
scatter = plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=labels, cmap='tab10', alpha=0.7) scatter = plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=labels, cmap='tab10', alpha=0.7)
plt.colorbar(scatter, ticks=range(N_CLUSTERS), label='Cluster ID') plt.colorbar(scatter, ticks=range(N_CLUSTERS), label='Cluster ID')
plt.title(f"Visualización de Clusters (K={N_CLUSTERS}) - Directo") plt.title(f"Cluster Visualization (K={N_CLUSTERS}) - Direct")
plt.xlabel("t-SNE 1") plt.xlabel("t-SNE 1")
plt.ylabel("t-SNE 2") plt.ylabel("t-SNE 2")
plt.grid(True, linestyle='--', alpha=0.5) plt.grid(True, linestyle='--', alpha=0.5)
plt.savefig(os.path.join(OUTPUT_DIR, "msi_clusters_direct_plot.png")) plt.savefig(os.path.join(OUTPUT_DIR, "msi_clusters_direct_plot.png"))
print(f"Gráfico de consistencia guardado en '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.") print(f"Consistency plot saved to '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
# 7. GUARDAR Y REPORTAR # 7. SAVE AND REPORT
df = pd.DataFrame({'ion_image': ion_names, 'cluster': labels}) df = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
df['mz'] = df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float) df['mz'] = df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_results.csv"), index=False) df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_results.csv"), index=False)
# Crear un resumen de cuántos iones hay por cluster # Create a summary of how many ions there are per cluster
print("\nResumen de Clusters (Consistente con el CSV y el Gráfico):") print("\nCluster Summary (Consistent with the CSV and the Plot):")
counts = df['cluster'].value_counts().sort_index() counts = df['cluster'].value_counts().sort_index()
print(counts) print(counts)
# Guardar también el resumen para evitar confusiones con otros archivos # Also save the summary to avoid confusion with other files
summary_df = counts.reset_index() summary_df = counts.reset_index()
summary_df.columns = ['Cluster_ID', 'Ion_Count'] summary_df.columns = ['Cluster_ID', 'Ion_Count']
summary_df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_summary.csv"), index=False) summary_df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_summary.csv"), index=False)
print(f"\nResultados guardados en '{OUTPUT_DIR}/msi_clusters_direct_results.csv' y '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.") print(f"\nResults saved to '{OUTPUT_DIR}/msi_clusters_direct_results.csv' and '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
print(f"Usa '{OUTPUT_DIR}/msi_clusters_direct_plot.png' para validar visualmente los puntos.") print(f"Use '{OUTPUT_DIR}/msi_clusters_direct_plot.png' to visually validate the points.")
@@ -10,17 +10,17 @@ from sklearn.manifold import TSNE
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import pandas as pd import pandas as pd
# 1. CONFIGURACIÓN # 1. CONFIGURATION
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "../..", "datos_para_ai") IMG_DIR = os.path.join(BASE_DIR, "../..", "ai_data")
ENCODER_PATH = os.path.join(BASE_DIR, "../..", "models", "msi_encoder_trained.pth") ENCODER_PATH = os.path.join(BASE_DIR, "../..", "models", "msi_encoder_trained.pth")
N_CLUSTERS = 10 N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. CARGAR EL MODELO ENTRENADO # 2. LOAD THE TRAINED MODEL
def load_trained_encoder(path): def load_trained_encoder(path):
if not os.path.exists(path): if not os.path.exists(path):
raise FileNotFoundError(f"No se encontró el modelo en {path}") raise FileNotFoundError(f"Model not found at {path}")
model = models.efficientnet_b0() model = models.efficientnet_b0()
model.classifier = nn.Identity() model.classifier = nn.Identity()
@@ -31,7 +31,7 @@ def load_trained_encoder(path):
model.eval() model.eval()
return model return model
# 3. DATASET PARA INFERENCIA # 3. DATASET FOR INFERENCE
class MSIDatasetInference(Dataset): class MSIDatasetInference(Dataset):
def __init__(self, img_dir): def __init__(self, img_dir):
self.img_dir = img_dir self.img_dir = img_dir
@@ -49,18 +49,18 @@ class MSIDatasetInference(Dataset):
image = Image.open(img_path).convert("RGB") image = Image.open(img_path).convert("RGB")
return self.transform(image), self.img_names[idx] return self.transform(image), self.img_names[idx]
# --- PROCESO --- # --- PROCESS ---
if __name__ == "__main__": if __name__ == "__main__":
print("Extrayendo características con el encoder...") print("Extracting features with the encoder...")
try: try:
encoder = load_trained_encoder(ENCODER_PATH) encoder = load_trained_encoder(ENCODER_PATH)
except Exception as e: except Exception as e:
print(f"Error al cargar el modelo: {e}") print(f"Error loading the model: {e}")
exit(1) exit(1)
dataset = MSIDatasetInference(IMG_DIR) dataset = MSIDatasetInference(IMG_DIR)
if len(dataset) == 0: if len(dataset) == 0:
print(f"No se encontraron imágenes en {IMG_DIR}") print(f"No images found in {IMG_DIR}")
exit(1) exit(1)
loader = DataLoader(dataset, batch_size=1, shuffle=False) loader = DataLoader(dataset, batch_size=1, shuffle=False)
@@ -72,28 +72,28 @@ if __name__ == "__main__":
for img, name in loader: for img, name in loader:
img = img.to(DEVICE) img = img.to(DEVICE)
feat = encoder(img) feat = encoder(img)
# Normalización L2 # L2 normalization
feat = feat / feat.norm(p=2, dim=1, keepdim=True) feat = feat / feat.norm(p=2, dim=1, keepdim=True)
features.append(feat.cpu().numpy().flatten()) features.append(feat.cpu().numpy().flatten())
ion_names.append(name[0]) ion_names.append(name[0])
features = np.array(features) features = np.array(features)
# 4. CLUSTERING K-MEANS # 4. K-MEANS CLUSTERING
print(f"Realizando KMeans con {N_CLUSTERS} clusters...") print(f"Running KMeans with {N_CLUSTERS} clusters...")
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42) km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
labels = km.fit_predict(features) labels = km.fit_predict(features)
# 5. VISUALIZACIÓN t-SNE CORREGIDA # 5. CORRECTED t-SNE VISUALIZATION
print("Generando visualización t-SNE con escala corregida...") print("Generating t-SNE visualization with corrected scale...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42) tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features) embeddings_2d = tsne.fit_transform(features)
plt.figure(figsize=(10, 8)) plt.figure(figsize=(10, 8))
# Aplicando tu corrección específica: # Applying your specific correction:
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50) scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50)
# Configuración de la barra de colores con los ticks exactos para 10 clusters # Configure the colorbar with exact ticks for 10 clusters
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS)) cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
cbar.set_label('Cluster ID') cbar.set_label('Cluster ID')
@@ -102,8 +102,8 @@ if __name__ == "__main__":
plt.ylabel("t-SNE dimension 2") plt.ylabel("t-SNE dimension 2")
plt.grid(True, linestyle='--', alpha=0.5) plt.grid(True, linestyle='--', alpha=0.5)
output_file = "msi_tsne_corregido.png" output_file = "msi_tsne_corrected.png"
plt.savefig(output_file, dpi=300, bbox_inches='tight') plt.savefig(output_file, dpi=300, bbox_inches='tight')
# plt.show() # plt.show()
print(f"Visualización guardada exitosamente en '{output_file}'.") print(f"Visualization successfully saved to '{output_file}'.")
@@ -9,17 +9,17 @@ from sklearn.manifold import TSNE
import pandas as pd import pandas as pd
import plotly.express as px import plotly.express as px
# 1. CONFIGURACIÓN # 1. CONFIGURATION
IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai" IMG_DIR = "/home/sierra/Documents/Test teams/Julia_msi_GUI-main/ai_data"
ENCODER_PATH = "Reporte/Model/msi_encoder_trained.pth" ENCODER_PATH = "Report/Model/msi_encoder_trained.pth"
CSV_PATH = "msi_clusters_results.csv" # Fuente de verdad CSV_PATH = "msi_clusters_results.csv" # Source of truth
N_CLUSTERS = 10 N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. CARGAR EL MODELO ENTRENADO # 2. LOAD THE TRAINED MODEL
def load_trained_encoder(path): def load_trained_encoder(path):
if not os.path.exists(path): if not os.path.exists(path):
raise FileNotFoundError(f"No se encontró el modelo en {path}") raise FileNotFoundError(f"Model not found at {path}")
model = models.efficientnet_b0() model = models.efficientnet_b0()
model.classifier = nn.Identity() model.classifier = nn.Identity()
@@ -30,7 +30,7 @@ def load_trained_encoder(path):
model.eval() model.eval()
return model return model
# 3. DATASET BASADO EN EL CSV # 3. DATASET BASED ON THE CSV
class MSIDatasetFromCSV(Dataset): class MSIDatasetFromCSV(Dataset):
def __init__(self, img_dir, img_names): def __init__(self, img_dir, img_names):
self.img_dir = img_dir self.img_dir = img_dir
@@ -48,17 +48,17 @@ class MSIDatasetFromCSV(Dataset):
image = Image.open(img_path).convert("RGB") image = Image.open(img_path).convert("RGB")
return self.transform(image) return self.transform(image)
# --- PROCESO --- # --- PROCESS ---
if __name__ == "__main__": if __name__ == "__main__":
# 4. CARGAR EL CSV DE RESULTADOS # 4. LOAD THE RESULTS CSV
print(f"Cargando datos desde {CSV_PATH}...") print(f"Loading data from {CSV_PATH}...")
df = pd.read_csv(CSV_PATH) df = pd.read_csv(CSV_PATH)
ion_names = df['ion_image'].tolist() ion_names = df['ion_image'].tolist()
# Asegurarnos de que cluster sea categórico para Plotly # Make sure cluster is categorical for Plotly
df['cluster'] = df['cluster'].astype(str) df['cluster'] = df['cluster'].astype(str)
print("Extrayendo características con el encoder...") print("Extracting features with the encoder...")
encoder = load_trained_encoder(ENCODER_PATH) encoder = load_trained_encoder(ENCODER_PATH)
dataset = MSIDatasetFromCSV(IMG_DIR, ion_names) dataset = MSIDatasetFromCSV(IMG_DIR, ion_names)
loader = DataLoader(dataset, batch_size=1, shuffle=False) loader = DataLoader(dataset, batch_size=1, shuffle=False)
@@ -68,40 +68,40 @@ if __name__ == "__main__":
for i, img in enumerate(loader): for i, img in enumerate(loader):
img = img.to(DEVICE) img = img.to(DEVICE)
feat = encoder(img) feat = encoder(img)
# Normalización L2 # L2 normalization
feat = feat / feat.norm(p=2, dim=1, keepdim=True) feat = feat / feat.norm(p=2, dim=1, keepdim=True)
features.append(feat.cpu().numpy().flatten()) features.append(feat.cpu().numpy().flatten())
if (i+1) % 100 == 0: if (i+1) % 100 == 0:
print(f"Iones procesados: {i+1}/{len(ion_names)}") print(f"Ions processed: {i+1}/{len(ion_names)}")
features = np.array(features) features = np.array(features)
# 5. t-SNE # 5. t-SNE
print("Calculando t-SNE...") print("Computing t-SNE...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42) tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features) embeddings_2d = tsne.fit_transform(features)
# Agregar coordenadas t-SNE al DataFrame original # Add t-SNE coordinates to the original DataFrame
df['tsne_1'] = embeddings_2d[:, 0] df['tsne_1'] = embeddings_2d[:, 0]
df['tsne_2'] = embeddings_2d[:, 1] df['tsne_2'] = embeddings_2d[:, 1]
# 6. VISUALIZACIÓN INTERACTIVA CON PLOTLY # 6. INTERACTIVE VISUALIZATION WITH PLOTLY
print("Generando gráfica interactiva con Plotly...") print("Generating interactive plot with Plotly...")
# Usar escala de colores similar a tab10 o cualitativa estándar # Use a color scale similar to tab10 or the standard qualitative one
fig = px.scatter( fig = px.scatter(
df, df,
x='tsne_1', x='tsne_1',
y='tsne_2', y='tsne_2',
color='cluster', color='cluster',
hover_data={'ion_image': True, 'mz': True, 'cluster': True, 'tsne_1': False, 'tsne_2': False}, 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})", title=f"Interactive t-SNE of MSI Ions (Consistent with {CSV_PATH})",
labels={'tsne_1': 't-SNE 1', 'tsne_2': 't-SNE 2'}, labels={'tsne_1': 't-SNE 1', 'tsne_2': 't-SNE 2'},
category_orders={"cluster": [str(i) for i in range(N_CLUSTERS)]}, category_orders={"cluster": [str(i) for i in range(N_CLUSTERS)]},
color_discrete_sequence=px.colors.qualitative.Plotly # O T10 si está disponible color_discrete_sequence=px.colors.qualitative.Plotly # Or T10 if available
) )
# Mejorar el diseño # Improve the layout
fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey'))) fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey')))
fig.update_layout( fig.update_layout(
legend_title_text='Cluster ID', legend_title_text='Cluster ID',
@@ -109,9 +109,9 @@ if __name__ == "__main__":
hoverlabel=dict(bgcolor="white", font_size=16) hoverlabel=dict(bgcolor="white", font_size=16)
) )
# Guardar como HTML # Save as HTML
output_html = "msi_tsne_interactivo.html" output_html = "msi_tsne_interactive.html"
fig.write_html(output_html) fig.write_html(output_html)
print(f"\n¡Éxito! Gráfica interactiva guardada en '{output_html}'.") print(f"\nSuccess! Interactive plot saved to '{output_html}'.")
print("Puedes abrir este archivo en cualquier navegador para explorar los clusters.") print("You can open this file in any browser to explore the clusters.")
+4 -2
View File
@@ -103,10 +103,12 @@ def main():
ap.add_argument("dataset") ap.add_argument("dataset")
ap.add_argument("--tile-size", type=int, default=96) ap.add_argument("--tile-size", type=int, default=96)
ap.add_argument("--clusters", action="store_true", help="also emit per-cluster mosaics") ap.add_argument("--clusters", action="store_true", help="also emit per-cluster mosaics")
ap.add_argument("--data-dir", default=None,
help="dataset directory (default: <root>/ai_data/<dataset>)")
args = ap.parse_args() args = ap.parse_args()
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
dataset_dir = os.path.join(root, "datasets", args.dataset) dataset_dir = args.data_dir or os.path.join(root, "ai_data", args.dataset)
viridis_dir = os.path.join(root, "outputs", "ion_images_viridis", args.dataset) viridis_dir = os.path.join(root, "outputs", "ion_images_viridis", args.dataset)
ions = load_ions(viridis_dir, args.tile_size, args.dataset) ions = load_ions(viridis_dir, args.tile_size, args.dataset)
out_dir = os.path.join(root, "outputs", args.dataset, "figures") out_dir = os.path.join(root, "outputs", args.dataset, "figures")
+2 -2
View File
@@ -6,7 +6,7 @@ import xml.etree.ElementTree as ET
import numpy as np import numpy as np
from PIL import Image from PIL import Image
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
TOLERANCE = 0.05 TOLERANCE = 0.05
TARGET_SIZE = (256, 256) TARGET_SIZE = (256, 256)
@@ -214,7 +214,7 @@ def extract_ion_images(spectra_info, ibd_path, target_mzs, tolerance, mz_format,
return exported return exported
if __name__ == "__main__": if __name__ == "__main__":
data_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(PROJECT_ROOT, "datasets", "Datura_leaf") data_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(PROJECT_ROOT, "ai_data", "Datura_leaf")
dataset_name = sys.argv[2] if len(sys.argv) > 2 else "Datura_leaf" dataset_name = sys.argv[2] if len(sys.argv) > 2 else "Datura_leaf"
imzml_path, ibd_path, output_dir, viridis_dir = configure(data_dir, dataset_name) imzml_path, ibd_path, output_dir, viridis_dir = configure(data_dir, dataset_name)
+1 -1
View File
@@ -7,7 +7,7 @@ matplotlib.use('Agg')
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from PIL import Image from PIL import Image
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from msi_preprocess_python import parse_imzml, compute_average_spectrum, load_mask, configure, find_mask_path from msi_preprocess_python import parse_imzml, compute_average_spectrum, load_mask, configure, find_mask_path
+3 -3
View File
@@ -30,9 +30,9 @@ dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
K = int(sys.argv[2]) if len(sys.argv) > 2 else 10 K = int(sys.argv[2]) if len(sys.argv) > 2 else 10
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name) IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images", dataset_name)
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth") MODEL_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name) OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs", dataset_name)
FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures") FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+3 -3
View File
@@ -26,9 +26,9 @@ def set_seed(seed=42):
set_seed(42) set_seed(42)
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth") MODEL_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", "msi_encoder_trained.pth")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs_k5") OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs_k5")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
K = 5 K = 5
+2 -2
View File
@@ -9,8 +9,8 @@ from sklearn.cluster import KMeans
import torch.nn.functional as F import torch.nn.functional as F
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth") ENCODER_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", "msi_encoder_trained.pth")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MSI_Structural_Encoder(nn.Module): class MSI_Structural_Encoder(nn.Module):
+2 -2
View File
@@ -8,8 +8,8 @@ from torchvision import transforms
import torch.nn as nn import torch.nn as nn
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth") MODEL_PATH = os.path.join(BASE_DIR, "..", "outputs", "models", "msi_encoder_trained.pth")
class MSI_Structural_Encoder(nn.Module): class MSI_Structural_Encoder(nn.Module):
def __init__(self): def __init__(self):
+3 -3
View File
@@ -7,9 +7,9 @@ from PIL import Image
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf" dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CSV_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name, "msi_clusters_results.csv") CSV_PATH = os.path.join(BASE_DIR, "..", "outputs", dataset_name, "msi_clusters_results.csv")
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name) IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images", dataset_name)
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name, "galleries") OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs", dataset_name, "galleries")
os.makedirs(OUTPUT_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True)
if os.path.exists(CSV_PATH): if os.path.exists(CSV_PATH):
+3 -3
View File
@@ -4,9 +4,9 @@ import matplotlib.pyplot as plt
from PIL import Image from PIL import Image
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CSV_PATH = os.path.join(BASE_DIR, "..", "..", "outputs_k5", "msi_clusters_results.csv") CSV_PATH = os.path.join(BASE_DIR, "..", "outputs_k5", "msi_clusters_results.csv")
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images") IMG_DIR = os.path.join(BASE_DIR, "..", "outputs", "ion_images")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs_k5", "figures", "galleries") OUTPUT_DIR = os.path.join(BASE_DIR, "..", "outputs_k5", "figures", "galleries")
os.makedirs(OUTPUT_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True)
if os.path.exists(CSV_PATH): if os.path.exists(CSV_PATH):
+280
View File
@@ -0,0 +1,280 @@
# src/BloomFilter.jl
"""
BloomFilter{T}
A simple, efficient Bloom filter implementation for probabilistic set membership testing.
# Fields
- `bits::BitVector`: The underlying bit array
- `size::Int`: Number of bits in the filter
- `hash_count::Int`: Number of hash functions to use
- `seed::UInt64`: Random seed for hash functions
- `count::Int`: Number of elements added (for monitoring)
"""
mutable struct BloomFilter{T}
bits::BitVector
size::Int
hash_count::Int
seed::UInt64
count::Int
end
"""
BloomFilter{T}(expected_elements::Int, false_positive_rate::Float64=0.01; kwargs...) -> Return type
Creates a Bloom filter optimized for the expected number of elements and desired false positive rate.
# Arguments
- `expected_elements::Int`: Argument description
- `false_positive_rate::Float64`: Argument description
(**Default**: `0.01`)
# Keywords
- `seed::Union{UInt32,UInt64}`: Keyword description
(**Default**: `0x12345678`)
# Returns
- A `BloomFilter{T}`.
"""
function BloomFilter{T}(expected_elements::Int, false_positive_rate::Float64=0.01; seed::Union{UInt32,UInt64}=0x12345678) where T
# Convert seed to UInt64 for consistency
seed_uint64 = UInt64(seed)
# Calculate optimal parameters using standard formulas
size = optimal_bit_size(expected_elements, false_positive_rate)
hash_count = optimal_hash_count(expected_elements, size)
bits = falses(size)
return BloomFilter{T}(bits, size, hash_count, seed_uint64, 0)
end
"""
optimal_bit_size(n::Int, p::Float64) -> Int
Calculates the optimal number of bits for a Bloom filter
# Arguments
- `n::Int`: Expected number of elements
- `p::Float64`: Desired false positive rate
# Returns
- An `Int` to determine the optimal number of bits for a Bloom filter.
"""
function optimal_bit_size(n::Int, p::Float64)::Int
if p <= 0.0 || p >= 1.0
throw(ArgumentError("False positive rate must be between 0 and 1"))
end
# m = - (n * ln(p)) / (ln(2)^2)
m = ceil(Int, - (n * log(p)) / (log(2)^2))
return max(m, 1)
end
"""
optimal_hash_count(n::Int, m::Int) -> Int
Calculates the optimal number of hash functions for a Bloom filter.
# Arguments
- `n::Int`: Expected number of elements
- `m::Int`: Number of bits in the filter
# Returns
- An `Int` to determine the optimal number of hash functions for a Bloom filter.
"""
function optimal_hash_count(n::Int, m::Int)::Int
if n <= 0 || m <= 0
return 1
end
# k = (m / n) * ln(2)
k = max(1, round(Int, (m / n) * log(2)))
return min(k, 8) # Practical limit to avoid too many hashes
end
"""
hash_functions(item::T, count::Int, size::Int, seed::UInt64) -> Vector{Int}
Generates multiple hash values for an item using double hashing technique.
# Arguments
- `item::T`: Argument description
- `count::Int`: Argument description
- `size::Int`: Argument description
- `seed::UInt64`: Argument description
# Returns
- A `Vector{Int}` of hash values.
"""
function hash_functions(item::T, count::Int, size::Int, seed::UInt64) where T
# Use Julia's built-in hash with different seeds
hashes = Vector{Int}(undef, count)
# First hash with the main seed. Convert to `UInt` so the same code works
# on 32-bit Julia, where `hash(x, h::UInt)` does not accept a UInt64.
h1 = hash(item, UInt(seed))
h2 = hash(item, UInt(seed + 1))
for i in 1:count
# Double hashing: h_i = h1 + i * h2
combined_hash = UInt64(h1) + UInt64(i) * UInt64(h2)
hashes[i] = (combined_hash % UInt64(size)) + 1 # 1-based indexing
end
return hashes
end
"""
Base.push!(bf::BloomFilter{T}, item::T)
Adds an element to the Bloom filter.
# Arguments:
- `bf::BloomFilter{T}`: Argument description
- `item::T`: Argument description
"""
function Base.push!(bf::BloomFilter{T}, item::T) where T
hashes = hash_functions(item, bf.hash_count, bf.size, bf.seed)
for h in hashes
bf.bits[h] = true
end
bf.count += 1
return bf
end
"""
Base.in(item::T, bf::BloomFilter{T}) -> Bool
Checks whether an element is possibly in the Bloom filter.
Returns `true` if the element might be in the set, `false` if it's definitely not.
# Arguments:
- `item::T`: Argument description
- `bf::BloomFilter{T}`: Argument description
"""
function Base.in(item::T, bf::BloomFilter{T})::Bool where T
hashes = hash_functions(item, bf.hash_count, bf.size, bf.seed)
for h in hashes
if !bf.bits[h]
return false # Definitely not in the set
end
end
return true # Possibly in the set
end
"""
contains(bf::BloomFilter{T}, item::T) -> Bool
Alias for `in()` for compatibility with your existing code.
# Arguments:
- `bf::BloomFilter{T}`: Argument description
- `item::T`: Argument description
"""
contains(bf::BloomFilter{T}, item::T) where T = item in bf
"""
add!(bf::BloomFilter{T}, item::T)
Alias for `push!()` for compatibility with your existing code.
# Arguments:
- `bf::BloomFilter{T}`: Argument description
- `item::T`: Argument description
"""
add!(bf::BloomFilter{T}, item::T) where T = push!(bf, item)
"""
false_positive_rate(bf::BloomFilter) -> Float64
Estimates the current false positive rate of the Bloom filter.
# Arguments:
- `bf::BloomFilter`: Argument description
"""
function false_positive_rate(bf::BloomFilter)::Float64
if bf.count == 0
return 0.0
end
# Theoretical false positive rate: (1 - e^(-k * n / m)) ^ k
k = bf.hash_count
n = bf.count
m = bf.size
return (1 - exp(-k * n / m)) ^ k
end
"""
fill_ratio(bf::BloomFilter)::Float64 return count(bf.bits) / length(bf.bits) end -> Return type
Returns the fraction of bits that are set to 1.
# Arguments
- `bf::BloomFilter`: Argument description
"""
function fill_ratio(bf::BloomFilter)::Float64
return count(bf.bits) / length(bf.bits)
end
"""
is_empty(bf::BloomFilter)::Bool return bf.count == 0 end -> Return type
Checks if the Bloom filter is empty (no elements added).
# Arguments
- `bf::BloomFilter`: Argument description
"""
function is_empty(bf::BloomFilter)::Bool
return bf.count == 0
end
"""
reset!(bf::BloomFilter) fill!(bf.bits, false) bf.count = 0 return bf end -> Return type
Clears the Bloom filter, removing all elements.
# Arguments
- `bf::BloomFilter`: Argument description
"""
function reset!(bf::BloomFilter)
fill!(bf.bits, false)
bf.count = 0
return bf
end
# Specialized constructor for empty Bloom filters
"""
BloomFilter{T}(; kwargs...) -> Return type
Description of the function
# Keywords
- `size::Int`: Keyword description
(**Default**: `100`)
- `hash_count::Int`: Keyword description
(**Default**: `3`)
- `seed::Union{UInt32,UInt64}`: Keyword description
(**Default**: `0x12345678`)
"""
function BloomFilter{T}(;size::Int=100, hash_count::Int=3, seed::Union{UInt32,UInt64}=0x12345678) where T
seed_uint64 = UInt64(seed)
bits = falses(size)
return BloomFilter{T}(bits, size, hash_count, seed_uint64, 0)
end
+245
View File
@@ -0,0 +1,245 @@
using Base.Threads
using Mmap
# POSIX madvise constants
const MADV_NORMAL = 0
const MADV_RANDOM = 1
const MADV_SEQUENTIAL = 2
const MADV_WILLNEED = 3
const MADV_DONTNEED = 4
"""
posix_madvise(buffer::AbstractArray, advice::Integer)
A safe wrapper for the OS `madvise` system call. Signals the kernel about the
access pattern for a memory-mapped region. Currently supports Linux/Unix systems.
"""
function posix_madvise(buffer::AbstractArray, advice::Integer)
@static if Sys.isunix()
try
ptr = pointer(buffer)
len = sizeof(buffer)
# ccall(:madvise, return_type, (arg_types...), args...)
ret = ccall(:madvise, Int32, (Ptr{Cvoid}, Csize_t, Int32), ptr, len, Int32(advice))
return ret == 0
catch
return false
end
else
return false # Not supported on this OS
end
end
# --- Buffer Pooling ---
"""
SimpleBufferPool
A dramatically simplified buffer pool that avoids complex locking.
# Arguments:
- `buffers::Dict{Int, Vector{Vector{UInt8}}}`: A dictionary mapping buffer size (in bytes) to a list of available buffers of that size.
- `max_pool_size::Int`: The maximum number of buffers to keep in the pool.
- `lock::ReentrantLock`: A lock to ensure thread-safe access to the pool.
"""
mutable struct SimpleBufferPool
buffers::Dict{Int, Vector{Vector{UInt8}}}
max_pool_size::Int
lock::ReentrantLock # Add lock for thread safety
end
"""
SimpleBufferPool()
Creates a new `SimpleBufferPool` with a default maximum pool size of 50.
"""
SimpleBufferPool() = SimpleBufferPool(Dict{Int, Vector{Vector{UInt8}}}(), 50, ReentrantLock())
"""
get_buffer!(pool::SimpleBufferPool, size::Int) -> Vector{UInt8}
Retrieves a `Vector{UInt8}` buffer of at least `size` bytes from the pool.
If no suitable buffer is available, a new one is allocated.
# Arguments:
- `pool`: The `SimpleBufferPool` to retrieve the buffer from.
- `size`: The minimum desired size of the buffer in bytes.
# Returns:
- A `Vector{UInt8}` buffer.
"""
function get_buffer!(pool::SimpleBufferPool, size::Int)::Vector{UInt8}
buf = lock(pool.lock) do
# Check for existing buffers of exact size first
if haskey(pool.buffers, size) && !isempty(pool.buffers[size])
return pop!(pool.buffers[size])
end
return nothing
end
if buf !== nothing
return buf
end
# No suitable buffer found, allocate new one (outside lock to reduce contention)
return Vector{UInt8}(undef, size)
end
"""
release_buffer!(pool::SimpleBufferPool, buffer::Vector{UInt8})
Returns a `Vector{UInt8}` buffer to the pool for future reuse.
# Arguments:
- `pool`: The `SimpleBufferPool` to return the buffer to.
- `buffer`: The `Vector{UInt8}` buffer to release.
"""
function release_buffer!(pool::SimpleBufferPool, buffer::Vector{UInt8})
size = length(buffer)
lock(pool.lock) do
if !haskey(pool.buffers, size)
pool.buffers[size] = Vector{Vector{UInt8}}()
end
# Limit pool size to prevent memory bloat
if length(pool.buffers[size]) < pool.max_pool_size
push!(pool.buffers[size], buffer)
end
end
# If pool is full, let buffer get GC'd
end
# --- Unified Error Types ---
abstract type MSIError <: Exception end
struct FileFormatError <: MSIError
msg::String
end
struct SpectrumNotFoundError <: MSIError
id
end
struct InvalidSpectrumError <: MSIError
id
reason::String
end
# --- Shared Constants ---
const DEFAULT_CACHE_SIZE = 100 # Default cache size for spectra
const DEFAULT_NUM_BINS = 2000 # Default number of bins for spectra
const DEFAULT_BLOOM_FILTER_SIZE = 10000 # Default size for empty spectra
const DEFAULT_FALSE_POSITIVE_RATE = 0.01 # Default false positive rate for bloom filters
"""
validate_spectrum_data(mz, intensity, id)
Checks a spectrum for common data integrity issues.
# Arguments:
- `mz`: The m/z values of the spectrum.
- `intensity`: The intensity values of the spectrum.
- `id`: The ID of the spectrum.
# Returns:
- `true` if the spectrum is valid.
# Throws:
- `InvalidSpectrumError` if the spectrum is invalid.
"""
function validate_spectrum_data(mz::AbstractVector, intensity::AbstractVector, id)
if length(mz) != length(intensity)
throw(InvalidSpectrumError(id, "m/z and intensity arrays have different lengths"))
end
if !all(isfinite, mz) || !all(isfinite, intensity)
throw(InvalidSpectrumError(id, "Spectrum contains NaN or Inf values"))
end
if !issorted(mz)
throw(InvalidSpectrumError(id, "m/z array is not sorted"))
end
return true
end
"""
create_bloom_filter_for_spectrum(mz::AbstractVector{<:Real}) -> BloomFilter{Int}
Memory-optimized version that processes data in chunks to reduce temporary allocations
and avoid holding large intermediate arrays.
# Arguments:
- `mz`: The m/z values of the spectrum.
# Returns:
- A `BloomFilter{Int}` for the spectrum.
"""
function create_bloom_filter_for_spectrum(mz::AbstractVector{<:Real})::BloomFilter{Int}
if isempty(mz)
return empty_bloom_filter()
end
# Size Bloom filter appropriately
n_points = length(mz)
bf = BloomFilter{Int}(n_points, DEFAULT_FALSE_POSITIVE_RATE)
discretization_factor = 100.0
chunk_size = 10000 # Process in chunks to reduce memory pressure
# Process spectrum data in chunks to avoid large temporary arrays
for chunk_start in 1:chunk_size:n_points
chunk_end = min(chunk_start + chunk_size - 1, n_points)
@inbounds for i in chunk_start:chunk_end
discretized_val = round(Int, mz[i] * discretization_factor)
push!(bf, discretized_val)
end
end
return bf
end
"""
empty_bloom_filter() -> BloomFilter{Int}
Creates an empty Bloom filter for spectra with no data.
# Returns:
- An empty `BloomFilter{Int}`.
"""
function empty_bloom_filter()::BloomFilter{Int}
return BloomFilter{Int}(size=DEFAULT_BLOOM_FILTER_SIZE, hash_count=3)
end
"""
AtomicFlag
A thread-safe boolean flag using atomic operations.
# Fields:
- `value::Base.Threads.Atomic{Int}`: The atomic value of the flag.
# Arguments:
- `value::Base.Threads.Atomic{Int}`: The atomic value of the flag.
"""
struct AtomicFlag
value::Base.Threads.Atomic{Int}
end
AtomicFlag() = AtomicFlag(Base.Threads.Atomic{Int}(0))
function set!(flag::AtomicFlag)
Base.Threads.atomic_add!(flag.value, 1)
end
function is_set(flag::AtomicFlag)::Bool
return Base.Threads.atomic_add!(flag.value, 0) > 0
end
function reset!(flag::AtomicFlag)
Base.Threads.atomic_xchg!(flag.value, 0)
end
+120
View File
@@ -0,0 +1,120 @@
# src/ImageProcessing
using Images
using ImageBinarization
using ImageMorphology
using ImageComponentAnalysis
using Colors # For converting to grayscale
export process_image_pipeline
export load_and_prepare_mask # Export the new function
"""
load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int})
Loads a PNG image mask, converts it to a binary (Boolean) matrix,
and resizes it to the specified `target_dims`. White pixels in the mask
are considered `true` (part of the ROI), and black pixels are `false`.
# Arguments
- `mask_path`: Absolute path to the PNG mask file.
- `target_dims`: A tuple `(width, height)` representing the desired output dimensions.
# Returns
- A `BitMatrix` of `target_dims` where `true` indicates the ROI.
"""
function load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int})
if !isfile(mask_path)
error("Mask file not found: $(mask_path)")
end
# Load the image
img = Images.load(mask_path)
# Convert to grayscale. Most images are already Colorant arrays, but TIFFs
# with extra samples (e.g. the optical reference images shipped with MSI
# datasets) load as TiffImages.WidePixel, for which Gray.(img) has no method.
# Fall back to the embedded color channel in that case.
gray_img = if eltype(img) <: Colorant
Gray.(img)
else
Gray.([getproperty(p, :color) for p in img])
end
# Binarize using Otsu's method - white regions become 'true'
binary_img = binarize(gray_img, Otsu())
# Resize to target dimensions
resized_img = imresize(binary_img, (target_dims[2], target_dims[1]))
# Ensure the output is a BitMatrix, as imresize can change the type
return resized_img .> 0.5
end
# ===================================================================
# CORE PROCESSING PIPELINE
# ===================================================================
"""
process_image_pipeline(gray_img; otsu_scale=1.0, noise_size_percent=0.1, hole_size_percent=0.05, smoothing=2)
Applies a multi-step image processing pipeline to a grayscale image to segment regions of interest.
The pipeline consists of:
1. **Binarization**: An adjusted Otsu's threshold is used to create a binary image.
2. **Noise Removal**: Small white regions (noise) are removed using an area opening operation.
3. **Hole Filling**: Small black regions (holes) within larger objects are filled.
4. **Edge Smoothing**: The edges of the final regions are smoothed using a morphological closing operation.
# Arguments
- `gray_img`: The input grayscale image (`Matrix{<:Gray}`).
# Keyword Arguments
- `otsu_scale`: A factor to scale the automatically determined Otsu threshold. Values > 1.0 make the threshold stricter (less white), < 1.0 make it more lenient (more white). Default: `1.0`.
- `noise_size_percent`: The percentage of the total image area used as a threshold to remove small white noise components. Default: `0.1`.
- `hole_size_percent`: The percentage of the total image area used as a threshold to fill black holes in white components. Default: `0.05`.
- `smoothing`: The size of the kernel for the final edge smoothing (closing) operation. Default: `2`.
# Returns
- A tuple containing four images representing the intermediate steps of the pipeline:
1. `binary_img`: The result of the initial binarization.
2. `noise_removed_img`: The image after noise removal.
3. `holes_filled_img`: The image after filling holes.
4. `smoothed_img`: The final smoothed image.
"""
function process_image_pipeline(gray_img;
otsu_scale=1.0,
noise_size_percent=0.1,
hole_size_percent=0.05,
smoothing=2)
# --- Step 1: Otsu Binarization ---
otsu_threshold = find_threshold(gray_img, Otsu())
adjusted_threshold = otsu_threshold * otsu_scale
binary_img = gray_img .>= adjusted_threshold
# --- Smart Parameter Scaling ---
image_area = length(gray_img)
noise_size_pixels = round(Int, image_area * noise_size_percent)
hole_size_pixels = round(Int, image_area * hole_size_percent)
# --- Step 2: Remove Small White Regions (Noise) ---
# area_opening is the correct morphological operation for this.
noise_removed_img = area_opening(binary_img, min_area=noise_size_pixels)
# --- Step 3: Fill Small Black Holes ---
# area_closing is the dual of area_opening and fills holes.
holes_filled_img = area_closing(noise_removed_img, min_area=hole_size_pixels)
# --- Step 4: Smooth Edges ---
# A morphological closing with a small disk smooths outlines.
# ImageMorphology requires odd-sized structuring elements; the historical
# default smoothing=2 produced a 2×2 matrix and threw "connectivity must be
# odd-sized". Normalize to the next odd size (minimum 3).
smooth_size = max(3, isodd(smoothing) ? smoothing : smoothing + 1)
smoothing_kernel = ones(Bool, (smooth_size, smooth_size))
smoothed_img = closing(holes_filled_img, smoothing_kernel)
# --- Return all intermediate steps for visualization ---
return binary_img, noise_removed_img, holes_filled_img, smoothed_img
end
+9
View File
@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2025 The LabABI, Cinvestav Irapuato, Mexico, <robert.winkler@cinvestav.mx>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+1840
View File
File diff suppressed because it is too large Load Diff
+154
View File
@@ -0,0 +1,154 @@
# MSI_src.jl
module MSI_src
# Export the public MSI API
export OpenMSIData,
GetSpectrum,
IterateSpectra,
ImportMzmlFile,
get_total_spectrum,
get_average_spectrum,
precompute_analytics,
process_spectrum,
process_image_pipeline,
load_and_prepare_mask,
set_global_mz_range!,
get_global_mz_range,
MSIData,
_iterate_spectra_fast,
validate_spectrum,
get_mz_slice,
REGISTRY_LOCK,
SpectrumMetadata,
SpectrumAsset,
SpectrumMode,
CENTROID,
PROFILE,
MzMLSource,
ImzMLSource,
SimpleBufferPool,
get_buffer!,
release_buffer!,
PROJECT_ROOT,
PUBLIC_DIR,
DEFAULT_REGISTRY_PATH,
ensure_public_dir
# Define shared registry lock
const REGISTRY_LOCK = ReentrantLock()
# Export the public preprocessing & precalculations API
export run_preprocessing_analysis,
main_precalculation,
FeatureMatrix,
Calibration,
Smoothing,
BaselineCorrection,
Normalization,
PeakPicking,
PeakBinning,
get_masked_spectrum_indices,
detect_peaks_profile_core,
detect_peaks_centroid_core,
smooth_spectrum_core,
apply_baseline_correction_core,
apply_normalization_core,
bin_peaks_core,
PeakSelection,
PeakAlignment,
find_calibration_peaks_core,
align_peaks_lowess_core,
MutableSpectrum,
transform_intensity_core,
calibrate_spectra_core
export apply_baseline_correction,
apply_smoothing,
apply_peak_picking,
apply_calibration,
apply_peak_alignment,
apply_normalization,
apply_peak_binning,
apply_intensity_transformation,
save_feature_matrix
# Sprint 2: Streaming Pipeline API
export process_dataset!,
PipelineConfig,
StreamingStep,
normalize_inplace!,
transform_inplace!,
smooth_inplace!,
baseline_subtract_inplace!,
detect_peaks_streaming,
calibrate_inplace!
# Include all source files directly into the main module
include("Paths.jl")
include("BloomFilters.jl")
include("Common.jl")
include("ResourcePool.jl")
include("MSIData.jl")
include("ParserHelpers.jl")
include("mzML.jl")
include("imzML.jl")
include("PlottingStubs.jl")
include("MzmlConverter.jl")
include("Preprocessing.jl")
include("ImageProcessing.jl")
include("Precalculations.jl")
include("PreprocessingPipeline.jl")
include("StreamingKernels.jl")
include("StreamingPipeline.jl")
using Setfield # For immutable struct updates
# --- Main Entry Point --- #
"""
OpenMSIData(filepath::String; cache_size=100)
Opens a .mzML or .imzML file and prepares it for data access.
This is the main entry point for the new data access API.
# Arguments
- `filepath::String`: Path to the .mzML or .imzML file to open.
- `cache_size::Int`: Number of spectra to cache in memory.
- `spectrum_type_map::Union{Dict{Int, Symbol}, Nothing}`: Optional mapping of spectrum indices to types.
# Returns
- An `MSIData` object.
"""
function OpenMSIData(filepath::String; cache_size=300, spectrum_type_map::Union{Dict{Int, Symbol}, Nothing}=nothing)
# Apply standard path normalization for cross-platform compatibility
# Ensure Windows backslashes are converted to OS-native separators
norm_filepath = normpath(replace(filepath, "\\" => "/"))
local msi_data
if endswith(lowercase(norm_filepath), ".mzml")
msi_data = load_mzml_lazy(norm_filepath, cache_size=cache_size)
elseif endswith(lowercase(norm_filepath), ".imzml")
msi_data = load_imzml_lazy(norm_filepath, cache_size=cache_size)
else
error("Unsupported file type: $norm_filepath. Please provide a .mzML or .imzML file.")
end
# Apply spectrum type map if provided
if spectrum_type_map !== nothing
for (idx, type_symbol) in spectrum_type_map
if 1 <= idx <= length(msi_data.spectra_metadata)
msi_data.spectra_metadata[idx] = @set msi_data.spectra_metadata[idx].type = type_symbol
else
@warn "Spectrum index $idx out of bounds for spectrum_type_map. Skipping."
end
end
end
return msi_data
end
end # module MSI_src
+883
View File
@@ -0,0 +1,883 @@
# src/MzmlConverter.jl
"""
This file contains the workflow for converting .mzML files (with one spectrum per pixel)
into a proper .imzML/.ibd file pair, using a separate synchronization file.
It replicates the functionality of the original R scripts that use MALDIquant.
"""
using DataFrames, Printf, CSV, UUIDs, ProgressMeter
# This file assumes that the main application file (e.g., app.jl) has already included
# the necessary source files: MSIData.jl, mzML.jl, imzML.jl
# A struct to hold the processed pixel data before exporting
"""
ProcessedPixel
A temporary struct to hold the data for a single, fully rendered pixel before
it is written to the final `.ibd` file.
# Fields
- `coords`: A tuple `(x, y)` of the pixel's spatial coordinates.
- `mz`: The m/z array for the pixel.
- `intensity`: The calculated intensity array for the pixel.
"""
struct ProcessedPixel
coords::Tuple{Int, Int}
mz::Vector{Float64} # Assuming m/z is consistent, can be optimized later
intensity::Vector{Float32}
end
"""
BinaryMetadata
A struct to hold the file offset and length for a spectrum's binary data arrays
(m/z and intensity) after they have been written to the `.ibd` file.
# Fields
- `mz_offset`, `mz_length`: Byte offset and length for the m/z array.
- `int_offset`, `int_length`: Byte offset and length for the intensity array.
"""
struct BinaryMetadata
mz_offset::UInt64
mz_length::UInt64
int_offset::UInt64
int_length::UInt64
end
"""
GetMzmlScanTime_linebyline(fileName::String)
Parses a `.mzML` file line-by-line to extract the scan start time for each
spectrum. This is a slow and memory-intensive fallback method used only when
the faster, index-based `GetMzmlScanTime` fails.
# Arguments
- `fileName`: Path to the `.mzML` file.
# Returns
- A `Matrix{Int64}` where each row is `[spectrum_index, time_in_milliseconds]`.
"""
function GetMzmlScanTime_linebyline(fileName::String)
times = Tuple{Int64, Int64}[]
try
file_size = filesize(fileName)
estimated_spectra = max(1000, file_size ÷ 10000)
sizehint!(times, estimated_spectra)
catch
end
open(fileName, "r") do stream
state = :outside_spectrum
current_index = 0
current_time = nothing
for line in eachline(stream)
if state == :outside_spectrum
if occursin("<spectrum ", line)
state = :in_spectrum
current_index = 0
current_time = nothing
idx_match = match(r"index=\"(\d+)\"", line)
if idx_match !== nothing
current_index = parse(Int, idx_match.captures[1]) + 1
end
end
elseif state == :in_spectrum
if occursin("<cvParam", line)
if occursin("MS:1000016", line) || occursin("MS:1000015", line)
time_match = match(r"value=\"([\d\.]+)\"", line)
if time_match !== nothing
time_val = parse(Float64, time_match.captures[1])
unit_scale = occursin("MS:1000016", line) ? 60000 : 1000
current_time = round(Int64, time_val * unit_scale)
end
end
end
if occursin("</spectrum>", line)
state = :outside_spectrum
if current_index > 0 && current_time !== nothing
push!(times, (current_index, current_time))
end
end
end
end
end
result = Matrix{Int64}(undef, length(times), 2)
for (i, t) in enumerate(times)
result[i, 1] = t[1]
result[i, 2] = t[2]
end
return result
end
"""
GetMzmlScanTime(fileName::String)
Parses a .mzML file to extract the scan start time for each spectrum.
Uses the indexed part of the .mzML file for fast access, falling back to
a slower line-by-line parse if the index is not present.
# Arguments
* `fileName`: Path to the .mzML file.
# Returns
- A `Matrix{Int64}` where each row is `[spectrum_index, time_in_milliseconds]`.
"""
function GetMzmlScanTime(fileName::String)
times = Tuple{Int64, Int64}[]
try
open(fileName, "r") do stream
# 1. Find and parse the spectrum index offsets
seekend(stream)
end_chunk_size = min(filesize(stream), 8192)
seek(stream, filesize(stream) - end_chunk_size)
footer = read(stream, String)
index_offset_match = match(r"<indexListOffset>(\d+)</indexListOffset>", footer)
if index_offset_match === nothing
@warn "No <indexListOffset> found. Falling back to slow line-by-line parsing for scan times. This may be memory intensive."
return GetMzmlScanTime_linebyline(fileName)
end
index_offset = parse(Int64, index_offset_match.captures[1])
seek(stream, index_offset)
# The find_tag function is defined in ParserHelpers.jl
if find_tag(stream, r"<index\s+name=\"spectrum\"") === nothing
@warn "Could not find spectrum index. Falling back to slow line-by-line parsing."
return GetMzmlScanTime_linebyline(fileName)
end
# The parse_offset_list function is defined in mzML.jl
spectrum_offsets = parse_offset_list(stream)
# 2. Iterate through offsets and parse time for each spectrum
for (idx, offset) in enumerate(spectrum_offsets)
seek(stream, offset)
current_time = nothing
# Read a limited number of lines to find the time
for _ in 1:100
if eof(stream) break end
line = readline(stream)
if occursin("MS:1000016", line) || occursin("MS:1000015", line) # scan start time
time_match = match(r"value=\"([\d\.]+)\"", line)
if time_match !== nothing
time_val = parse(Float64, time_match.captures[1])
unit_scale = occursin("MS:1000016", line) ? 60000 : 1000 # minutes vs seconds
current_time = round(Int64, time_val * unit_scale)
break
end
end
if occursin("<binary>", line) || occursin("</spectrum>", line)
break
end
end
if current_time !== nothing
push!(times, (idx, current_time))
end
end
end
catch e
@error "Failed to parse scan times with indexed method. Falling back to line-by-line." exception=(e, catch_backtrace())
return GetMzmlScanTime_linebyline(fileName)
end
# The index is already sorted by spectrum index, so no need to sort `times`.
# Normalize times relative to the first scan
if !isempty(times)
first_time = times[1][2]
for i in eachindex(times)
times[i] = (times[i][1], times[i][2] - first_time)
end
end
result = Matrix{Int64}(undef, length(times), 2)
for (i, t) in enumerate(times)
result[i, 1] = t[1]
result[i, 2] = t[2]
end
return result
end
"""
MatchAcquireTime(sync_file_path::String, scans::Matrix{Int64})
Correlates pixel acquisition times from a synchronization file with scan
acquisition times from an mzML file.
This is a Julia implementation of the `MatchAcquireTime` function from the R scripts.
# Arguments
* `sync_file_path`: Path to the synchronization file (.txt).
* `scans`: A matrix of scan times, as returned by `GetMzmlScanTime`.
# Returns
- A `Matrix{Int64}` where each row is `[pixel_index, pixel_time_ms, first_scan_index, last_scan_index]`.
"""
function MatchAcquireTime(sync_file_path::String, scans::Matrix{Int64}; img_width::Int=0, img_height::Int=0)
if !isfile(sync_file_path)
error("Synchronization file not found: $sync_file_path")
end
pixel_df = CSV.read(sync_file_path, DataFrame, header=false, skipto=3)
pixel_matrix = Matrix(pixel_df)
num_pixels_original = size(pixel_matrix, 1)
if num_pixels_original == 0
return zeros(Int64, 0, 5)
end
# Determine image dimensions and generate coordinates
current_img_width = img_width
current_img_height = img_height
if current_img_width == 0 || current_img_height == 0
if size(pixel_matrix, 2) >= 3
@info "Sync file contains X, Y coordinates"
coordinates = convert(Matrix{Int}, pixel_matrix[:, 1:2])
pixel_times = convert(Vector{Int64}, pixel_matrix[:, 3])
current_img_width = maximum(coordinates[:, 1])
current_img_height = maximum(coordinates[:, 2])
# Apply R's pixel truncation logic
num_pixels = (floor(Int, (num_pixels_original - 1) / current_img_width)) * current_img_width
if num_pixels <= 0
error("Calculated num_pixels to process is zero or negative: $num_pixels")
end
# Truncate arrays
final_coordinates = coordinates[1:num_pixels, :]
final_pixel_times = pixel_times[1:num_pixels]
else
@info "Sync file contains Index and Time; generating coordinates"
pixel_times = convert(Vector{Int64}, pixel_matrix[:, 2])
# R's width detection logic
diffs = pixel_matrix[2:end, 1] .- pixel_matrix[1:end-1, 1]
width_indices = findall(x -> x != 1, diffs)
if !isempty(width_indices)
current_img_width = width_indices[1]
else
current_img_width = num_pixels_original
end
current_img_height = num_pixels_original ÷ current_img_width
# R's pixel truncation logic
num_pixels = (floor(Int, (num_pixels_original - 1) / current_img_width)) * current_img_width
if num_pixels <= 0
error("Calculated num_pixels to process is zero or negative: $num_pixels")
end
# Generate coordinates for truncated pixels
final_coordinates = zeros(Int, num_pixels, 2)
final_pixel_times = zeros(Int64, num_pixels)
for i in 1:num_pixels
idx = pixel_matrix[i, 1]
final_coordinates[i, 1] = ((idx - 1) % current_img_width) + 1
final_coordinates[i, 2] = fld(idx - 1, current_img_width) + 1
final_pixel_times[i] = pixel_times[i]
end
end
else
@info "Using provided dimensions: $(current_img_width)x$(current_img_height)"
pixel_times = convert(Vector{Int64}, pixel_matrix[:, 2])
# R's pixel truncation logic (FIXED: consistent formula)
num_pixels = (floor(Int, (num_pixels_original - 1) / current_img_width)) * current_img_width
if num_pixels <= 0
error("Calculated num_pixels to process is zero or negative: $num_pixels")
end
# Generate coordinates
final_coordinates = zeros(Int, num_pixels, 2)
final_pixel_times = zeros(Int64, num_pixels)
for i in 1:num_pixels
idx = pixel_matrix[i, 1]
final_coordinates[i, 1] = ((idx - 1) % current_img_width) + 1
final_coordinates[i, 2] = fld(idx - 1, current_img_width) + 1
final_pixel_times[i] = pixel_times[i]
end
end
# Normalize pixel times
if !isempty(final_pixel_times)
min_pixel_time = minimum(final_pixel_times)
final_pixel_times .-= min_pixel_time
end
num_scans = size(scans, 1)
if num_scans == 0
return hcat(final_coordinates, final_pixel_times, zeros(Int64, num_pixels, 2))
end
# FIXED R's time matching algorithm with bounds checking
first_idx = 1
last_idx = 1
index_matrix = zeros(Int, num_pixels, 2)
for i_pixel in 1:num_pixels
pixel_time = final_pixel_times[i_pixel]
# Find the first scan that reaches or exceeds pixel time
while last_idx <= num_scans && scans[last_idx, 2] < pixel_time
last_idx += 1
end
# Ensure valid indices
if last_idx > num_scans
# No more scans available for remaining pixels
index_matrix[i_pixel:end, 1] .= num_scans + 1 # Invalid index
index_matrix[i_pixel:end, 2] .= num_scans # Invalid index
break
end
# Assign scan indices with bounds checking
start_scan = max(1, first_idx)
end_scan = max(1, last_idx - 1)
# Ensure start_scan <= end_scan
if start_scan > end_scan
start_scan = end_scan
end
index_matrix[i_pixel, 1] = start_scan
index_matrix[i_pixel, 2] = end_scan
# Update for next iteration (R's algorithm)
first_idx = last_idx - 1
last_idx = first_idx
# Ensure first_idx doesn't go below 1
if first_idx < 1
first_idx = 1
last_idx = 1
end
end
return hcat(final_coordinates, final_pixel_times, index_matrix)
end
"""
RenderPixel(pixel_info, scans, msi_data, scan_time_deltas, pixel_time_deltas)
Reconstructs the spectrum for a single pixel by combining intensities from the
raw MS scans that occurred during the pixel's acquisition time. It uses a
weighted interpolation scheme based on the relative timing of scans and pixels.
This function handles three cases:
1. A single scan falls entirely within the pixel's time window.
2. The pixel's time window is covered by two partial scans.
3. The pixel's time window covers one or more full scans plus two partial scans.
# Arguments
- `pixel_info`: A row from the timing matrix containing the pixel's time and scan indices.
- `scans`: The matrix of scan times.
- `msi_data`: The `MSIData` object for the source `.mzML` file.
- `scan_time_deltas`: Pre-calculated time durations for each scan.
- `pixel_time_deltas`: Pre-calculated time durations for each pixel.
# Returns
- A tuple `(mz_array, intensity_array)` for the rendered pixel spectrum.
"""
function RenderPixel(
intensity_buffer::Vector{Float32},
pixel_info::AbstractVector{Int64},
scans::AbstractMatrix{Int64},
msi_data::MSIData,
scan_time_deltas::AbstractVector{Int64},
pixel_time_deltas::AbstractVector{Int64}
)
pixel_time = pixel_info[3]
first_scan = pixel_info[4]
last_scan = pixel_info[5]
num_actions = last_scan - first_scan
# Get reference m/z array from the first scan involved.
mz_array, _ = GetSpectrum(msi_data, first_scan)
# If the first spectrum was empty, we can't do anything else.
if isempty(mz_array)
return (mz_array, view(intensity_buffer, 0:-1), UNKNOWN)
end
# Determine the mode for the output spectrum. If any contributing scan is profile, the result is profile.
final_mode = CENTROID
for i in first_scan:last_scan
if msi_data.spectra_metadata[i].mode == PROFILE
final_mode = PROFILE
break
end
end
# Use the provided buffer instead of allocating a new one.
if length(intensity_buffer) < length(mz_array)
error("Provided intensity buffer is too small for spectrum of length $(length(mz_array))")
end
new_intensity = view(intensity_buffer, 1:length(mz_array))
fill!(new_intensity, 0.0f0)
# SAFETY: Ensure we have valid scan indices
if first_scan < 1 || last_scan > size(scans, 1) || first_scan > last_scan
return (mz_array, new_intensity, final_mode) # Return zero intensity for invalid ranges
end
if num_actions == 0 # Single scan contributes to the pixel
process_spectrum(msi_data, first_scan) do _, intensity
# SAFETY: Ensure positive scaling
scale = max(pixel_time_deltas[first_scan] / scan_time_deltas[first_scan], 0.0f0)
new_intensity .= intensity .* scale
end
elseif num_actions == 1 # Two partial scans contribute
# First partial scan
process_spectrum(msi_data, first_scan) do _, intensity1
scale1 = max((scans[last_scan, 2] - pixel_time) / scan_time_deltas[first_scan], 0.0f0)
new_intensity .+= intensity1 .* scale1
end
# Second partial scan
process_spectrum(msi_data, last_scan) do _, intensity2
next_pixel_time = pixel_time + pixel_time_deltas[first_scan]
scale2 = max((next_pixel_time - scans[last_scan, 2]) / scan_time_deltas[last_scan], 0.0f0)
new_intensity .+= intensity2 .* scale2
end
elseif num_actions > 1 # Multiple scans contribute
# First partial scan
process_spectrum(msi_data, first_scan) do _, intensity1
scale1 = max((scans[first_scan + 1, 2] - pixel_time) / scan_time_deltas[first_scan], 0.0f0)
new_intensity .+= intensity1 .* scale1
end
# Full scans in the middle
for i in (first_scan + 1):(last_scan - 1)
process_spectrum(msi_data, i) do _, intensity_middle
new_intensity .+= intensity_middle
end
end
# Last partial scan
process_spectrum(msi_data, last_scan) do _, intensity2
next_pixel_time = pixel_time + pixel_time_deltas[first_scan]
scale2 = max((next_pixel_time - scans[last_scan, 2]) / scan_time_deltas[last_scan], 0.0f0)
new_intensity .+= intensity2 .* scale2
end
end
# FINAL SAFETY: Clamp any negative values to zero
new_intensity = max.(new_intensity, 0.0f0)
return (mz_array, new_intensity, final_mode)
end
"""
ConvertMzmlToImzml(source_file, target_ibd_file, timing_matrix, scans)
Orchestrates the conversion of spectra from a `.mzML` file into a binary `.ibd`
file. It iterates through each pixel defined in the `timing_matrix`, calls
`RenderPixel` to reconstruct the pixel's spectrum, and writes the resulting
m/z and intensity arrays to the `.ibd` file in little-endian byte order.
# Arguments
- `source_file`: Path to the source `.mzML` file.
- `target_ibd_file`: Path for the output `.ibd` binary file.
- `timing_matrix`: The output from `MatchAcquireTime`, mapping pixels to scans.
- `scans`: The matrix of scan times from `GetMzmlScanTime`.
# Returns
- A tuple `(binary_meta_vec, coords_vec, (width, height))` containing:
- A vector of `BinaryMetadata` for each spectrum.
- A vector of `(x, y)` coordinate tuples.
- A tuple of the final image dimensions.
"""
function ConvertMzmlToImzml(source_file::String, target_ibd_file::String, timing_matrix::Matrix{Int64}, scans::Matrix{Int64})
if size(timing_matrix, 1) == 0
# Create an empty .ibd file if there's nothing to process
open(target_ibd_file, "w") do ibd_stream
write(ibd_stream, zeros(UInt8, 16)) # UUID placeholder
end
return BinaryMetadata[], Tuple{Int, Int}[], (0, 0), SpectrumMode[], uuid4()
end
width = maximum(timing_matrix[:, 1])
height = maximum(timing_matrix[:, 2])
msi_data = OpenMSIData(source_file)
local binary_meta_vec, coords_vec, pixel_modes, ibd_uuid
try
precompute_analytics(msi_data)
max_points = isempty(msi_data.spectrum_stats_df.NumPoints) ? 0 : maximum(msi_data.spectrum_stats_df.NumPoints)
intensity_buffer = zeros(Float32, max_points)
scan_time_deltas = zeros(Int64, size(scans, 1))
if size(scans, 1) > 1
for i in 1:(size(scans, 1) - 1)
delta = scans[i+1, 2] - scans[i, 2]
scan_time_deltas[i] = max(1, delta)
end
scan_time_deltas[end] = max(1, scan_time_deltas[end-1])
end
pixel_time_deltas = zeros(Int64, size(timing_matrix, 1))
if size(timing_matrix, 1) > 1
for i in 1:(size(timing_matrix, 1) - 1)
delta = timing_matrix[i+1, 3] - timing_matrix[i, 3]
pixel_time_deltas[i] = max(1, delta)
end
pixel_time_deltas[end] = max(1, pixel_time_deltas[end-1])
end
binary_meta_vec = BinaryMetadata[]
sizehint!(binary_meta_vec, size(timing_matrix, 1))
coords_vec = Tuple{Int, Int}[]
sizehint!(coords_vec, size(timing_matrix, 1))
pixel_modes = SpectrumMode[]
sizehint!(pixel_modes, size(timing_matrix, 1))
empty_pixel_count = 0
open(target_ibd_file, "w") do ibd_stream
# Generate and write a valid UUID
ibd_uuid = uuid4()
write(ibd_stream, htol(ibd_uuid.value))
p = Progress(size(timing_matrix, 1), 1, "Converting pixels... ")
for i in 1:size(timing_matrix, 1)
pixel_info = timing_matrix[i, :]
x, y = pixel_info[1], pixel_info[2]
push!(coords_vec, (x, y))
first_scan = pixel_info[4]
last_scan = pixel_info[5]
if first_scan > last_scan || first_scan < 1 || last_scan > size(scans, 1)
empty_pixel_count += 1
current_pos = position(ibd_stream)
push!(binary_meta_vec, BinaryMetadata(current_pos, 0, current_pos, 0))
push!(pixel_modes, UNKNOWN) # Mode for empty pixel
next!(p)
continue
end
mz, intensity, pixel_mode = RenderPixel(intensity_buffer, pixel_info, scans, msi_data, scan_time_deltas, pixel_time_deltas)
push!(pixel_modes, pixel_mode)
# Write m/z array (as Float64)
mz_offset = position(ibd_stream)
write(ibd_stream, htol.(mz)) # mz is Vector{Float64}
mz_length = position(ibd_stream) - mz_offset
# Write intensity array (as Float32)
int_offset = position(ibd_stream)
write(ibd_stream, htol.(intensity)) # intensity is Vector{Float32}
int_length = position(ibd_stream) - int_offset
push!(binary_meta_vec, BinaryMetadata(mz_offset, mz_length, int_offset, int_length))
next!(p)
end
end
@info "Found and processed $empty_pixel_count empty pixels out of $(size(timing_matrix, 1)) total."
finally
close(msi_data)
end
return binary_meta_vec, coords_vec, (width, height), pixel_modes, ibd_uuid, msi_data.instrument_metadata
end
"""
ExportImzml(target_file, binary_meta, coords, dims)
Generates the `.imzML` metadata file. This XML file contains all the necessary
metadata to interpret the corresponding `.ibd` binary file, including references
to external data offsets, image dimensions, and CV parameters describing the
experiment and data format.
# Arguments
- `target_file`: The path for the output `.imzML` file.
- `binary_meta`: A vector of `BinaryMetadata` structs with offset and length info.
- `coords`: A vector of `(x, y)` coordinates for each spectrum.
- `dims`: A tuple `(width, height)` of the final image dimensions.
# Returns
- `true` on success, `false` on failure.
"""
function ExportImzml(target_file::String, binary_meta::Vector{BinaryMetadata}, coords::Vector{Tuple{Int, Int}}, dims::Tuple{Int, Int}, modes::Vector{SpectrumMode}, ibd_uuid::UUID, instrument_meta::InstrumentMetadata)
ibd_file = replace(target_file, r"\.imzML$"i => ".ibd")
if isempty(binary_meta)
@warn "No binary metadata to export; creating empty imzML file."
# Still create a valid, empty imzML file
end
try
# The .ibd file is now written by ConvertMzmlToImzml.
# This function is only responsible for the .imzML XML metadata file.
open(target_file, "w") do imzml_stream
# XML Header
write(imzml_stream, """<?xml version="1.0" encoding="ISO-8859-1"?>
<mzML xmlns="http://psi.hupo.org/ms/mzml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://psi.hupo.org/ms/mzml http://psidev.info/files/ms/mzML/xsd/mzML1.1.0.xsd" version="1.1" id="$(splitext(basename(target_file))[1])">
""")
# CV List, File Description, etc. (static parts)
write(imzml_stream, """ <cvList count="3">
<cv id="MS" fullName="Proteomics Standards Initiative Mass Spectrometry Ontology" version="1.3.1" URI="http://psidev.info/ms/mzML/psi-ms.obo"/>
<cv id="UO" fullName="Unit Ontology" version="1.15" URI="http://obo.cvs.sourceforge.net/obo/obo/ontology/phenotype/unit.obo"/>
<cv id="IMS" fullName="Imaging MS Ontology" version="0.9.1" URI="http://www.maldi-msi.org/download/imzml/imagingMS.obo"/>
</cvList>
""")
write(imzml_stream, """ <fileDescription>
<fileContent>
<cvParam cvRef="MS" accession="MS:1000579" name="MS1 spectrum"/>
<cvParam cvRef="IMS" accession="IMS:1000080" name="mass spectrum"/>
<cvParam cvRef="IMS" accession="IMS:1000031" name="processed"/>
<cvParam cvRef="IMS" accession="IMS:1000081" name="ibd uuid" value="$(ibd_uuid)"/>
$(
if instrument_meta.polarity == :positive
""" <cvParam cvRef="MS" accession="MS:1000130" name="positive scan"/>"""
elseif instrument_meta.polarity == :negative
""" <cvParam cvRef="MS" accession="MS:1000129" name="negative scan"/>"""
else
""
end
)
</fileContent>
</fileDescription>
""")
write(imzml_stream, """ <referenceableParamGroupList count="2">
<referenceableParamGroup id="mzArray">
<cvParam cvRef="MS" accession="MS:1000576" name="no compression"/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitCvRef="MS" unitAccession="MS:1000040" unitName="m/z"/>
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float"/>
</referenceableParamGroup>
<referenceableParamGroup id="intensityArray">
<cvParam cvRef="MS" accession="MS:1000576" name="no compression"/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" unitCvRef="MS" unitAccession="MS:1000131" unitName="number of counts"/>
<cvParam cvRef="MS" accession="MS:1000521" name="32-bit float"/>
</referenceableParamGroup>
</referenceableParamGroupList>
""")
write(imzml_stream, """ <sampleList count="1">
<sample id="sample1" name="ImagingSample">
<cvParam cvRef="MS" accession="MS:1000001" name="sample number" value="1"/>
</sample>
</sampleList>
""")
write(imzml_stream, """ <softwareList count="1">
<software id="MSIConverter" version="1.0">
<cvParam cvRef="MS" accession="MS:1000799" name="custom unreleased software tool" value="mzML to imzML converter"/>
</software>
</softwareList>
""")
write(imzml_stream, """ <scanSettingsList count="1">
<scanSettings id="scanSettings1">
<cvParam cvRef="IMS" accession="IMS:1000042" name="max count of pixel x" value="$(dims[1])"/>
<cvParam cvRef="IMS" accession="IMS:1000043" name="max count of pixel y" value="$(dims[2])"/>
<cvParam cvRef="IMS" accession="IMS:1000046" name="pixel size x" value="1" unitCvRef="UO" unitAccession="UO:0000017" unitName="micrometer"/>
<cvParam cvRef="IMS" accession="IMS:1000047" name="pixel size y" value="1" unitCvRef="UO" unitAccession="UO:0000017" unitName="micrometer"/>
<cvParam cvRef="IMS" accession="IMS:1000092" name="line scan sequence" value="line scan"/>
<cvParam cvRef="IMS" accession="IMS:1000093" name="spotsize" value="1"/>
</scanSettings>
</scanSettingsList>
""")
write(imzml_stream, """ <instrumentConfigurationList count="1">
<instrumentConfiguration id="instrument1">
$(
if instrument_meta.instrument_model != "Not Available"
""" <cvParam cvRef="MS" accession="MS:1000031" name="instrument model" value="$(instrument_meta.instrument_model)"/>"""
else
""
end
)
$(
if instrument_meta.resolution !== nothing
""" <cvParam cvRef="MS" accession="MS:1001496" name="mass resolving power" value="$(instrument_meta.resolution)"/>"""
else
""
end
)
<componentList count="3">
<source order="1">
<cvParam cvRef="MS" accession="MS:1000075" name="MALDI source"/>
</source>
<analyzer order="2">
<cvParam cvRef="MS" accession="MS:1000084" name="time-of-flight"/>
$(
if instrument_meta.acquisition_mode == :centroid
""" <cvParam cvRef="MS" accession="MS:1000127" name="centroid spectrum"/>"""
elseif instrument_meta.acquisition_mode == :profile
""" <cvParam cvRef="MS" accession="MS:1000128" name="profile spectrum"/>"""
else
""
end
)
</analyzer>
<detector order="3">
<cvParam cvRef="MS" accession="MS:1000253" name="electron multiplier"/>
</detector>
</componentList>
<softwareRef ref="MSIConverter"/>
</instrumentConfiguration>
</instrumentConfigurationList>
""")
write(imzml_stream, """ <dataProcessingList count="$(1 + (instrument_meta.vendor_preprocessing_steps !== nothing ? length(instrument_meta.vendor_preprocessing_steps) : 0))">
<dataProcessing id="conversionProcessing">
<processingMethod order="1" softwareRef="MSIConverter">
<cvParam cvRef="MS" accession="MS:1000544" name="Conversion to imzML"/>
</processingMethod>
$(
if instrument_meta.vendor_preprocessing_steps !== nothing
join([
""" <processingMethod order="$(i + 1)" softwareRef="MSIConverter">
<cvParam cvRef="MS" accession="MS:1000589" name="data processing" value="$(step)"/>
</processingMethod>"""
for (i, step) in enumerate(instrument_meta.vendor_preprocessing_steps)
], "\n")
else
""
end
)
</dataProcessing>
</dataProcessingList>
""")
# Run and Spectrum List
spectrum_offsets = UInt64[]
write(imzml_stream, """ <run defaultInstrumentConfigurationRef="instrument1" id="run1" sampleRef="sample1">
<spectrumList count="$(length(binary_meta))" defaultDataProcessingRef="conversionProcessing">
""")
# Write each spectrum's metadata
for (i, meta) in enumerate(binary_meta)
x, y = coords[i]
spectrum_start = position(imzml_stream)
push!(spectrum_offsets, spectrum_start)
# Calculate number of points from byte length
mz_points = meta.mz_length ÷ sizeof(Float64)
int_points = meta.int_length ÷ sizeof(Float32)
write(imzml_stream, """ <spectrum id="Scan=$(i)" defaultArrayLength="$(mz_points)" index="$(i-1)">
<cvParam cvRef="MS" accession="MS:1000511" name="ms level" value="1"/>
""")
if modes[i] == CENTROID
write(imzml_stream, """ <cvParam cvRef="MS" accession="MS:1000127" name="centroid spectrum"/>
""")
elseif modes[i] == PROFILE
write(imzml_stream, """ <cvParam cvRef="MS" accession="MS:1000128" name="profile spectrum"/>
""")
end
write(imzml_stream, """ <scanList count="1">
<scan instrumentConfigurationRef="instrument1">
<cvParam cvRef="IMS" accession="IMS:1000050" name="position x" value="$(x)"/>
<cvParam cvRef="IMS" accession="IMS:1000051" name="position y" value="$(y)"/>
</scan>
</scanList>
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="0">
<referenceableParamGroupRef ref="mzArray"/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external array length" value="$(mz_points)"/>
<cvParam cvRef="IMS" accession="IMS:1000102" name="external offset" value="$(meta.mz_offset)"/>
<binary/>
</binaryDataArray>
<binaryDataArray encodedLength="0">
<referenceableParamGroupRef ref="intensityArray"/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external array length" value="$(int_points)"/>
<cvParam cvRef="IMS" accession="IMS:1000102" name="external offset" value="$(meta.int_offset)"/>
<binary/>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
""")
end
write(imzml_stream, """ </spectrumList>
</run>
</mzML>
""")
end
println("Successfully created: $target_file")
println("Successfully created: $ibd_file")
return true
catch e
@error "Failed to export imzML metadata file" exception=(e, catch_backtrace())
# Clean up partial .imzML file
isfile(target_file) && rm(target_file, force=true)
# Do not delete the .ibd file as it might be useful for debugging
return false
end
end
"""
ImportMzmlFile(source_file::String, sync_file::String, target_file::String)
Main workflow function to convert a .mzML file to an .imzML file.
# Arguments
* `source_file`: Path to the input .mzML file.
* `sync_file`: Path to the synchronization text file.
* `target_file`: Path for the output .imzML file (the .ibd will be named accordingly).
* `img_width`: width dimention for the creation of the x axis
* `img_height`: height dimention for the creation of the y axis
# Returns
- `true` if the conversion was successful.
- `false` if the conversion failed.
# Example
```julia
ImportMzmlFile("test.mzML", "test.txt", "test.imzML")
```
"""
function ImportMzmlFile(source_file::String, sync_file::String, target_file::String; img_width::Int=0, img_height::Int=0)
if !isfile(source_file)
throw(ArgumentError("Source mzML file not found: $source_file"))
end
println("Step 1: Getting scan times from .mzML file...")
scans = GetMzmlScanTime(source_file)
println("Step 2: Matching acquisition times...")
timing_matrix = MatchAcquireTime(sync_file, scans; img_width=img_width, img_height=img_height)
println("Step 3: Converting spectra and writing .ibd file...")
ibd_file = replace(target_file, r"\.imzML$"i => ".ibd")
binary_meta, coords, (width, height), pixel_modes, ibd_uuid, instrument_meta = ConvertMzmlToImzml(source_file, ibd_file, timing_matrix, scans)
# Flip image vertically to match R script output
flipped_coords = [(x, height - y + 1) for (x, y) in coords]
println("Step 4: Exporting .imzML metadata file...")
success = ExportImzml(target_file, binary_meta, flipped_coords, (width, height), pixel_modes, ibd_uuid, instrument_meta)
if success
println("Conversion successful: $target_file")
else
println("Conversion failed.")
end
return success
end
+161
View File
@@ -0,0 +1,161 @@
# src/ParserHelpers.jl
"""
This file provides common helper functions for parsing mzML and imzML files.
"""
# ============================================================================
#
# Data Structures and Low-Level Parser Helpers
#
# ============================================================================
"""
SpecDim
A struct to hold configuration for a spectral data axis (e.g., m/z or intensity).
"""
mutable struct SpecDim
Format::Type
Packed::Bool
Axis::Int
Skip::Int
Mode::SpectrumMode
end
"""
find_tag(stream, regex::Regex)
Reads a stream line-by-line until a line matches the provided regex.
# Arguments
- `stream::IO`: The stream to parse the metadata from.
- `regex::Regex`: The regex to match.
# Returns
- A `RegexMatch` object if a match is found, otherwise throws an error.
# Example
```julia
find_tag(open("test.mzML"), r"<spectrum")
```
"""
function find_tag(stream, regex::Regex)
while !eof(stream)
line = readline(stream)
isTag = match(regex, line)
if isTag !== nothing
return isTag
end
end
error("Tag not found for regex: $regex")
end
"""
get_attribute(source::String, tag::String = "([^=]+)")
Retrieves an attribute's value from an XML tag string.
# Arguments
- `source::String`: The string to parse the attribute from.
- `tag::String`: The tag to match.
# Returns
- A `RegexMatch` object containing the attribute and its value.
# Example
```julia
get_attribute("<spectrum index=\"1\">", "index")
```
"""
function get_attribute(source::AbstractString, tag::String = "([^=]+)")
# Construct the regex pattern string
pattern_str = "\\s*" * tag * "=\"([^\"]*)\""
regStr = Regex(pattern_str)
return match(regStr, source)
end
"""
configure_spec_dim(stream)
Parses a block of `<cvParam>` tags from an XML stream to configure a `SpecDim`
struct. It reads accessions to determine the data format (e.g., `Float32`),
compression status (`zlib`), and axis type (m/z vs. intensity).
# Arguments
- `stream::IO`: An IO stream positioned at the start of the `cvParam` block.
# Returns
- A `SpecDim` struct populated with the parsed configuration.
# Example
```julia
configure_spec_dim(open("test.mzML"))
```
"""
function configure_spec_dim(stream)
axis = SpecDim(Float64, false, 1, 0, UNKNOWN) # Add UNKNOWN as default mode
while !eof(stream)
currLine = readline(stream)
matchInfo = match(r"^\s*<(cvParam)", currLine)
if matchInfo === nothing
# Check for end of cvParam block
if match(r"^\s*</", currLine) !== nothing
return axis
end
continue
end
index = length(matchInfo.captures[1])
attr_match = get_attribute(currLine[index:end], "accession")
if attr_match !== nothing
accession = attr_match.captures[1]
if accession == "MS:1000515" # intensity array
axis.Axis = 2
elseif accession == "MS:1000519" # 32-bit integer
axis.Format = Int32
elseif accession == "MS:1000521" # 32-bit float
axis.Format = Float32
elseif accession == "MS:1000522" # 64-bit integer
axis.Format = Int64
elseif accession == "MS:1000574" # zlib compression
axis.Packed = true
elseif accession == "MS:1000127" # centroid spectrum
axis.Mode = CENTROID
elseif accession == "MS:1000128" # profile spectrum
axis.Mode = PROFILE
end
end
end
return axis
end
# ============================================================================
#
# Data Structures and Helpers for mzML lazy parsing
#
# ============================================================================
"""
CVParams
A mutable struct used during the parsing of mzML files to temporarily hold
CV parameter information for a data array before it is converted into a
`SpectrumAsset`.
# Fields
- `format`: The data type (e.g., `Float64`).
- `is_compressed`: A boolean indicating if the data is compressed.
- `axis_type`: A symbol indicating the array type (`:mz` or `:intensity`).
"""
mutable struct CVParams
format::Type
is_compressed::Bool
axis_type::Symbol
end
+49
View File
@@ -0,0 +1,49 @@
# src/Paths.jl
# Shared filesystem locations for JuliaMSI.
#
# All application-owned files live under the project's `public/` directory.
# Keeping those paths in one place avoids mixing `pwd()`-relative and
# `@__DIR__`-relative paths (which is especially fragile on Windows).
const PROJECT_ROOT = normpath(joinpath(@__DIR__, ".."))
const PUBLIC_DIR = joinpath(PROJECT_ROOT, "public")
const DEFAULT_REGISTRY_PATH = joinpath(PUBLIC_DIR, "registry.json")
"""
ensure_public_dir(; path::AbstractString = PUBLIC_DIR) -> String
Ensures that the application's `public/` directory exists and is writable.
JuliaMSI writes generated bitmaps, masks, and `registry.json` into this
directory, so a read-only or missing directory is a fatal configuration error.
A short write probe is used instead of relying only on permission bits, because
Windows ACLs and read-only attributes are not reliably reflected by `iswritable`.
"""
function ensure_public_dir(; path::AbstractString = PUBLIC_DIR)
try
mkpath(path)
catch e
error("JuliaMSI cannot create the public directory at \"$path\". " *
"Move the project to a writable location or fix the directory permissions. " *
"Original error: $(sprint(showerror, e))")
end
isdir(path) ||
error("JuliaMSI expected a directory at \"$path\", but it is not a directory.")
probe = joinpath(path, ".juliamsi_write_probe_$(getpid())")
try
open(probe, "w") do io
write(io, "ok")
end
catch e
error("JuliaMSI cannot write to \"$path\". The application requires write " *
"access to its public directory for generated images, masks, and " *
"registry.json. Move the project to a writable location or fix the " *
"directory permissions. Original error: $(sprint(showerror, e))")
finally
isfile(probe) && rm(probe; force=true)
end
return String(path)
end
+30
View File
@@ -0,0 +1,30 @@
# src/PlottingStubs.jl
#
# These names used to live in MSI_src and were exported from the core module.
# They are GUI/plotting helpers that require CairoMakie, so their
# implementations now live in julia_imzML_visual.jl. Keeping explicit stubs
# here gives downstream code an actionable error instead of an UndefVarError,
# while keeping `using MSI_src` lightweight for headless use.
#
# The stubs are intentionally NOT exported.
const _PLOTTING_MOVED_MESSAGE = """
This function is a GUI/plotting helper and is no longer implemented in the
MSI_src core. It moved to the GUI layer (julia_imzML_visual.jl) so that
`using MSI_src` does not load CairoMakie.
Load the GUI module that defines it, or call the corresponding helper from your
application/plotting layer. See the JuliaMSI README for the migration note.
"""
function plot_slice(args...; kwargs...)
error(_PLOTTING_MOVED_MESSAGE)
end
function plot_slices(args...; kwargs...)
error(_PLOTTING_MOVED_MESSAGE)
end
function generate_colorbar_image(args...; kwargs...)
error(_PLOTTING_MOVED_MESSAGE)
end
File diff suppressed because it is too large Load Diff
+1259
View File
File diff suppressed because it is too large Load Diff
+510
View File
@@ -0,0 +1,510 @@
# src/PreprocessingPipeline.jl
using Base.Threads # For multithreading
using Printf # For @sprintf
using Interpolations # For linear_interpolation
using DataFrames # For saving feature matrix
using CSV # For saving feature matrix
# This file provides a set of functions that apply preprocessing steps to a vector of
# `MutableSpectrum` objects. Each function takes the vector of spectra and a dictionary
# of parameters, modifying the spectra in-place where appropriate. This mirrors the
# logic from `test/run_preprocessing.jl` but is intended for use in the main application.
# ===================================================================
# PREPROCESSING PIPELINE FUNCTIONS (IN-PLACE)
# ===================================================================
"""
apply_baseline_correction(spectra::Vector{MutableSpectrum}, params::Dict)
Applies baseline correction to the intensity data of each spectrum. This function
modifies the `.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The algorithm to use. Supports `:snip`, `:convex_hull`, `:median`. Defaults to `:snip`.
- `:iterations` (Int): The number of iterations for the SNIP algorithm. Defaults to 100.
- `:window` (Int): The window size for the Median algorithm. Defaults to 20.
"""
function apply_baseline_correction(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :snip)
iterations = get(params, :iterations, 100)
window = get(params, :window, 20)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
original_length = length(s.intensity)
baseline = apply_baseline_correction_core(s.intensity; method=method, iterations=iterations, window=window)
# CRITICAL: Ensure baseline has the same length as intensity
if length(baseline) != original_length
@warn "Baseline correction: length mismatch for spectrum $(s.id). baseline=$(length(baseline)), intensity=$original_length. Skipping this spectrum."
continue
end
s.intensity = max.(0.0, s.intensity .- baseline)
end
end
end
"""
apply_intensity_transformation(spectra::Vector{MutableSpectrum}, params::Dict)
Applies an intensity transformation to the intensity data of each spectrum. This function
modifies the `.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The transformation to apply. Supports `:sqrt`, `:log`, `:log2`, `:log10`, `:log1p`. Defaults to `:sqrt`.
"""
function apply_intensity_transformation(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :sqrt)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
original_length = length(s.intensity)
transformed = transform_intensity_core(s.intensity; method=method)
# CRITICAL: Ensure transformation preserves array length
if length(transformed) != original_length
@warn "Intensity transformation: length mismatch for spectrum $(s.id). transformed=$(length(transformed)), original=$original_length. Skipping this spectrum."
continue
end
s.intensity = transformed
end
end
end
"""
apply_smoothing(spectra::Vector{MutableSpectrum}, params::Dict)
Applies a smoothing filter to the intensity data of each spectrum. This function
modifies the `.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The smoothing algorithm. Supports `:savitzky_golay`, `:moving_average`. Defaults to `:savitzky_golay`.
- `:window` (Int): The size of the smoothing window. Defaults to 9.
- `:order` (Int): The polynomial order for the Savitzky-Golay filter. Defaults to 2.
"""
function apply_smoothing(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :savitzky_golay)
window = get(params, :window, 9)
order = get(params, :order, 2)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
original_length = length(s.intensity)
smoothed_intensity = smooth_spectrum_core(s.intensity; method=method, window=window, order=order)
# CRITICAL: Ensure smoothing preserves array length
if length(smoothed_intensity) != original_length
@warn "Smoothing: length mismatch for spectrum $(s.id). smoothed=$(length(smoothed_intensity)), original=$original_length, method=$method, window=$window. Skipping this spectrum."
continue
end
s.intensity = max.(0.0, smoothed_intensity)
end
end
end
"""
apply_peak_picking(spectra::Vector{MutableSpectrum}, params::Dict)
Detects peaks in each spectrum and stores them in the `.peaks` field of each
`MutableSpectrum` object, modifying it in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The peak detection algorithm. Supports `:profile`, `:wavelet`, `:centroid`. Defaults to `:profile`.
- `:snr_threshold` (Float64): Signal-to-Noise Ratio threshold.
- `:half_window` (Int): Half-window size for local maxima detection.
- `:min_peak_prominence` (Float64): Minimum required prominence for a peak.
- `:merge_peaks_tolerance` (Float64): m/z tolerance to merge adjacent peaks.
"""
function apply_peak_picking(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :profile)
snr_threshold = get(params, :snr_threshold, 3.0)
half_window = get(params, :half_window, 10)
min_peak_prominence = get(params, :min_peak_prominence, 0.1)
merge_peaks_tolerance = get(params, :merge_peaks_tolerance, 0.002)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
# old_len = length(s.peaks)
if method == :profile
s.peaks = detect_peaks_profile_core(s.mz, s.intensity; snr_threshold=snr_threshold, half_window=half_window, min_peak_prominence=min_peak_prominence, merge_peaks_tolerance=merge_peaks_tolerance)
elseif method == :wavelet
s.peaks = detect_peaks_wavelet_core(s.mz, s.intensity; snr_threshold=snr_threshold, half_window=half_window)
elseif method == :centroid
s.peaks = detect_peaks_centroid_core(s.mz, s.intensity; snr_threshold=snr_threshold)
else
s.peaks = detect_peaks_profile_core(s.mz, s.intensity; snr_threshold=snr_threshold, half_window=half_window)
end
# @info "Spectrum $(s.id): detected $(length(s.peaks)) peaks"
else
s.peaks = []
end
end
end
"""
apply_peak_selection(spectra::Vector{MutableSpectrum}, params::Dict)
Filters peaks within each spectrum based on quality criteria. This step removes peaks
that do not meet the specified thresholds for signal-to-noise ratio (SNR),
full width at half maximum (FWHM), and peak shape.
This function modifies the `.peaks` field of each `MutableSpectrum` object in the `spectra` vector in-place.
# Parameters from `params` Dict:
- `:min_snr` (Float64): The minimum Signal-to-Noise Ratio required for a peak to be kept.
- `:min_fwhm_ppm` (Float64): The minimum FWHM (in ppm) for a peak.
- `:max_fwhm_ppm` (Float64): The maximum FWHM (in ppm) for a peak.
- `:min_shape_r2` (Float64): The minimum R² value from a Gaussian fit, measuring peak shape quality.
"""
function apply_peak_selection(spectra::Vector{MutableSpectrum}, params::Dict)
min_snr = get(params, :min_snr, 0.0)
min_fwhm = get(params, :min_fwhm_ppm, 0.0)
max_fwhm = get(params, :max_fwhm_ppm, Inf)
min_r2 = get(params, :min_shape_r2, 0.0)
# Handle `nothing` from params, which can happen if pre-calculation fails.
min_snr = isnothing(min_snr) ? 0.0 : min_snr
min_fwhm = isnothing(min_fwhm) ? 0.0 : min_fwhm
max_fwhm = isnothing(max_fwhm) ? Inf : max_fwhm
min_r2 = isnothing(min_r2) ? 0.0 : min_r2
Threads.@threads for s in spectra
if !isempty(s.peaks)
filter!(p ->
p.snr >= min_snr &&
(min_fwhm <= p.fwhm <= max_fwhm) &&
p.shape_r2 >= min_r2,
s.peaks
)
end
end
end
"""
apply_calibration(spectra::Vector{MutableSpectrum}, params::Dict, reference_peaks::Dict)
Performs mass calibration on each spectrum using a list of internal standards.
This function modifies the `.mz` axis of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The calibration method. Only `:internal_standards` is currently meaningful.
- `:ppm_tolerance` (Float64): The tolerance in PPM for matching detected peaks to reference masses.
- `:fit_order` (Int): The polynomial order for the calibration fit (not yet used in this implementation, defaults to linear).
"""
function apply_calibration(spectra::Vector{MutableSpectrum}, params::Dict, reference_peaks::Dict)
method = get(params, :method, :none)
ppm_tolerance = get(params, :ppm_tolerance, 20.0)
if method == :none || isempty(reference_peaks)
return
end
reference_masses = collect(keys(reference_peaks))
Threads.@threads for i in 1:length(spectra)
s = spectra[i]
if validate_spectrum(s.mz, s.intensity)
original_length = length(s.mz)
matched_peaks = find_calibration_peaks_core(s.mz, s.intensity, reference_masses; ppm_tolerance=ppm_tolerance)
if length(matched_peaks) >= 2
measured = sort(collect(values(matched_peaks)))
theoretical = sort(collect(keys(matched_peaks)))
itp = linear_interpolation(measured, theoretical, extrapolation_bc=Line())
new_mz = itp(s.mz)
# CRITICAL: Ensure m/z axis preserves array length
if length(new_mz) != original_length
@warn "Calibration: length mismatch for spectrum $(s.id). new_mz=$(length(new_mz)), original=$original_length. Skipping this spectrum."
continue
end
s.mz = new_mz # Modify mz-axis in-place
else
@warn "Spectrum $(s.id): insufficient reference peaks ($(length(matched_peaks)) found), skipping calibration."
end
end
end
end
"""
apply_peak_alignment(spectra::Vector{MutableSpectrum}, params::Dict)
Aligns the m/z axis of all spectra to a chosen reference spectrum. This function
modifies both the `.mz` axis and the m/z values within the `.peaks` field of each
`MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The alignment algorithm. Supports `:lowess`, `:linear`, `:ransac`.
- `:tolerance` (Float64): The tolerance for matching peaks between spectra.
- `:tolerance_unit` (Symbol): The unit for tolerance, `:mz` or `:ppm`.
"""
function apply_peak_alignment(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :none)
tolerance = get(params, :tolerance, 0.002)
tolerance_unit = get(params, :tolerance_unit, :mz)
if method == :none
return
end
ref_find_idx = findfirst(s -> !isempty(s.peaks), spectra)
if ref_find_idx === nothing
@warn "Insufficient spectra with peaks for alignment. Skipping."
return
end
ref_spectrum = spectra[ref_find_idx]
ref_peaks_mz = [p.mz for p in ref_spectrum.peaks]
Threads.@threads for s in spectra
if s.id == ref_spectrum.id || isempty(s.peaks)
continue
end
current_peaks_mz = [p.mz for p in s.peaks]
alignment_func = align_peaks_lowess_core(ref_peaks_mz, current_peaks_mz; method=method, tolerance=tolerance, tolerance_unit=tolerance_unit)
original_length = length(s.mz)
new_mz = alignment_func.(s.mz)
# CRITICAL: Ensure alignment preserves array length
if length(new_mz) != original_length
@warn "Peak alignment: m/z length mismatch for spectrum $(s.id). new_mz=$(length(new_mz)), original=$original_length. Skipping this spectrum."
continue
end
s.mz = new_mz # Update m/z axis
# Update peak m/z values
for i in 1:length(s.peaks)
old_peak = s.peaks[i]
aligned_peak_mz = alignment_func(old_peak.mz)
s.peaks[i] = (mz=aligned_peak_mz, intensity=old_peak.intensity, fwhm=old_peak.fwhm, shape_r2=old_peak.shape_r2, snr=old_peak.snr, prominence=old_peak.prominence)
end
end
end
"""
apply_normalization(spectra::Vector{MutableSpectrum}, params::Dict)
Applies intensity normalization to each spectrum. This function modifies the
`.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The normalization method. Supports `:tic`, `:median`, `:rms`, `:none`.
"""
function apply_normalization(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :tic)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
original_length = length(s.intensity)
normalized = apply_normalization_core(s.intensity; method=method)
# CRITICAL: Ensure normalization preserves array length
if length(normalized) != original_length
@warn "Normalization: length mismatch for spectrum $(s.id). normalized=$(length(normalized)), original=$original_length. Skipping this spectrum."
continue
end
s.intensity = normalized
end
end
end
function apply_peak_binning(spectra::Vector{MutableSpectrum}, params::Dict)
tolerance = get(params, :tolerance, 20.0)
tolerance_unit = get(params, :tolerance_unit, :ppm)
min_peak_per_bin = get(params, :min_peak_per_bin, 3)
if isempty(spectra) || all(s -> isempty(s.peaks), spectra)
@warn "No peaks found for binning. Returning empty feature matrix."
return nothing, nothing
end
all_peaks = Vector{Tuple{Float64, Float64}}()
for s in spectra
for p in s.peaks
push!(all_peaks, (p.mz, p.intensity))
end
end
if isempty(all_peaks)
@warn "No peaks collected for binning."
return nothing, nothing
end
sort!(all_peaks, by=x->x[1])
bin_centers = Float64[]
bin_intensities = Float64[]
i = 1
while i <= length(all_peaks)
current_bin_start = i
current_peak = all_peaks[i]
j = i + 1
while j <= length(all_peaks)
next_peak = all_peaks[j]
tol = (tolerance_unit == :ppm) ? (current_peak[1] * tolerance / 1e6) : tolerance
if (next_peak[1] - current_peak[1]) <= tol
j += 1
else
break
end
end
current_bin_end = j - 1
bin_size = current_bin_end - current_bin_start + 1
if bin_size >= min_peak_per_bin
bin_peaks = all_peaks[current_bin_start:current_bin_end]
mz_sum = sum(p[1] for p in bin_peaks)
intensity_sum = sum(p[2] for p in bin_peaks)
mz_center = mz_sum / bin_size
avg_intensity = intensity_sum / bin_size
push!(bin_centers, mz_center)
push!(bin_intensities, avg_intensity)
end
i = j
end
if !isempty(bin_centers)
n_bins = length(bin_centers)
feature_matrix = Matrix{Float64}(undef, 2, n_bins)
for i in 1:n_bins
feature_matrix[1, i] = bin_centers[i]
feature_matrix[2, i] = bin_intensities[i]
end
bin_info = [(bin_centers[i], bin_intensities[i]) for i in 1:n_bins]
return feature_matrix, bin_info
else
@warn "No bins created after filtering"
return nothing, nothing
end
end
"""
save_feature_matrix(feature_matrix::Matrix{Float64}, bin_info, output_dir::String) -> Tuple{String, String}
Saves the aggregated `2 x n_bins` feature matrix into two different CSV formats.
1. **Simple Format (`feature_matrix_simple.csv`):** A two-column CSV with "mz" and "intensity".
2. **Standard Format (`feature_matrix_standard.csv`):** A row-based format where m/z values are headers and there is a single data row for the aggregated spectrum.
# Arguments
- `feature_matrix::Matrix{Float64}`: The `2 x n_bins` matrix from `apply_peak_binning`.
- `bin_info`: The associated bin information (currently unused but kept for compatibility).
- `output_dir::String`: The directory where the output CSV files will be saved.
# Returns
- A tuple containing the paths to the two saved files.
"""
function save_feature_matrix(feature_matrix::Matrix{Float64}, bin_info, output_dir::String)
# Save as simple CSV with m/z and intensity rows
csv_path = joinpath(output_dir, "feature_matrix_simple.csv")
open(csv_path, "w") do io
write(io, "mz,intensity\n")
for i in 1:size(feature_matrix, 2)
mz = feature_matrix[1, i]
intensity = feature_matrix[2, i]
write(io, "$mz,$intensity\n")
end
end
@info "Saved simple feature matrix: $csv_path"
# Also save in a more standard format for MSI
csv_path_standard = joinpath(output_dir, "feature_matrix_standard.csv")
open(csv_path_standard, "w") do io
write(io, "sample_type,")
mz_headers = [@sprintf("mz_%.4f", feature_matrix[1, i]) for i in 1:size(feature_matrix, 2)]
write(io, join(mz_headers, ",") * "\n")
write(io, "aggregated_spectrum,")
intensity_values = [feature_matrix[2, i] for i in 1:size(feature_matrix, 2)]
write(io, join(string.(intensity_values), ",") * "\n")
end
@info "Saved standard format matrix: $csv_path_standard"
return csv_path, csv_path_standard
end
function execute_full_preprocessing(progress_callback::Function, # Now first positional
spectra::Vector{MutableSpectrum}, params::Dict,
pipeline_steps::Vector{String}, reference_peaks::Dict,
mask_path::Union{String, Nothing} # Positional argument
)
println("Starting preprocessing pipeline with $(length(spectra)) spectra")
println("Steps: $(join(pipeline_steps, " -> "))")
# These variables will be populated by the pipeline steps
feature_matrix = nothing
bin_definitions = nothing
# Apply pipeline steps, modifying `spectra` in-place
for step in pipeline_steps
progress_callback(step)
println("\n" * "-"^60)
println("PROCESSING STEP: $step")
println("-"^60)
if step == "stabilization"
println(" Applying intensity transformation (stabilization)")
apply_intensity_transformation(spectra, get(params, :Stabilization, Dict()))
elseif step == "baseline_correction"
println(" Applying baseline correction")
apply_baseline_correction(spectra, get(params, :BaselineCorrection, Dict()))
elseif step == "smoothing"
println(" Applying smoothing")
apply_smoothing(spectra, get(params, :Smoothing, Dict()))
elseif step == "peak_picking"
println(" Applying peak picking")
apply_peak_picking(spectra, get(params, :PeakPicking, Dict()))
elseif step == "peak_selection"
println(" Applying peak selection")
apply_peak_selection(spectra, get(params, :PeakSelection, Dict()))
elseif step == "calibration"
println(" Applying calibration")
apply_calibration(spectra, get(params, :Calibration, Dict()), reference_peaks)
elseif step == "peak_alignment"
println(" Applying peak alignment")
apply_peak_alignment(spectra, get(params, :PeakAlignment, Dict()))
elseif step == "normalization"
println(" Applying normalization")
apply_normalization(spectra, get(params, :Normalization, Dict()))
elseif step == "peak_binning"
println(" Applying peak binning")
feature_matrix, bin_definitions = apply_peak_binning(spectra, get(params, :PeakBinning, Dict()))
else
@warn "Unknown step: $step, skipping"
end
println("✓ Completed step: $step")
end
return feature_matrix, bin_definitions
end
+79
View File
@@ -0,0 +1,79 @@
# src/ResourcePool.jl
using Base.Threads
"""
ResourcePool{T}
A thread-safe pool for reusing objects of type `T` to minimize allocations and GC pressure.
Specifically designed for high-performance computing tasks where large buffers are needed
repeatedly across multiple threads.
# Fields:
- `pool::Vector{T}`: The underlying storage for idle resources.
- `lock::ReentrantLock`: Ensures thread-safe access to the pool.
- `max_size::Int`: Maximum number of resources to hold in the pool.
- `constructor::Function`: A function to create a new resource if the pool is empty.
"""
mutable struct ResourcePool{T}
pool::Vector{T}
lock::ReentrantLock
max_size::Int
constructor::Function
end
"""
ResourcePool{T}(constructor::Function; max_size::Int=2 * nthreads())
Creates a new `ResourcePool` for resources of type `T`.
"""
function ResourcePool{T}(constructor::Function; max_size::Int=2 * nthreads()) where T
return ResourcePool{T}(T[], ReentrantLock(), max_size, constructor)
end
"""
acquire(pool::ResourcePool{T}) -> T
Retrieves a resource from the pool. If the pool is empty, a new resource is created
using the constructor.
"""
function acquire(pool::ResourcePool{T}) where T
lock(pool.lock) do
if !isempty(pool.pool)
return pop!(pool.pool)
end
end
# Create new resource outside of lock to minimize contention
return pool.constructor()
end
"""
release!(pool::ResourcePool{T}, resource::T)
Returns a resource to the pool for later reuse. If the pool is already at `max_size`,
the resource is allowed to be garbage collected.
"""
function release!(pool::ResourcePool{T}, resource::T) where T
lock(pool.lock) do
if length(pool.pool) < pool.max_size
push!(pool.pool, resource)
end
end
return nothing
end
"""
with_resource(f::Function, pool::ResourcePool{T})
Acquires a resource from the pool, executes the function `f(resource)`, and
automatically releases the resource back to the pool when finished.
"""
function with_resource(f::Function, pool::ResourcePool{T}) where T
resource = acquire(pool)
try
return f(resource)
finally
release!(pool, resource)
end
end
+317
View File
@@ -0,0 +1,317 @@
# src/StreamingKernels.jl
# ============================================================================
# In-Place Spectral Kernels for the Streaming Pipeline
#
# These functions operate on raw (mz, intensity) views from the Sprint 1
# Mmap engine. They write results back to the input buffers using .= to
# achieve zero-allocation processing per spectrum.
#
# Design contract:
# - All !-suffixed functions modify their arguments in-place
# - If a kernel needs temporary storage, it borrows from data.resource_pool
# - No function creates MutableSpectrum objects
# ============================================================================
using Statistics: mean, median
# =============================================================================
# Category A: Purely Streamable Kernels
# =============================================================================
"""
normalize_inplace!(intensity::AbstractVector{<:Real}, method::Symbol)
Normalizes intensity values in-place. Supports :tic, :median, :rms.
Zero-allocation for the normalization itself.
"""
@inline function normalize_inplace!(intensity::AbstractVector{<:Real}, method::Symbol)
if method === :tic
s = sum(intensity)
if s > 0
intensity ./= s
end
elseif method === :median
m = median(intensity)
if m > 0
intensity ./= m
end
elseif method === :rms
s = sqrt(sum(abs2, intensity) / length(intensity))
if s > 0
intensity ./= s
end
end
return intensity
end
"""
transform_inplace!(intensity::AbstractVector{Float64}, method::Symbol)
Applies intensity transformation in-place. Supports :sqrt, :log1p, :log, :log2, :log10.
"""
@inline function transform_inplace!(intensity::AbstractVector{Float64}, method::Symbol)
if method === :sqrt
@inbounds @simd for i in eachindex(intensity)
intensity[i] = sqrt(max(0.0, intensity[i]))
end
elseif method === :log1p
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log1p(max(0.0, intensity[i]))
end
elseif method === :log
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log(max(eps(Float64), intensity[i]))
end
elseif method === :log2
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log2(max(eps(Float64), intensity[i]))
end
elseif method === :log10
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log10(max(eps(Float64), intensity[i]))
end
end
return intensity
end
"""
smooth_inplace!(intensity::AbstractVector{Float64}, data::MSIData;
method::Symbol=:savitzky_golay, window::Int=9, order::Int=2)
Smooths intensity in-place using a temporary buffer from the resource pool.
The SavitzkyGolay library allocates internally, but we copy the result back
to the original buffer and return the pool buffer.
"""
function smooth_inplace!(intensity::AbstractVector{Float64}, scratch::AbstractVector{Float64}, data::MSIData;
method::Symbol=:savitzky_golay, window::Int=9, order::Int=2)
n = length(intensity)
if n < 3
return intensity
end
if method === :savitzky_golay
win = isodd(window) ? window : window + 1
if n < win
return intensity
end
# SavitzkyGolay handles its own math but causes mild allocation.
res = SavitzkyGolay.savitzky_golay(collect(intensity), win, order)
@inbounds for i in eachindex(intensity)
intensity[i] = max(0.0, res.y[i])
end
elseif method === :moving_average
copyto!(scratch, intensity)
half_w = div(window, 2)
@inbounds for i in 1:n
s_idx = max(1, i - half_w)
e_idx = min(n, i + half_w)
s = 0.0
@simd for j in s_idx:e_idx
s += scratch[j]
end
intensity[i] = max(0.0, s / (e_idx - s_idx + 1))
end
end
return intensity
end
"""
baseline_subtract_inplace!(intensity::AbstractVector{Float64}, data::MSIData;
method::Symbol=:snip, iterations::Int=100, window::Int=20)
Subtracts baseline from intensity in-place. Uses two pool buffers for the
SNIP ping-pong iteration to avoid any heap allocation in the hot loop.
"""
function baseline_subtract_inplace!(intensity::AbstractVector{Float64}, scratch::AbstractVector{Float64}, data::MSIData;
method::Symbol=:snip, iterations::Int=100, window::Int=20)
n = length(intensity)
if n < 3
return intensity
end
if method === :snip
copyto!(scratch, intensity)
for k in 1:iterations
prev_val = scratch[1]
scratch[1] = min(scratch[1], scratch[2])
@inbounds for i in 2:n-1
curr_val = scratch[i]
scratch[i] = min(curr_val, 0.5 * (prev_val + scratch[i+1]))
prev_val = curr_val
end
scratch[n] = min(scratch[n], prev_val)
end
@inbounds @simd for i in 1:n
intensity[i] = max(0.0, intensity[i] - scratch[i])
end
elseif method === :convex_hull
baseline = convex_hull_baseline(intensity)
@inbounds @simd for i in eachindex(intensity)
intensity[i] = max(0.0, intensity[i] - baseline[i])
end
elseif method === :median
baseline = median_baseline(intensity; window=window)
@inbounds @simd for i in eachindex(intensity)
intensity[i] = max(0.0, intensity[i] - baseline[i])
end
end
return intensity
end
"""
detect_peaks_streaming(mz::AbstractVector, intensity::AbstractVector;
method::Symbol=:profile, snr_threshold::Float64=3.0,
half_window::Int=10, min_peak_prominence::Float64=0.1,
merge_peaks_tolerance::Float64=0.002)
Detects peaks and returns a vector of (mz, intensity) tuples.
This delegates to existing _core functions but returns a lightweight format
suitable for sparse accumulation (no NamedTuple overhead in the hot path).
"""
function detect_peaks_streaming(callback::Function, mz::AbstractVector{Float64}, intensity::AbstractVector{Float64}, scratch::AbstractVector{Float64};
method::Symbol=:profile, snr_threshold::Float64=3.0,
half_window::Int=10, min_peak_prominence::Float64=0.1,
merge_peaks_tolerance::Float64=0.002)
n = length(intensity)
if n < 3
return
end
if method === :profile || method === :wavelet
# Zero-allocation noisy estimation (using mean of bottom half)
sum_i = 0.0
@simd for i in 1:n
sum_i += intensity[i]
end
mean_i = sum_i / n
sum_noise = 0.0
count_noise = 0
@inbounds for i in 1:n
if intensity[i] < mean_i
sum_noise += intensity[i]
count_noise += 1
end
end
# Use * 1.5 as an approximation to MAD
noise_level = count_noise > 0 ? (sum_noise / count_noise) * 1.5 + eps(Float64) : mean_i + eps(Float64)
# We will use the scratch buffer to store candidate indices to avoid allocating `Int[]`
# Because scratch is Float64, we can safely store integer indices up to 2^53 exactly.
num_candidates = 0
@inbounds for i in 2:n-1
if intensity[i] > snr_threshold * noise_level
left = max(1, i - half_window)
right = min(n, i + half_window)
is_max = true
for j in left:right
if intensity[j] > intensity[i]
is_max = false
break
end
end
if is_max
# Compute prominence
min_left = intensity[i]
for j in left:i
if intensity[j] < min_left
min_left = intensity[j]
end
end
min_right = intensity[i]
for j in i:right
if intensity[j] < min_right
min_right = intensity[j]
end
end
prominence = intensity[i] - max(min_left, min_right)
if prominence > min_peak_prominence * intensity[i]
num_candidates += 1
scratch[num_candidates] = i
end
end
end
end
# Merge close peaks
if num_candidates > 0
if merge_peaks_tolerance > 0
last_idx = trunc(Int, scratch[1])
# We emit the first peak lazily down below, so let's compact them in place
num_merged = 1
for i in 2:num_candidates
idx = trunc(Int, scratch[i])
if (mz[idx] - mz[last_idx]) > merge_peaks_tolerance
num_merged += 1
scratch[num_merged] = idx
last_idx = idx
elseif intensity[idx] > intensity[last_idx]
scratch[num_merged] = idx
last_idx = idx
end
end
num_candidates = num_merged
end
# Emit merged peaks
for i in 1:num_candidates
idx = trunc(Int, scratch[i])
callback(mz[idx], intensity[idx])
end
end
elseif method === :centroid
# Just use any value over snr_threshold * mean_noise
sum_i = sum(intensity)
mean_i = sum_i / n
noise_level = mean_i + eps(Float64)
@inbounds for i in 1:n
if intensity[i] > snr_threshold * noise_level
callback(mz[i], intensity[i])
end
end
end
end
# =============================================================================
# Category B: Conditionally Streamable Kernels (Fixed-Reference)
# =============================================================================
"""
calibrate_inplace!(mz::Vector{Float64}, intensity::AbstractVector,
reference_masses::Vector{Float64}; ppm_tolerance::Float64=20.0)
Calibrates the m/z axis in-place using a fixed dictionary of internal standard
reference masses. This is streamable because the reference is constant.
Returns `true` if calibration was applied, `false` if insufficient peaks were found.
"""
function calibrate_inplace!(mz::Vector{Float64}, intensity::AbstractVector,
reference_masses::Vector{Float64}; ppm_tolerance::Float64=20.0)
matched_peaks = find_calibration_peaks_core(mz, intensity, reference_masses;
ppm_tolerance=ppm_tolerance)
if length(matched_peaks) < 2
return false # Insufficient reference peaks
end
measured = sort(collect(values(matched_peaks)))
theoretical = sort(collect(keys(matched_peaks)))
itp = linear_interpolation(measured, theoretical, extrapolation_bc=Line())
# Apply calibration in-place
@inbounds for i in eachindex(mz)
mz[i] = itp(mz[i])
end
return true
end
+403
View File
@@ -0,0 +1,403 @@
# src/StreamingPipeline.jl
# ============================================================================
# The Streaming Pipeline Executor
#
# This module provides `process_dataset!`, the Sprint 2 master function that
# streams spectral data through an in-place kernel chain and accumulates
# results into a SparseMatrixCSC without ever holding more than 1 spectrum
# per thread in RAM.
#
# Architecture:
# 1. _iterate_spectra_fast → Mmap zero-copy views
# 2. copyto!(writable_buf, view) → makes mutable copy for kernels
# 3. Kernel chain: smooth! → baseline! → peaks → bin
# 4. Thread-local (I, J, V) sparse accumulators
# 5. Final sparse(I, J, V, num_bins, num_spectra) assembly
#
# This works alongside the existing execute_full_preprocessing in
# PreprocessingPipeline.jl — it does NOT replace the app.jl integration.
# ============================================================================
using SparseArrays
using Printf
# =============================================================================
# Configuration Structs
# =============================================================================
"""
StreamingStep
Represents a single step in the streaming pipeline.
"""
struct StreamingStep
name::Symbol
params::Dict{Symbol, Any}
end
"""
PipelineConfig
Holds the complete configuration for a streaming pipeline execution.
# Fields
- `steps::Vector{StreamingStep}` — ordered sequence of processing steps
- `reference_peaks::Vector{Float64}` — fixed m/z values for calibration (Category B)
- `num_bins::Int` — number of bins for the output feature matrix
- `min_peaks_per_bin::Int` — minimum peak count to keep a bin
- `frequency_threshold::Float64` — minimum fraction of spectra a bin must appear in (0.0-1.0)
# Example
```julia
config = PipelineConfig(
steps = [
StreamingStep(:smoothing, Dict(:method => :savitzky_golay, :window => 9, :order => 2)),
StreamingStep(:baseline_correction, Dict(:method => :snip, :iterations => 100)),
StreamingStep(:normalization, Dict(:method => :tic)),
StreamingStep(:peak_picking, Dict(:method => :profile, :snr_threshold => 3.0)),
],
num_bins = 2000
)
```
"""
struct PipelineConfig
steps::Vector{StreamingStep}
reference_peaks::Vector{Float64}
num_bins::Int
min_peaks_per_bin::Int
frequency_threshold::Float64
end
# Convenience constructor with defaults
function PipelineConfig(; steps::Vector{StreamingStep}=StreamingStep[],
reference_peaks::Vector{Float64}=Float64[],
num_bins::Int=2000,
min_peaks_per_bin::Int=3,
frequency_threshold::Float64=0.0)
return PipelineConfig(steps, reference_peaks, num_bins, min_peaks_per_bin, frequency_threshold)
end
# =============================================================================
# Sparse Accumulator (Thread-Local)
# =============================================================================
"""
SparseAccumulator
Thread-local accumulator for sparse matrix construction.
Collects (row, col, val) triplets that will be assembled into
a SparseMatrixCSC at the end of the pipeline.
"""
mutable struct SparseAccumulator
I::Vector{Int} # Row indices (bin indices)
J::Vector{Int} # Column indices (spectrum indices)
V::Vector{Float64} # Values (intensities)
lck::Base.Threads.SpinLock
function SparseAccumulator(capacity_hint::Int=10000)
acc = new(
Vector{Int}(undef, 0),
Vector{Int}(undef, 0),
Vector{Float64}(undef, 0),
Base.Threads.SpinLock()
)
sizehint!(acc.I, capacity_hint)
sizehint!(acc.J, capacity_hint)
sizehint!(acc.V, capacity_hint)
return acc
end
end
"""
accumulate!(acc::SparseAccumulator, spectrum_idx::Int, bin_indices::AbstractVector{Int},
intensities::AbstractVector{Float64})
Appends peak data for one spectrum into the sparse accumulator.
"""
@inline function accumulate!(acc::SparseAccumulator, spectrum_idx::Int,
bin_indices::AbstractVector{Int},
intensities::AbstractVector{Float64})
n = length(bin_indices)
for k in 1:n
@inbounds begin
push!(acc.I, bin_indices[k])
push!(acc.J, spectrum_idx)
push!(acc.V, intensities[k])
end
end
end
# =============================================================================
# The Pipeline Executor
# =============================================================================
"""
process_dataset!(data::MSIData, config::PipelineConfig;
progress_callback::Union{Function, Nothing}=nothing,
masked_indices::Union{AbstractVector{Int}, Nothing}=nothing)
The Sprint 2 master streaming function. Processes an entire MSI dataset through
a kernel chain without holding more than 1 spectrum per thread in RAM.
# Returns
- `SparseMatrixCSC{Float64, Int}`: The feature matrix (bins × spectra)
- `Vector{Float64}`: The m/z bin centers
# Architecture
1. Ensures analytics are computed (for global m/z range)
2. Creates thread-local SparseAccumulators
3. Streams spectra via `_iterate_spectra_fast`
4. Per spectrum: copy view → kernel chain → peak detect → bin → accumulate
5. Merges accumulators → `sparse(I, J, V)`
"""
function process_dataset!(data::MSIData, config::PipelineConfig;
progress_callback::Union{Function, Nothing}=nothing,
masked_indices::Union{AbstractVector{Int}, Nothing}=nothing)
# --- Step 1: Ensure analytics are computed (provides global m/z range) ---
if !is_set(data.analytics_ready)
println("Pre-computing analytics for streaming pipeline...")
precompute_analytics(data)
end
# Determine global m/z range for binning
global_min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0)
global_max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0)
if !isfinite(global_min_mz) || !isfinite(global_max_mz) || global_min_mz >= global_max_mz
@warn "Invalid global m/z range: [$global_min_mz, $global_max_mz]. Cannot bin peaks."
return spzeros(0, 0), Float64[]
end
num_bins = config.num_bins
bin_edges = range(global_min_mz, stop=global_max_mz, length=num_bins + 1)
bin_centers = [(bin_edges[i] + bin_edges[i+1]) / 2 for i in 1:num_bins]
inv_bin_width = 1.0 / step(bin_edges)
num_spectra = length(data.spectra_metadata)
indices_to_process = masked_indices === nothing ? nothing : masked_indices
# --- Step 2: Create thread-local accumulators ---
# `maxthreadid()` also covers the interactive thread pool.
n_threads = max(1, Base.Threads.maxthreadid())
accumulators = [SparseAccumulator(num_spectra * 10) for _ in 1:n_threads]
spectra_processed = Base.Threads.Atomic{Int}(0)
# NEW: Create dedicated workspace buffers for each thread.
# This completely eliminates the need for acquire/release and prevents deadlocks.
workspaces_mz = [Vector{Float64}(undef, 0) for _ in 1:n_threads]
workspaces_int = [Vector{Float64}(undef, 0) for _ in 1:n_threads]
workspaces_scratch = [Vector{Float64}(undef, 0) for _ in 1:n_threads]
# Pre-parse step configuration for fast dispatch in the hot loop
has_smoothing = false
has_baseline = false
has_normalization = false
has_transform = false
has_peak_picking = false
has_calibration = false
smooth_params = Dict{Symbol, Any}()
baseline_params = Dict{Symbol, Any}()
norm_params = Dict{Symbol, Any}()
transform_params = Dict{Symbol, Any}()
peak_params = Dict{Symbol, Any}()
for s in config.steps
if s.name === :smoothing
has_smoothing = true
smooth_params = s.params
elseif s.name === :baseline_correction
has_baseline = true
baseline_params = s.params
elseif s.name === :normalization
has_normalization = true
norm_params = s.params
elseif s.name === :stabilization || s.name === :intensity_transformation
has_transform = true
transform_params = s.params
elseif s.name === :peak_picking
has_peak_picking = true
peak_params = s.params
elseif s.name === :calibration
has_calibration = true
end
end
reference_masses = config.reference_peaks
# --- Step 3: Stream and process ---
start_time = time_ns()
# Use let block to capture all variables cleanly for the closure
let data=data, accumulators=accumulators, spectra_processed=spectra_processed,
bin_edges=bin_edges, num_bins=num_bins, inv_bin_width=inv_bin_width,
global_min_mz=global_min_mz,
workspaces_mz=workspaces_mz, workspaces_int=workspaces_int, workspaces_scratch=workspaces_scratch,
has_smoothing=has_smoothing, has_baseline=has_baseline,
has_normalization=has_normalization, has_transform=has_transform,
has_peak_picking=has_peak_picking, has_calibration=has_calibration,
smooth_params=smooth_params, baseline_params=baseline_params,
norm_params=norm_params, transform_params=transform_params,
peak_params=peak_params, reference_masses=reference_masses
_iterate_spectra_fast(data, indices_to_process) do idx, mz_view, int_view
thread_id = Base.Threads.threadid()
acc = accumulators[thread_id]
# --- Grab Thread-Local Workspaces ---
# No locking, no blocking, guaranteed to be available
mz_buf = workspaces_mz[thread_id]
int_buf = workspaces_int[thread_id]
scratch_buf = workspaces_scratch[thread_id]
resize!(mz_buf, length(mz_view))
resize!(int_buf, length(int_view))
resize!(scratch_buf, length(int_view))
copyto!(mz_buf, mz_view)
copyto!(int_buf, int_view)
# --- Kernel Chain (in pipeline order) ---
# Category B: Fixed-reference calibration
if has_calibration && !isempty(reference_masses)
calibrate_inplace!(mz_buf, int_buf, reference_masses)
end
# Category A: Intensity transformation
if has_transform
transform_inplace!(int_buf, get(transform_params, :method, :sqrt))
end
# Category A: Smoothing
if has_smoothing
smooth_inplace!(int_buf, scratch_buf, data;
method=get(smooth_params, :method, :savitzky_golay),
window=get(smooth_params, :window, 9),
order=get(smooth_params, :order, 2))
end
# Category A: Baseline correction
if has_baseline
baseline_subtract_inplace!(int_buf, scratch_buf, data;
method=get(baseline_params, :method, :snip),
iterations=get(baseline_params, :iterations, 100),
window=get(baseline_params, :window, 20))
end
# Category A: Normalization
if has_normalization
normalize_inplace!(int_buf, get(norm_params, :method, :tic))
end
# --- Peak Detection & Binning ---
if has_peak_picking
detect_peaks_streaming(mz_buf, int_buf, scratch_buf;
method=get(peak_params, :method, :profile),
snr_threshold=Float64(get(peak_params, :snr_threshold, 3.0)),
half_window=Int(get(peak_params, :half_window, 10)),
min_peak_prominence=Float64(get(peak_params, :min_peak_prominence, 0.1)),
merge_peaks_tolerance=Float64(get(peak_params, :merge_peaks_tolerance, 0.002))) do peak_mz, peak_int
# Bin each discovered peak directly
bin_idx = trunc(Int, (peak_mz - global_min_mz) * inv_bin_width) + 1
bin_idx = clamp(bin_idx, 1, num_bins)
push!(acc.I, bin_idx)
push!(acc.J, idx)
push!(acc.V, peak_int)
end
else
# No peak picking: bin raw intensity directly
@inbounds for i in eachindex(mz_buf)
bin_idx = trunc(Int, (mz_buf[i] - global_min_mz) * inv_bin_width) + 1
bin_idx = clamp(bin_idx, 1, num_bins)
push!(acc.I, bin_idx)
push!(acc.J, idx)
push!(acc.V, int_buf[i])
end
end
Base.Threads.atomic_add!(spectra_processed, 1)
end
end
# --- Step 4: Merge thread-local accumulators ---
total_entries = sum(length(acc.I) for acc in accumulators)
merged_I = Vector{Int}(undef, total_entries)
merged_J = Vector{Int}(undef, total_entries)
merged_V = Vector{Float64}(undef, total_entries)
offset = 0
for acc in accumulators
n = length(acc.I)
if n > 0
copyto!(merged_I, offset + 1, acc.I, 1, n)
copyto!(merged_J, offset + 1, acc.J, 1, n)
copyto!(merged_V, offset + 1, acc.V, 1, n)
offset += n
end
end
# --- Step 5: Assemble sparse matrix ---
# Use max combiner: when multiple peaks map to the same bin for same spectrum,
# keep the maximum intensity
feature_matrix = sparse(merged_I, merged_J, merged_V, num_bins, num_spectra, max)
# --- Step 6: Apply frequency threshold if configured ---
if config.frequency_threshold > 0.0
# Count how many spectra have a non-zero value in each bin
bin_presence = vec(sum(feature_matrix .> 0, dims=2))
min_count = ceil(Int, config.frequency_threshold * num_spectra)
keep_bins = findall(bin_presence .>= min_count)
feature_matrix = feature_matrix[keep_bins, :]
bin_centers = bin_centers[keep_bins]
end
duration = (time_ns() - start_time) / 1e9
n_processed = spectra_processed[]
n_nonzeros = nnz(feature_matrix)
sparsity = 1.0 - n_nonzeros / (size(feature_matrix, 1) * size(feature_matrix, 2) + 1)
@printf "Streaming pipeline complete: %d spectra processed in %.2f seconds.\n" n_processed duration
@printf "Feature matrix: %d bins × %d spectra, %d non-zeros (%.1f%% sparse)\n" size(feature_matrix, 1) size(feature_matrix, 2) n_nonzeros sparsity * 100
@printf "RAM: %.1f MB (vs %.1f MB dense)\n" (n_nonzeros * 16) / 1e6 (size(feature_matrix, 1) * size(feature_matrix, 2) * 8) / 1e6
if progress_callback !== nothing
progress_callback(1.0)
end
return feature_matrix, collect(Float64, bin_centers)
end
"""
save_sparse_matrix(matrix::SparseMatrixCSC, output_path::String)
Exports a highly optimized SparseMatrixCSC array to disk using the standard
Matrix Market Coordinate format (`.mtx`), guaranteeing no bottleneck or OOM crashes
for extremely large MS dataset persistence.
"""
function save_sparse_matrix(matrix::SparseMatrixCSC{Float64, Int}, output_path::String)
m, n = size(matrix)
nnz_val = nnz(matrix)
# Use streaming I/O with a large buffer for ultra-fast persistence
open(output_path, "w") do io
# Write Matrix Market Header
write(io, "%%MatrixMarket matrix coordinate real general\n")
write(io, "$m $n $nnz_val\n")
# Directly extract CSC properties (O(1) memory, zero allocation)
row_indices = rowvals(matrix)
values_array = nonzeros(matrix)
@inbounds for filter_j in 1:n
# nzrange returns the index bounds for non-zero elements in column 'j'
for idx in nzrange(matrix, filter_j)
i = row_indices[idx]
v = values_array[idx]
write(io, "$i $filter_j $v\n")
end
end
end
end
+1355
View File
File diff suppressed because it is too large Load Diff
+499
View File
@@ -0,0 +1,499 @@
# src/mzML.jl
# This file is responsible for parsing metadata from .mzML files.
# It has been refactored to produce a unified MSIData object.
# Constants for CV parameter accessions - defined once for performance
const MZ_AXIS_ACCESSION = "MS:1000514"
const INTENSITY_AXIS_ACCESSION = "MS:1000515"
const COMPRESSION_ACCESSION = "MS:1000574"
const NO_COMPRESSION_ACCESSION = "MS:1000576"
# Data format accessions as constants
const DATA_FORMAT_ACCESSIONS = Dict{String, DataType}(
"MS:1000518" => Int16,
"MS:1000519" => Int32,
"MS:1000520" => Float64,
"MS:1000521" => Float32,
"MS:1000522" => Int64,
"MS:1000523" => Float64
)
"""
parse_instrument_metadata_mzml(stream::IO)
Parses instrument metadata from an mzML file.
# Arguments
- `stream::IO`: The stream to parse the metadata from.
# Returns
- `InstrumentMetadata`: The instrument metadata.
# Example
```julia
parse_instrument_metadata_mzml(open("test.mzML"))
```
"""
function parse_instrument_metadata_mzml(stream::IO)
println("DEBUG: Starting mzML instrument metadata parsing...")
# Initialize with default values from the InstrumentMetadata constructor
instrument_meta = InstrumentMetadata()
# Create temporary variables to hold parsed values
resolution = instrument_meta.resolution
instrument_model = instrument_meta.instrument_model
mass_accuracy_ppm = instrument_meta.mass_accuracy_ppm
polarity = instrument_meta.polarity
calibration_status = instrument_meta.calibration_status
laser_settings = Dict{String, Any}() # Use Any for heterogeneous values
vendor_preprocessing_steps = String[] # Initialize vendor_preprocessing_steps
try
# Reset stream and read a sufficiently large header block to find metadata.
seekstart(stream)
header_block = ""
header_read_limit = 50000 # Read up to 50KB of header
bytes_read = 0
while !eof(stream) && bytes_read < header_read_limit
line_pos = position(stream)
line = readline(stream)
bytes_read += (position(stream) - line_pos)
# Stop at the start of the main data section
if occursin("<run>", line) || occursin("<spectrumList>", line)
break
end
header_block *= line * "\n"
end
header_io = IOBuffer(header_block)
while !eof(header_io)
line = readline(header_io)
if occursin("<cvParam", line)
accession_match = get_attribute(line, "accession")
value_match = get_attribute(line, "value")
name_match = get_attribute(line, "name") # For laser attributes and vendor_preprocessing names
if accession_match !== nothing
acc = accession_match.captures[1]
val = (value_match !== nothing) ? value_match.captures[1] : ""
name = (name_match !== nothing) ? name_match.captures[1] : "" # NEW: Get name for logging
if acc == "MS:1000031" # instrument model
instrument_model = val
#println("DEBUG: Instrument model: $instrument_model")
elseif acc == "MS:1001496" # mass resolving power (more specific)
resolution = tryparse(Float64, val)
#println("DEBUG: Resolution (specific): $resolution")
elseif acc == "MS:1000011" && resolution === nothing # resolution (less specific)
resolution = tryparse(Float64, val)
#println("DEBUG: Resolution (less specific): $resolution")
elseif acc == "MS:1000016" # mass accuracy (ppm)
mass_accuracy_ppm = tryparse(Float64, val)
#println("DEBUG: Mass accuracy (ppm): $mass_accuracy_ppm")
elseif acc == "MS:1000130" # positive scan
polarity = :positive
#println("DEBUG: Polarity: positive")
elseif acc == "MS:1000129" # negative scan
polarity = :negative
#println("DEBUG: Polarity: negative")
elseif acc == "MS:1000592" # external calibration
calibration_status = :external
#println("DEBUG: Calibration status: external")
elseif acc == "MS:1000593" # internal calibration
calibration_status = :internal
#println("DEBUG: Calibration status: internal")
elseif acc == "MS:1000747" && calibration_status == :uncalibrated # instrument specific calibration
calibration_status = :internal # Assume as a form of internal calibration
#println("DEBUG: Calibration status: instrument specific (internal)")
elseif acc == "MS:1000867" # laser wavelength
laser_settings["wavelength_nm"] = tryparse(Float64, val)
#println("DEBUG: Laser wavelength: $(laser_settings["wavelength_nm"]) nm")
elseif acc == "MS:1000868" # laser fluence
laser_settings["fluence"] = tryparse(Float64, val)
#println("DEBUG: Laser fluence: $(laser_settings["fluence"])")
elseif acc == "MS:1000869" # laser repetition rate
laser_settings["repetition_rate_hz"] = tryparse(Float64, val)
#println("DEBUG: Laser repetition rate: $(laser_settings["repetition_rate_hz"]) Hz")
# NEW: Vendor Preprocessing terms
elseif acc == "MS:1000579" # baseline correction
push!(vendor_preprocessing_steps, "Baseline Correction")
#println("DEBUG: Vendor preprocessing step: Baseline Correction")
elseif acc == "MS:1000580" # smoothing
push!(vendor_preprocessing_steps, "Smoothing")
#println("DEBUG: Vendor preprocessing step: Smoothing")
elseif acc == "MS:1000578" # data transformation (e.g., centroiding)
push!(vendor_preprocessing_steps, "Data Transformation: $(name)")
#println("DEBUG: Vendor preprocessing step: Data Transformation: $(name)")
elseif acc == "MS:1000800" # deisotoping
push!(vendor_preprocessing_steps, "Deisotoping")
#println("DEBUG: Vendor preprocessing step: Deisotoping")
end
end
end
end
catch e
@warn "Could not fully parse instrument metadata from mzML header. Using defaults. Error: $e"
end
println("DEBUG: Finished mzML instrument metadata parsing.")
# Always return a valid object
return InstrumentMetadata(
resolution,
instrument_meta.acquisition_mode, # To be determined by load_mzml_lazy
instrument_meta.mz_axis_type,
calibration_status,
instrument_model,
mass_accuracy_ppm,
isempty(laser_settings) ? nothing : laser_settings,
polarity,
isempty(vendor_preprocessing_steps) ? nothing : vendor_preprocessing_steps # NEW field
)
end
"""
get_spectrum_asset_metadata(stream::IO)
Parses a `<binaryDataArray>` block within an mzML file to extract metadata
for a single data array (e.g., m/z or intensity). It reads CV parameters to
determine the data type, compression, and axis type.
# Arguments
- `stream`: An IO stream positioned at the beginning of a `<binaryDataArray>` block.
# Returns
- A `SpectrumAsset` struct containing the parsed metadata, including the binary
data offset, encoded length, format, and compression status.
"""
function get_spectrum_asset_metadata(stream::IO)
start_pos = position(stream)
#println("DEBUG: Entering get_spectrum_asset_metadata to parse binaryDataArray...")
bda_tag = find_tag(stream, r"<binaryDataArray\s+encodedLength=\"(\d+)\"")
if bda_tag === nothing
throw(FileFormatError("Cannot find binaryDataArray"))
end
encoded_length = parse(Int32, bda_tag.captures[1])
#println("DEBUG: Encoded length: $encoded_length")
# Initialize parameters as separate variables with concrete types
data_format::DataType = Float64
compression_flag::Bool = false
axis::Symbol = :mz
while !eof(stream)
line = readline(stream)
if occursin("</binaryDataArray>", line)
break
end
if occursin("<cvParam", line)
accession = get_attribute(line, "accession")
if accession === nothing
continue
end
acc_str = accession.captures[1]
# Use constant comparisons and dictionary lookup for better performance
if acc_str == MZ_AXIS_ACCESSION
axis = :mz
#println("DEBUG: Axis type identified as: m/z")
elseif acc_str == INTENSITY_AXIS_ACCESSION
axis = :intensity
#println("DEBUG: Axis type identified as: intensity")
elseif haskey(DATA_FORMAT_ACCESSIONS, acc_str)
data_format = DATA_FORMAT_ACCESSIONS[acc_str]
#println("DEBUG: Data format identified as: $data_format")
elseif acc_str == COMPRESSION_ACCESSION
compression_flag = true
#println("DEBUG: Compression: true")
elseif acc_str == NO_COMPRESSION_ACCESSION
compression_flag = false
#println("DEBUG: Compression: false")
end
end
end
seek(stream, start_pos)
readuntil(stream, "<binary>")
binary_offset = position(stream)
#println("DEBUG: Binary data offset: $binary_offset")
# Move stream to the end of the binary data array for the next iteration
readuntil(stream, "</binaryDataArray>")
#println("DEBUG: Exiting get_spectrum_asset_metadata.")
# Create SpectrumAsset directly from the variables
return SpectrumAsset(data_format, compression_flag, binary_offset, encoded_length, axis, 0.0, 0.0)
end
# This function is updated to return the generic SpectrumMetadata struct
"""
parse_spectrum_metadata(stream::IO, offset::Int64)
Parses an entire `<spectrum>` block from an mzML file, given a starting offset.
It extracts the spectrum ID and calls `get_spectrum_asset_metadata` to parse
the m/z and intensity array metadata.
# Arguments
- `stream`: An IO stream for the mzML file.
- `offset`: The byte offset where the `<spectrum>` block begins.
# Returns
- A `SpectrumMetadata` struct containing the parsed metadata for one spectrum.
"""
function parse_spectrum_metadata(stream::IO, offset::Int64)
seek(stream, offset)
# Read the whole spectrum block to parse mode
spectrum_start_pos = position(stream)
line = ""
spectrum_buffer = IOBuffer()
while !eof(stream)
line = readline(stream)
write(spectrum_buffer, line)
if occursin("</spectrum>", line)
break
end
end
spectrum_xml = String(take!(spectrum_buffer))
seek(stream, spectrum_start_pos) # Reset for other parsing
id_match = match(r"<spectrum\s+index=\"\d+\"\s+id=\"([^\"]+)", spectrum_xml)
id = id_match === nothing ? "" : id_match.captures[1]
#println("DEBUG: Parsing spectrum ID: $id")
# Determine mode from the XML block
mode = UNKNOWN
if occursin("MS:1000127", spectrum_xml)
mode = CENTROID
#println("DEBUG: Spectrum mode: CENTROID")
elseif occursin("MS:1000128", spectrum_xml)
mode = PROFILE
#println("DEBUG: Spectrum mode: PROFILE")
end
# Find where the binary data list starts to parse assets
binary_list_match = findfirst("<binaryDataArrayList", spectrum_xml)
if binary_list_match !== nothing
seek(stream, spectrum_start_pos + binary_list_match.start - 1)
end
asset1 = get_spectrum_asset_metadata(stream)
asset2 = get_spectrum_asset_metadata(stream)
# Determine which asset is m/z and which is intensity
mz_asset, int_asset = if asset1.axis_type == :mz
(asset1, asset2)
else
(asset2, asset1)
end
#println("DEBUG: m/z Asset - Format: $(mz_asset.format), Compressed: $(mz_asset.is_compressed), Offset: $(mz_asset.offset), Encoded Length: $(mz_asset.encoded_length)")
#println("DEBUG: Intensity Asset - Format: $(int_asset.format), Compressed: $(int_asset.is_compressed), Offset: $(int_asset.offset), Encoded Length: $(int_asset.encoded_length)")
#println("DEBUG: Finished parsing spectrum ID: $id metadata.")
# Create the new unified metadata object
# For mzML, x and y coordinates are not applicable, so we use 0.
return SpectrumMetadata(Int32(0), Int32(0), id, :sample, mode, mz_asset, int_asset)
end
"""
parse_offset_list(stream::IO)
Parses the `<index name="spectrum">` block in an indexed mzML file to extract
the byte offsets for each spectrum.
# Arguments
- `stream`: An IO stream positioned at the start of the `<index>` block.
# Returns
- A `Vector{Int64}` containing the byte offsets for all spectra.
"""
function parse_offset_list(stream::IO)
offsets = Int64[]
offset_regex = r"<offset[^>]*>(\d+)</offset>"
# Actively search for offset tags, ignoring other lines until the end of the index is found.
while !eof(stream)
line = readline(stream)
# First, check for the end condition.
if occursin("</index>", line) || occursin("</indexedmzML>", line)
break
end
# If it's not the end, see if it's an offset tag.
m = match(offset_regex, line)
if m !== nothing
push!(offsets, parse(Int64, m.captures[1]))
end
# If it's neither, ignore the line and continue the loop.
end
return offsets
end
"""
find_index_offset(stream::IO)::Int64
Finds the index offset in an mzML file by reading from the end.
Optimized version with better buffer management.
# Arguments
- `stream::IO`: The stream to parse the metadata from.
# Returns
- `Int64`: The index offset.
# Example
```julia
find_index_offset(open("test.mzML"))
```
"""
function find_index_offset(stream::IO)::Int64
file_size = filesize(stream)
seekend(stream)
# Read larger chunk for better chance of finding the offset
chunk_size = min(8192, file_size)
seek(stream, file_size - chunk_size)
footer = read(stream, String)
index_offset_match = match(r"<indexListOffset>(\d+)</indexListOffset>", footer)
if index_offset_match === nothing
throw(FileFormatError("Could not find <indexListOffset>. File may not be an indexed mzML."))
end
return parse(Int64, index_offset_match.captures[1])
end
# This is the main lazy-loading function for mzML, now returning an MSIData object.
"""
load_mzml_lazy(file_path::String; cache_size::Int=100)
Lazily loads an indexed `.mzML` file by parsing only the metadata. It reads the
spectrum index from the end of the file to get the offsets of each spectrum,
then parses the metadata for each spectrum without loading the binary data.
# Arguments
- `file_path`: The path to the `.mzML` file.
- `cache_size`: The number of spectra to hold in an LRU cache for faster access.
# Returns
- An `MSIData` object ready for lazy data access.
"""
function load_mzml_lazy(file_path::String; cache_size::Int=100)
println("DEBUG: Opening file stream for $file_path")
# --- Handle Pool Optimization ---
# Open multiple handles to the .mzML file to avoid lock contention
num_handles = max(1, Threads.maxthreadid())
mzml_handles = [open(file_path, "r") for _ in 1:num_handles]
# Use the first handle for initial parsing
primary_handle = mzml_handles[1]
try
# --- NEW: Parse instrument metadata from header ---
println("DEBUG: Parsing instrument metadata from header...")
instrument_meta = parse_instrument_metadata_mzml(primary_handle)
seekstart(primary_handle) # Reset stream after header parsing
println("DEBUG: Finding index offset...")
index_offset = find_index_offset(primary_handle)
# --- NEW: Mmap Optimization with RAM Safety ---
mmap_data = nothing
try
file_size = filesize(file_path)
println("DEBUG: Memory mapping .mzML file...")
seekstart(primary_handle) # Anchor Mmap to the beginning of the file to prevent overflow
mmap_data = Mmap.mmap(primary_handle, Vector{UInt8}, (file_size,))
println("DEBUG: .mzML file mmapped successfully.")
catch e
@warn "Memory mapping failed for mzML, falling back to standard I/O: $e"
end
println("DEBUG: Seeking to index list at offset $index_offset.")
seek(primary_handle, index_offset)
println("DEBUG: Searching for '<index name=\"spectrum\">'.")
if find_tag(primary_handle, r"<index\s+name=\"spectrum\"") === nothing
throw(FileFormatError("Could not find spectrum index."))
end
println("DEBUG: Parsing spectrum offsets...")
spectrum_offsets = parse_offset_list(primary_handle)
if isempty(spectrum_offsets)
throw(FileFormatError("No spectrum offsets found."))
end
num_spectra = length(spectrum_offsets)
println("DEBUG: Found $num_spectra spectrum offsets.")
println("DEBUG: Parsing metadata for each spectrum...")
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
@inbounds for i in 1:num_spectra
spectra_metadata[i] = parse_spectrum_metadata(primary_handle, spectrum_offsets[i])
if i % 1000 == 0
println("DEBUG: Processed $i/$num_spectra spectra")
end
end
println("DEBUG: Metadata parsing complete for all $num_spectra spectra.")
# Inferred global formats from first spectrum
first_meta = spectra_metadata[1]
mz_format = first_meta.mz_asset.format
intensity_format = first_meta.int_asset.format
# Determine overall acquisition mode ...
num_centroid = count(m -> m.mode == CENTROID, spectra_metadata)
num_profile = count(m -> m.mode == PROFILE, spectra_metadata)
acq_mode_symbol = if num_centroid > 0 && num_profile == 0
:centroid
elseif num_profile > 0 && num_centroid == 0
:profile
elseif num_centroid > 0 && num_profile > 0
:mixed
else
:unknown
end
final_instrument_meta = InstrumentMetadata(
instrument_meta.resolution,
acq_mode_symbol,
instrument_meta.mz_axis_type,
instrument_meta.calibration_status,
instrument_meta.instrument_model,
instrument_meta.mass_accuracy_ppm,
instrument_meta.laser_settings,
instrument_meta.polarity,
instrument_meta.vendor_preprocessing_steps
)
source = MzMLSource(mzml_handles, mz_format, intensity_format, mmap_data)
println("DEBUG: Creating MSIData object.")
return MSIData(source, spectra_metadata, final_instrument_meta, (0, 0), nothing, cache_size)
catch e
# Close all handles in the pool if initialization fails
for h in mzml_handles
isopen(h) && close(h)
end
rethrow(e)
end
end
-56783
View File
File diff suppressed because it is too large Load Diff