diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..cbe9c40 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +.git +.gitignore +.dockerignore +datos_para_ai +outputs +models.zip +figures +venv +*.pdf +*.aux +*.bbl +*.blg +*.log +*.out +*.toc diff --git a/.gitignore b/.gitignore index 5141580..11764f8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,11 @@ data/Leaf.imzML data/Leaf.ibd data/Leaf.imzML.cache JuliaMSI/ -environment/Manifest.toml +# environment/Manifest.toml is intentionally tracked (reproducible Julia lock) datos_para_ai/* +outputs/ +venv/ +.ipynb_checkpoints/ # LaTeX build files *.aux diff --git a/Dockerfile b/Dockerfile index 03ae171..73e4afc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,9 +18,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && 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.3") # ============================================================ -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.3-linux-x86_64.tar.gz \ | tar -xz -C /usr/local --strip-components=1 # ============================================================ diff --git a/Dockerfile.cpu b/Dockerfile.cpu new file mode 100644 index 0000000..ca264da --- /dev/null +++ b/Dockerfile.cpu @@ -0,0 +1,54 @@ +FROM 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.3") +# ============================================================ +RUN curl -fsSL https://julialang-s3.julialang.org/bin/linux/x64/1.11/julia-1.11.3-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 +# ============================================================ +RUN julia --project=/app/environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate(); Pkg.precompile()' + +# ============================================================ +# 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"] diff --git a/Makefile b/Makefile index 3232f84..92bfc75 100644 --- a/Makefile +++ b/Makefile @@ -47,32 +47,32 @@ pipeline: step1: # Julia preprocessing @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 \ - /app/scripts/julia/julia_msi_bridge.jl /app/datasets/$(D) $(D) + /app/scripts_julia/julia_msi_bridge.jl /app/datos_para_ai/$(D) $(D) step2: # SimCLR training @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 @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 @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 @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 @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 @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 \ - /app/scripts/julia/plot_mass_spectra.jl $(D) + /app/scripts_julia/plot_mass_spectra.jl $(D) /app/datos_para_ai/$(D) # ============================================================ # Plots @@ -80,7 +80,7 @@ step7: # Mass spectra plot-spectra: @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 \ - /app/scripts/julia/plot_mass_spectra.jl $(D) + /app/scripts_julia/plot_mass_spectra.jl $(D) /app/datos_para_ai/$(D) # ============================================================ # Cleanup (outputs only; datasets are symlinked and never removed) diff --git a/README.md b/README.md index b0da686..a32e1b8 100644 --- a/README.md +++ b/README.md @@ -6,142 +6,207 @@ 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 into spatially coherent metabolic domains. -This repository is the self-contained, reproducible home of the manuscript -*"A scalable deep learning workflow for mass spectrometry imaging"* — the manuscript -(`MSI_julia-python_mapping.md`), all of its figures, the pinned environment, and the -pipeline that produces every result are here. It ships the **renderable manuscript and its -figures**, plus all seven pipeline stages. +This repository accompanies the manuscript *"A scalable deep learning workflow for mass +spectrometry imaging"* (`MSI_julia-python_mapping.md`). It is self-contained: it ships the +manuscript and figures, the pinned environments, the full seven-stage pipeline, and a +**vendored copy of the JuliaMSI engine** (`src/`, MIT) so no external Julia project is +required. Raw MSI datasets are supplied by the user (see [Datasets](#datasets)). -> This clone is a **standalone repository**: the raw MSI datasets are supplied by the user -> (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 +## Repository layout ``` -msi-julia-python-cnn/ -├── README.md # this document -├── LICENSE # MIT -├── 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) -├── docker-compose.yml # msi-pipeline-gpu / msi-pipeline-cpu services +. +├── README.md +├── MSI_julia-python_mapping.md # manuscript (pandoc/biblatex, references zotero.bib) +├── zotero.bib # manuscript bibliography +├── documentation.md # technical rationale, hyperparameters, validation +├── figure1.png figure2.png figure3.png figure4.png +├── Dockerfile # GPU image (CUDA 12.4 + Julia + Python/SimCLR) +├── Dockerfile.cpu # CPU image (Ubuntu 22.04 + Julia + Python/SimCLR) +├── docker-compose.yml # msi-pipeline-gpu / msi-pipeline-cpu services ├── .dockerignore -├── .gitignore -├── environment/ # pinned dependencies -│ ├── Project.toml # Julia package set (incl. julia_mzML_imzML engine) -│ ├── Manifest.toml # locked Julia environment (julia 1.12.6) -│ └── requirements.txt # Python deps (torch, sklearn, Pillow, …) -├── src/ -│ └── MSI_src.jl # core Julia engine module (memory-mapped imzML, TrIQ, slices) -├── scripts/ -│ ├── setup_datasets.sh # add a new imzML dataset via symlinks -│ ├── julia/ -│ │ ├── julia_msi_bridge.jl # Stage 1: preprocess + PNG export (grayscale + viridis) -│ │ ├── plot_mass_spectra.jl # Stage 7: mean + per-cluster spectra -│ │ └── 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 -│ ├── 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) -│ ├── quantitative_validation.py# Stage 5: isotope colocalization, PCA baseline, ARI -│ ├── visualize_clusters.py # Stage 6: per-cluster galleries -│ ├── plot_mass_spectra_python.py # Stage 7 Python fallback -│ ├── make_ion_carpet.py # standalone ion-carpet exporter (manuscript figures) -│ └── (test_grouping, verify_coherence, guided_vascular) # dev/analysis helpers -├── datasets/ # user-provided data (see Datasets below) -│ ├── datasets.csv # registry of the 7 manuscript datasets (+ mask flags) -│ ├── Datura_leaf/ Datura_root/ San_pedro/ -│ └── Mouse_bladder/ Mouse_Liver/ Mouse_Stomach/ Human_colon/ -└── outputs/ # generated (git-ignored): ion images, models, figures +├── Makefile # build/run + step1..step7 targets (Docker) +├── run_full_pipeline.sh # single entry point: 7 stages (one or many datasets) +├── environment/ # pinned dependencies +│ ├── Project.toml # Julia package set +│ ├── Manifest.toml # locked Julia environment (julia 1.11.3) +│ └── requirements.txt # Python deps (torch, sklearn, Pillow, …) +├── src/ # vendored JuliaMSI engine (MIT) — see below +│ └── MSI_src.jl + 14 modules # memory-mapped imzML, TrIQ, slicing, masks +├── scripts_julia/ +│ ├── julia_msi_bridge.jl # Stage 1: preprocess + PNG export (grayscale + viridis) +│ ├── plot_mass_spectra.jl # Stage 7: mean + per-cluster spectra +│ └── graph_cluster_spectra.jl # dev helper (spectrum figure with cluster mapping) +├── scripts_python/ +│ ├── CNN_proof_1.py # Stage 2: SimCLR contrastive training +│ ├── evaluate_clustering.py # Stage 3: K sweep (2..20, 3 metrics) +│ ├── graph_tsne_msi.py # Stage 4: t-SNE + K-Means +│ ├── quantitative_validation.py # Stage 5: isotope co-localization, PCA baseline, ARI +│ ├── visualize_clusters.py # Stage 6: per-cluster galleries +│ ├── plot_mass_spectra_python.py # Stage 7 Python fallback +│ ├── msi_preprocess_python.py # Stage 1 Python fallback (vendor imzML) +│ ├── make_ion_carpet.py # standalone ion-carpet mosaics (manuscript figures) +│ └── build_manuscript_figures.py # composite figure panels +├── datos_para_ai/ # user-provided datasets (git-ignored) +└── outputs/ # generated (git-ignored): ion images, models, figures ``` ## The seven pipeline stages | 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) | -| 2 | `scripts/python/CNN_proof_1.py` | grayscale PNGs → SimCLR 4-layer GroupNorm encoder → 128-dim latents (`outputs/models//`) | -| 3 | `scripts/python/evaluate_clustering.py` | latents → K sweep k=2..20 (Silhouette, Davies-Bouldin, Calinski-Harabasz) → best K | -| 4 | `scripts/python/graph_tsne_msi.py ` | latents → t-SNE colored by K-Means (best K) | -| 5 | `scripts/python/quantitative_validation.py ` | latents → isotope co-localization, PCA baseline, ARI stability | -| 6 | `scripts/python/visualize_clusters.py ` | clusters → representative ion-image galleries per cluster | -| 7 | `scripts/julia/plot_mass_spectra.jl ` (Python fallback) | spectra → mean spectrum + per-cluster annotated spectra | -| — | `scripts/python/make_ion_carpet.py [--clusters]` (standalone) | Stage-1 viridis corpus → full-dataset & per-cluster ion-carpet mosaics (manuscript Fig. carpet / carpet-root) | +| 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//`) | +| 3 | `scripts_python/evaluate_clustering.py` | latents → K sweep k=2..20 (Silhouette, Davies-Bouldin, Calinski-Harabasz) → best K (`outputs//best_k_results.csv`) | +| 4 | `scripts_python/graph_tsne_msi.py ` | latents → t-SNE colored by K-Means | +| 5 | `scripts_python/quantitative_validation.py ` | latents → isotope co-localization, PCA baseline, ARI stability | +| 6 | `scripts_python/visualize_clusters.py ` | clusters → representative ion-image galleries per cluster | +| 7 | `scripts_julia/plot_mass_spectra.jl [data_dir]` (fallback: `plot_mass_spectra_python.py`) | spectra → mean + per-cluster annotated spectra | +| — | `scripts_python/make_ion_carpet.py [--clusters]` (standalone) | Stage-1 viridis corpus → full-dataset & per-cluster ion-carpet mosaics | -## Run - -### Native (venv + system Julia) +## Quick start (Docker, recommended) ```bash -# one-time setup: Python environment with pinned deps +# 1) build the GPU image (use `make build-cpu` for the CPU image) +make build + +# 2) put each dataset in its own folder, e.g. +# datos_para_ai/Datura_leaf/.imzML (+ .ibd, optional ROI .png) + +# 3) run +make run # every dataset under datos_para_ai/ +make run-dataset D=Datura_leaf # a single dataset +``` + +Equivalent raw Docker, if you prefer not to use `make`: + +```bash +docker build -t msi-pipeline-gpu . +docker run --gpus all --shm-size=2g -it \ + -v "$PWD/datos_para_ai:/app/datos_para_ai" \ + -v "$PWD/outputs:/app/outputs" \ + msi-pipeline-gpu bash + +# then, inside the container: +bash run_full_pipeline.sh # all datasets under datos_para_ai/ +bash run_full_pipeline.sh Datura_leaf # a single dataset +``` + +For CPU-only machines, build `Dockerfile.cpu` (`make build-cpu`) and drop `--gpus all`. +In VS Code the bundled `.devcontainer/` builds the GPU image with the right flags. + +## Native run (venv + system Julia) + +```bash +# one-time setup 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) -bash run_full_pipeline.sh # all 7 manuscript datasets -bash run_full_pipeline.sh Datura_leaf # single dataset - -# optional: regenerate the ion-carpet mosaics after Stage 1 -venv/bin/python scripts/python/make_ion_carpet.py Datura_leaf --clusters +# run everything, or a single dataset +bash run_full_pipeline.sh +bash run_full_pipeline.sh Datura_leaf ``` -`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 -make build # GPU image (NVIDIA Container Toolkit required to run) -make build-cpu # CPU-only image -make run # full pipeline on all datasets -make run-dataset D=Datura_leaf -make step1..step7 D=... # re-run a single stage (steps 4–5 need K=) +julia --threads auto --project=environment scripts_julia/julia_msi_bridge.jl datos_para_ai/ +python scripts_python/CNN_proof_1.py +python scripts_python/evaluate_clustering.py # writes outputs//best_k_results.csv +python scripts_python/graph_tsne_msi.py +python scripts_python/quantitative_validation.py +python scripts_python/visualize_clusters.py +julia --project=environment scripts_julia/plot_mass_spectra.jl datos_para_ai/ ``` -### Add a custom dataset - -```bash -bash scripts/setup_datasets.sh /path/to/your_data.imzML my_dataset -``` +Docker equivalents: `make step1 D=` … `make step7 D=`, with +`make step4 D= K=5` and `make step5 D= K=5`. Stages 4–5 need the cluster +count `K`; Stage 3 prints and stores the best value (Silhouette optimum by default). ## Datasets -All seven benchmark datasets are **public** and listed in `datasets/datasets.csv` -(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). Access -instructions: **TODO — add accession DOI/URL per dataset**. Download each raw -imzML/ibd pair and place it (or symlink it) into `datasets//`, matching the -`imzml_file` column. ROI masks (`region_of_interest.png` / `region_of_interest_.png`) -are already expected there for the masked datasets (all except San Pedro). +The pipeline reads **any valid imzML** (profile or centroid) — it is **not** restricted to +the manuscript datasets. For each dataset create `datos_para_ai//` containing: + +- exactly one `.imzML` file, and +- its sibling `.ibd` binary (the imzML references the `.ibd` by basename, so both must sit + in the same folder). + +The folder name becomes the dataset name used throughout `outputs/`. + +**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. + +The seven manuscript 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). Access instructions: **TODO — add accession DOI/URL +per dataset**. Related dataset DOIs are listed in `DOIs.md` (e.g. San Pedro cactus +; general imzML test data +). + +`models.zip` contains the trained SimCLR encoders for the seven manuscript datasets. +Unzip it into `outputs/` (`unzip models.zip -d outputs/`) to reuse +`outputs/models//msi_encoder_trained.pth` and skip Stage 2 for those datasets. + +## 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: + +- (upstream) +- +- +- + +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` | `datos_para_ai` | override the dataset root directory | +| `MSI_K` | auto | force a cluster count instead of the Stage-3 Silhouette choice | ## Prerequisites -- **Julia 1.12.x** (instantiate against `environment/`; first run resolves the depot) -- **Python 3.10+** (`environment/requirements.txt`; torch builds for your GPU/CPU) -- Optional: **Docker 24+** with NVIDIA Container Toolkit for the GPU image - -Pipeline configuration knobs (see `run_full_pipeline.sh`): `MSI_PEAK_FRAC`, -`MSI_PEAK_MIN_MZ_GAP`, `MSI_BIN_AVG`, `MSI_MEM_MAX` (cgroup memory ceiling). +- **Julia 1.11.x** — instantiate against `environment/Manifest.toml`. +- **Python 3.10+** — `environment/requirements.txt` (torch builds for your GPU/CPU). +- 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. ## Manuscript figures -The manuscript (`MSI_julia-python_mapping.md`, biblatex bibliography `zotero.bib`) +The manuscript (`MSI_julia-python_mapping.md`, biblatex bibliography `zotero.bib`) is +accompanied by composite panels: ``` -figure1.png # JuliaMSI vs Cardinal vs MALDIquant: slice throughput + peak load RAM, red X on failed MALDIquant runs (Fig. \ref{fig:benchmark}) -figure2.png # K-sweep clustering validation for the Datura leaf + root demonstration datasets (Fig. \ref{fig:clustering}) -figure3.png # t-SNE + biologically interpretable ion galleries, mouse bladder over human colon (Fig. \ref{fig:tsne_clusters}) +figure1.png # JuliaMSI vs Cardinal vs MALDIquant: throughput + RAM (Fig. benchmark) +figure2.png # K-sweep clustering validation for the Datura leaf + root datasets +figure3.png # t-SNE + biologically interpretable ion galleries +figure4.png # additional composite panel ``` -The three manuscript figures are composite panels assembled by -`scripts/python/build_manuscript_figures.py` from the per-dataset outputs of the pipeline -(`outputs//msi_tsne_plot.png`, `outputs//figures/cluster_validation_detailed_plot.png`, -`outputs//galleries/`, and the benchmark CSV under `Benchmark_recommendation/results/`). -Re-run that script after any pipeline or benchmark change to regenerate them. \ No newline at end of file +They are assembled by `scripts_python/build_manuscript_figures.py` from per-dataset +outputs (`outputs//msi_tsne_plot.png`, +`outputs//figures/cluster_validation_detailed_plot.png`, `outputs//galleries/`). +Re-run that script after any pipeline change to regenerate them. + +## License + +MIT — see `LICENSE`. The vendored `src/` retains its own MIT license (`src/LICENSE`). diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..4597da4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,29 @@ +services: + msi-pipeline-gpu: + build: + context: . + dockerfile: Dockerfile + image: msi-pipeline-gpu + working_dir: /app + shm_size: "2gb" + volumes: + - ./datos_para_ai:/app/datos_para_ai + - ./outputs:/app/outputs + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + + msi-pipeline-cpu: + build: + context: . + dockerfile: Dockerfile.cpu + image: msi-pipeline-cpu + working_dir: /app + shm_size: "2gb" + volumes: + - ./datos_para_ai:/app/datos_para_ai + - ./outputs:/app/outputs diff --git a/environment/Manifest.toml b/environment/Manifest.toml new file mode 100644 index 0000000..cdfba11 --- /dev/null +++ b/environment/Manifest.toml @@ -0,0 +1,3072 @@ +# This file is machine-generated - editing it directly is not advised + +julia_version = "1.11.3" +manifest_format = "2.0" +project_hash = "76cbec1aac4016ed87eedf9fd86c6d8f60db717a" + +[[deps.ANSIColoredPrinters]] +git-tree-sha1 = "574baf8110975760d391c710b6341da1afa48d8c" +uuid = "a4c015fc-c6ff-483c-b24f-f7ea428134e9" +version = "0.0.1" + +[[deps.ATK_jll]] +deps = ["Artifacts", "Glib_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c0a10eaf3a7e1e909ef8fe45971a73524bfce1bf" +uuid = "7b86fcea-f67b-53e1-809c-8f1719c154e8" +version = "2.38.1+0" + +[[deps.AbstractFFTs]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef" +uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c" +version = "1.5.0" +weakdeps = ["ChainRulesCore", "Test"] + + [deps.AbstractFFTs.extensions] + AbstractFFTsChainRulesCoreExt = "ChainRulesCore" + AbstractFFTsTestExt = "Test" + +[[deps.AbstractTrees]] +git-tree-sha1 = "2d9c9a55f9c93e8887ad391fbae72f8ef55e1177" +uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" +version = "0.4.5" + +[[deps.Accessors]] +deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"] +git-tree-sha1 = "2eeb2c9bef11013efc6f8f97f32ee59b146b09fb" +uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697" +version = "0.1.44" + + [deps.Accessors.extensions] + AxisKeysExt = "AxisKeys" + IntervalSetsExt = "IntervalSets" + LinearAlgebraExt = "LinearAlgebra" + StaticArraysExt = "StaticArrays" + StructArraysExt = "StructArrays" + TestExt = "Test" + UnitfulExt = "Unitful" + + [deps.Accessors.weakdeps] + AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" + Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.Adapt]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "28e1637322d4019ed2577cbec9268fab9b7da117" +uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" +version = "4.6.0" +weakdeps = ["SparseArrays", "StaticArrays"] + + [deps.Adapt.extensions] + AdaptSparseArraysExt = "SparseArrays" + AdaptStaticArraysExt = "StaticArrays" + +[[deps.AdaptivePredicates]] +git-tree-sha1 = "7e651ea8d262d2d74ce75fdf47c4d63c07dba7a6" +uuid = "35492f91-a3bd-45ad-95db-fcad7dcfedb7" +version = "1.2.0" + +[[deps.AliasTables]] +deps = ["PtrArrays", "Random"] +git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff" +uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8" +version = "1.1.3" + +[[deps.Animations]] +deps = ["Colors"] +git-tree-sha1 = "e092fa223bf66a3c41f9c022bd074d916dc303e7" +uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340" +version = "0.4.2" + +[[deps.ArgParse]] +deps = ["Logging", "TextWrap"] +git-tree-sha1 = "22cf435ac22956a7b45b0168abbc871176e7eecc" +uuid = "c7e460c6-2fb9-53a9-8c5b-16f535851c63" +version = "1.2.0" + +[[deps.ArgTools]] +uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" +version = "1.1.2" + +[[deps.ArnoldiMethod]] +deps = ["LinearAlgebra", "Random", "StaticArrays"] +git-tree-sha1 = "d57bd3762d308bded22c3b82d033bff85f6195c6" +uuid = "ec485272-7323-5ecc-a04f-4719b315124d" +version = "0.4.0" + +[[deps.ArrayInterface]] +deps = ["Adapt", "LinearAlgebra"] +git-tree-sha1 = "3d0cabd25fab32390e3bcb82cd67e700aebd9816" +uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9" +version = "7.25.0" + + [deps.ArrayInterface.extensions] + ArrayInterfaceAMDGPUExt = "AMDGPU" + ArrayInterfaceBandedMatricesExt = "BandedMatrices" + ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices" + ArrayInterfaceCUDAExt = "CUDA" + ArrayInterfaceCUDSSExt = ["CUDSS", "CUDA"] + ArrayInterfaceChainRulesCoreExt = "ChainRulesCore" + ArrayInterfaceChainRulesExt = "ChainRules" + ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore" + ArrayInterfaceMetalExt = "Metal" + ArrayInterfaceReverseDiffExt = "ReverseDiff" + ArrayInterfaceSparseArraysExt = "SparseArrays" + ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore" + ArrayInterfaceTrackerExt = "Tracker" + + [deps.ArrayInterface.weakdeps] + AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" + BandedMatrices = "aae01518-5342-5314-be14-df237901396f" + BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0" + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e" + ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2" + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" + Metal = "dde4c033-4e86-420c-a63e-0dd931031962" + ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" + Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c" + +[[deps.Artifacts]] +uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" +version = "1.11.0" + +[[deps.Automa]] +deps = ["PrecompileTools", "SIMD", "TranscodingStreams"] +git-tree-sha1 = "a8f503e8e1a5f583fbef15a8440c8c7e32185df2" +uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b" +version = "1.1.0" + +[[deps.AxisAlgorithms]] +deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"] +git-tree-sha1 = "01b8ccb13d68535d73d2b0c23e39bd23155fb712" +uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950" +version = "1.1.0" + +[[deps.AxisArrays]] +deps = ["Dates", "IntervalSets", "IterTools", "RangeArrays"] +git-tree-sha1 = "4126b08903b777c88edf1754288144a0492c05ad" +uuid = "39de3d68-74b9-583c-8d2d-e117c070f3a9" +version = "0.4.8" + +[[deps.Base64]] +uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" +version = "1.11.0" + +[[deps.BaseDirs]] +git-tree-sha1 = "bca794632b8a9bbe159d56bf9e31c422671b35e0" +uuid = "18cc8868-cbac-4acf-b575-c8ff214dc66f" +version = "1.3.2" + +[[deps.BenchmarkTools]] +deps = ["Compat", "JSON", "Logging", "PrecompileTools", "Printf", "Profile", "Statistics", "UUIDs"] +git-tree-sha1 = "9670d3febc2b6da60a0ae57846ba74670290653f" +uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" +version = "1.8.0" + +[[deps.Bessels]] +git-tree-sha1 = "4435559dc39793d53a9e3d278e185e920b4619ef" +uuid = "0e736298-9ec6-45e8-9647-e4fc86a2fe38" +version = "0.2.8" + +[[deps.BitFlags]] +git-tree-sha1 = "bbe1079eecf9c9fbb52765193ad2bae27ae09bc8" +uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35" +version = "0.1.10" + +[[deps.BitTwiddlingConvenienceFunctions]] +deps = ["Static"] +git-tree-sha1 = "f21cfd4950cb9f0587d5067e69405ad2acd27b87" +uuid = "62783981-4cbd-42fc-bca8-16325de8dc4b" +version = "0.1.6" + +[[deps.BufferedStreams]] +git-tree-sha1 = "6863c5b7fc997eadcabdbaf6c5f201dc30032643" +uuid = "e1450e63-4bb3-523b-b2a4-4ffa8c0fd77d" +version = "1.2.2" + +[[deps.Bzip2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1b96ea4a01afe0ea4090c5c8039690672dd13f2e" +uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0" +version = "1.0.9+0" + +[[deps.CEnum]] +git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc" +uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" +version = "0.5.0" + +[[deps.CPUSummary]] +deps = ["CpuId", "IfElse", "PrecompileTools", "Preferences", "Static"] +git-tree-sha1 = "f3a21d7fc84ba618a779d1ed2fcca2e682865bab" +uuid = "2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9" +version = "0.2.7" + +[[deps.CRC32c]] +uuid = "8bf52ea8-c179-5cab-976a-9e18b702a9bc" +version = "1.11.0" + +[[deps.CRlibm]] +deps = ["CRlibm_jll"] +git-tree-sha1 = "66188d9d103b92b6cd705214242e27f5737a1e5e" +uuid = "96374032-68de-5a5b-8d9e-752f78720389" +version = "1.0.2" + +[[deps.CRlibm_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "e329286945d0cfc04456972ea732551869af1cfc" +uuid = "4e9b3aee-d8a1-5a3d-ad8b-7d824db253f0" +version = "1.0.1+0" + +[[deps.CSV]] +deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "PrecompileTools", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings", "WorkerUtilities"] +git-tree-sha1 = "8d8e0b0f350b8e1c91420b5e64e5de774c2f0f4d" +uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" +version = "0.10.16" + +[[deps.Cairo]] +deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"] +git-tree-sha1 = "71aa551c5c33f1a4415867fe06b7844faadb0ae9" +uuid = "159f3aea-2a34-519c-b102-8c37f9878175" +version = "1.1.1" + +[[deps.CairoMakie]] +deps = ["CRC32c", "Cairo", "Cairo_jll", "Colors", "FileIO", "FreeType", "GeometryBasics", "LinearAlgebra", "Makie", "PrecompileTools"] +git-tree-sha1 = "1a063740329b7ee9ec602505c41cccb8500b637d" +uuid = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" +version = "0.15.11" + +[[deps.Cairo_jll]] +deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"] +git-tree-sha1 = "1fa950ebc3e37eccd51c6a8fe1f92f7d86263522" +uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a" +version = "1.18.7+0" + +[[deps.CatIndices]] +deps = ["CustomUnitRanges", "OffsetArrays"] +git-tree-sha1 = "a0f80a09780eed9b1d106a1bf62041c2efc995bc" +uuid = "aafaddc9-749c-510e-ac4f-586e18779b91" +version = "0.2.2" + +[[deps.ChainRulesCore]] +deps = ["Compat", "LinearAlgebra"] +git-tree-sha1 = "12177ad6b3cad7fd50c8b3825ce24a99ad61c18f" +uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" +version = "1.26.1" +weakdeps = ["SparseArrays"] + + [deps.ChainRulesCore.extensions] + ChainRulesCoreSparseArraysExt = "SparseArrays" + +[[deps.ChunkCodecCore]] +git-tree-sha1 = "1a3ad7e16a321667698a19e77362b35a1e94c544" +uuid = "0b6fb165-00bc-4d37-ab8b-79f91016dbe1" +version = "1.0.1" + +[[deps.ChunkCodecLibZlib]] +deps = ["ChunkCodecCore", "Zlib_jll"] +git-tree-sha1 = "cee8104904c53d39eb94fd06cbe60cb5acde7177" +uuid = "4c0bbee4-addc-4d73-81a0-b6caacae83c8" +version = "1.0.0" + +[[deps.ChunkCodecLibZstd]] +deps = ["ChunkCodecCore", "Zstd_jll"] +git-tree-sha1 = "34d9873079e4cb3d0c62926a225136824677073f" +uuid = "55437552-ac27-4d47-9aa3-63184e8fd398" +version = "1.0.0" + +[[deps.CloseOpenIntervals]] +deps = ["Static", "StaticArrayInterface"] +git-tree-sha1 = "05ba0d07cd4fd8b7a39541e31a7b0254704ea581" +uuid = "fb6a15b2-703c-40df-9091-08a04967cfa9" +version = "0.1.13" + +[[deps.Clustering]] +deps = ["Distances", "LinearAlgebra", "NearestNeighbors", "Printf", "Random", "SparseArrays", "Statistics", "StatsBase"] +git-tree-sha1 = "3e22db924e2945282e70c33b75d4dde8bfa44c94" +uuid = "aaaa29a8-35af-508c-8bc3-b662a17a0fe5" +version = "0.15.8" + +[[deps.CodeTracking]] +deps = ["InteractiveUtils", "REPL", "UUIDs"] +git-tree-sha1 = "cfb7a2e89e245a9d5016b70323db412b3a7438d5" +uuid = "da1fd8a2-8d9e-5ec2-8556-3022fb5608a2" +version = "3.0.2" + +[[deps.CodecBase]] +deps = ["TranscodingStreams"] +git-tree-sha1 = "40956acdbef3d8c7cc38cba42b56034af8f8581a" +uuid = "6c391c72-fb7b-5838-ba82-7cfb1bcfecbf" +version = "0.3.4" + +[[deps.CodecZlib]] +deps = ["TranscodingStreams", "Zlib_jll"] +git-tree-sha1 = "962834c22b66e32aa10f7611c08c8ca4e20749a9" +uuid = "944b1d66-785c-5afd-91f1-9de20f533193" +version = "0.7.8" + +[[deps.CodecZstd]] +deps = ["TranscodingStreams", "Zstd_jll"] +git-tree-sha1 = "da54a6cd93c54950c15adf1d336cfd7d71f51a56" +uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2" +version = "0.8.7" + +[[deps.ColorBrewer]] +deps = ["Colors", "JSON"] +git-tree-sha1 = "07da79661b919001e6863b81fc572497daa58349" +uuid = "a2cac450-b92f-5266-8821-25eda20663c8" +version = "0.4.2" + +[[deps.ColorSchemes]] +deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"] +git-tree-sha1 = "b0fd3f56fa442f81e0a47815c92245acfaaa4e34" +uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" +version = "3.31.0" + +[[deps.ColorTypes]] +deps = ["FixedPointNumbers", "Random"] +git-tree-sha1 = "67e11ee83a43eb71ddc950302c53bf33f0690dfe" +uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" +version = "0.12.1" +weakdeps = ["StyledStrings"] + + [deps.ColorTypes.extensions] + StyledStringsExt = "StyledStrings" + +[[deps.ColorVectorSpace]] +deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"] +git-tree-sha1 = "8b3b6f87ce8f65a2b4f857528fd8d70086cd72b1" +uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" +version = "0.11.0" +weakdeps = ["SpecialFunctions"] + + [deps.ColorVectorSpace.extensions] + SpecialFunctionsExt = "SpecialFunctions" + +[[deps.Colors]] +deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] +git-tree-sha1 = "37ea44092930b1811e666c3bc38065d7d87fcc74" +uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" +version = "0.13.1" + +[[deps.CommonMark]] +deps = ["PrecompileTools"] +git-tree-sha1 = "731edf630eb23140a3c7a2e74d4186f562996d76" +uuid = "a80b9123-70ca-4bc0-993e-6e3bcb318db6" +version = "1.0.2" +weakdeps = ["Markdown", "MarkdownAST"] + + [deps.CommonMark.extensions] + CommonMarkMarkdownASTExt = "MarkdownAST" + CommonMarkMarkdownExt = "Markdown" + +[[deps.CommonWorldInvalidations]] +git-tree-sha1 = "ae52d1c52048455e85a387fbee9be553ec2b68d0" +uuid = "f70d9fcc-98c5-4d4a-abd7-e4cdeebd8ca8" +version = "1.0.0" + +[[deps.Compat]] +deps = ["TOML", "UUIDs"] +git-tree-sha1 = "9d8a54ce4b17aa5bdce0ea5c34bc5e7c340d16ad" +uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" +version = "4.18.1" +weakdeps = ["Dates", "LinearAlgebra"] + + [deps.Compat.extensions] + CompatLinearAlgebraExt = "LinearAlgebra" + +[[deps.Compiler]] +git-tree-sha1 = "382d79bfe72a406294faca39ef0c3cef6e6ce1f1" +uuid = "807dbc54-b67e-4c79-8afb-eafe4df6f2e1" +version = "0.1.1" + +[[deps.CompilerSupportLibraries_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" +version = "1.1.1+0" + +[[deps.CompositionsBase]] +git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad" +uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b" +version = "0.1.2" +weakdeps = ["InverseFunctions"] + + [deps.CompositionsBase.extensions] + CompositionsBaseInverseFunctionsExt = "InverseFunctions" + +[[deps.ComputationalResources]] +git-tree-sha1 = "52cb3ec90e8a8bea0e62e275ba577ad0f74821f7" +uuid = "ed09eef8-17a6-5b46-8889-db040fac31e3" +version = "0.3.2" + +[[deps.ComputePipeline]] +deps = ["Observables", "Preferences"] +git-tree-sha1 = "7bc84b769c1d384315e7b5c4ac03a6c303e6cf35" +uuid = "95dc2771-c249-4cd0-9c9f-1f3b4330693c" +version = "0.1.8" + +[[deps.ConcurrentUtilities]] +deps = ["Serialization", "Sockets"] +git-tree-sha1 = "21d088c496ea22914fe80906eb5bce65755e5ec8" +uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb" +version = "2.5.1" + +[[deps.Configurations]] +deps = ["ExproniconLite", "OrderedCollections", "TOML"] +git-tree-sha1 = "4358750bb58a3caefd5f37a4a0c5bfdbbf075252" +uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d" +version = "0.17.6" + +[[deps.ConstructionBase]] +git-tree-sha1 = "b4b092499347b18a015186eae3042f72267106cb" +uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9" +version = "1.6.0" +weakdeps = ["IntervalSets", "LinearAlgebra", "StaticArrays"] + + [deps.ConstructionBase.extensions] + ConstructionBaseIntervalSetsExt = "IntervalSets" + ConstructionBaseLinearAlgebraExt = "LinearAlgebra" + ConstructionBaseStaticArraysExt = "StaticArrays" + +[[deps.ContinuousWavelets]] +deps = ["AbstractFFTs", "Documenter", "FFTW", "Interpolations", "LinearAlgebra", "SpecialFunctions", "Wavelets"] +git-tree-sha1 = "17066a488f55711113968c2844ec4e455151251a" +uuid = "96eb917e-2868-4417-9cb6-27e7ff17528f" +version = "1.1.8" + +[[deps.Contour]] +git-tree-sha1 = "439e35b0b36e2e5881738abc8857bd92ad6ff9a8" +uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" +version = "0.6.3" + +[[deps.ConvexHulls2d]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "cd7759cfeaf855fed46ec26a26fb323ac3a5501e" +uuid = "438b5665-92b0-42e6-bc36-e4ac8449fa2d" +version = "0.1.1" +weakdeps = ["Makie"] + + [deps.ConvexHulls2d.extensions] + ConvexHulls2dMakieExt = "Makie" + +[[deps.CoordinateTransformations]] +deps = ["LinearAlgebra", "StaticArrays"] +git-tree-sha1 = "a692f5e257d332de1e554e4566a4e5a8a72de2b2" +uuid = "150eb455-5306-5404-9cee-2592286d6298" +version = "0.6.4" + +[[deps.CoreMath]] +deps = ["CoreMath_jll"] +git-tree-sha1 = "8c0480f92b1b1796239156a1b9b1bfb1b39499b4" +uuid = "b7a15901-be09-4a0e-87d2-2e66b0e09b5a" +version = "0.1.0" + +[[deps.CoreMath_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "a692a4c1dc59a4b8bc0b6403876eb3250fde2bc3" +uuid = "a38c48d9-6df1-5ac9-9223-b6ada3b5572b" +version = "0.1.0+0" + +[[deps.CpuId]] +deps = ["Markdown"] +git-tree-sha1 = "fcbb72b032692610bfbdb15018ac16a36cf2e406" +uuid = "adafc99b-e345-5852-983c-f28acb93d879" +version = "0.3.1" + +[[deps.Crayons]] +git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15" +uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" +version = "4.1.1" + +[[deps.CustomUnitRanges]] +git-tree-sha1 = "1a3f97f907e6dd8983b744d2642651bb162a3f7a" +uuid = "dc8bdbbb-1ca9-579f-8c36-e416f6a65cce" +version = "1.0.2" + +[[deps.DSP]] +deps = ["Bessels", "FFTW", "IterTools", "LinearAlgebra", "Polynomials", "Random", "Reexport", "SpecialFunctions", "Statistics"] +git-tree-sha1 = "d335b2929e1b6067951a1250df247cc5fab7d40e" +uuid = "717857b8-e6f2-59f4-9121-6e50c889abd2" +version = "0.8.5" +weakdeps = ["OffsetArrays"] + + [deps.DSP.extensions] + OffsetArraysExt = "OffsetArrays" + +[[deps.DataAPI]] +git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe" +uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" +version = "1.16.0" + +[[deps.DataFrames]] +deps = ["Compat", "DataAPI", "DataStructures", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrecompileTools", "PrettyTables", "Printf", "Random", "Reexport", "SentinelArrays", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] +git-tree-sha1 = "5fab31e2e01e70ad66e3e24c968c264d1cf166d6" +uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" +version = "1.8.2" + +[[deps.DataStructures]] +deps = ["Compat", "InteractiveUtils", "OrderedCollections"] +git-tree-sha1 = "4e1fe97fdaed23e9dc21d4d664bea76b65fc50a0" +uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" +version = "0.18.22" + +[[deps.DataValueInterfaces]] +git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" +uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" +version = "1.0.0" + +[[deps.Dates]] +deps = ["Printf"] +uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" +version = "1.11.0" + +[[deps.Dbus_jll]] +deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "473e9afc9cf30814eb67ffa5f2db7df82c3ad9fd" +uuid = "ee1fde0b-3d02-5ea6-8484-8dfef6360eab" +version = "1.16.2+0" + +[[deps.DelaunayTriangulation]] +deps = ["AdaptivePredicates", "EnumX", "ExactPredicates", "Random"] +git-tree-sha1 = "c55f5a9fd67bdbc8e089b5a3111fe4292986a8e8" +uuid = "927a84f5-c5f4-47a5-9785-b46e178433df" +version = "1.6.6" + +[[deps.DelimitedFiles]] +deps = ["Mmap"] +git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae" +uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" +version = "1.9.1" + +[[deps.Distances]] +deps = ["LinearAlgebra", "Statistics", "StatsAPI"] +git-tree-sha1 = "c7e3a542b999843086e2f29dac96a618c105be1d" +uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" +version = "0.10.12" +weakdeps = ["ChainRulesCore", "SparseArrays"] + + [deps.Distances.extensions] + DistancesChainRulesCoreExt = "ChainRulesCore" + DistancesSparseArraysExt = "SparseArrays" + +[[deps.Distributed]] +deps = ["Random", "Serialization", "Sockets"] +uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" +version = "1.11.0" + +[[deps.Distributions]] +deps = ["AliasTables", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns"] +git-tree-sha1 = "e421c1938fafab0165b04dc1a9dbe2a26272952c" +uuid = "31c24e10-a181-5473-b8eb-7969acd0382f" +version = "0.25.125" + + [deps.Distributions.extensions] + DistributionsChainRulesCoreExt = "ChainRulesCore" + DistributionsDensityInterfaceExt = "DensityInterface" + DistributionsTestExt = "Test" + + [deps.Distributions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + DensityInterface = "b429d917-457f-4dbc-8f4c-0cc954292b1d" + Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[[deps.DocStringExtensions]] +git-tree-sha1 = "7442a5dfe1ebb773c29cc2962a8980f47221d76c" +uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" +version = "0.9.5" + +[[deps.Documenter]] +deps = ["ANSIColoredPrinters", "AbstractTrees", "Base64", "CodecZlib", "Dates", "DocStringExtensions", "Downloads", "Git", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "MarkdownAST", "Pkg", "PrecompileTools", "REPL", "RegistryInstances", "SHA", "TOML", "Test", "Unicode"] +git-tree-sha1 = "56e9c37b5e7c3b4f080ab1da18d72d5c290e184a" +uuid = "e30172f5-a6a5-5a46-863b-614d45cd2de4" +version = "1.17.0" + +[[deps.DotEnv]] +deps = ["PrecompileTools"] +git-tree-sha1 = "92e88cb68a5b10545234f46dfaeb2fa8a8a50c45" +uuid = "4dc1fcf4-5e3b-5448-94ab-0c38ec0385c1" +version = "1.0.0" + +[[deps.Downloads]] +deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] +uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" +version = "1.6.0" + +[[deps.EarCut_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "e3290f2d49e661fbd94046d7e3726ffcb2d41053" +uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5" +version = "2.2.4+0" + +[[deps.EnumX]] +git-tree-sha1 = "c49898e8438c828577f04b92fc9368c388ac783c" +uuid = "4e289a0a-7415-4d19-859d-a7e5c4648b56" +version = "1.0.7" + +[[deps.EpollShim_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "8a4be429317c42cfae6a7fc03c31bad1970c310d" +uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43" +version = "0.0.20230411+1" + +[[deps.ExactPredicates]] +deps = ["IntervalArithmetic", "Random", "StaticArrays"] +git-tree-sha1 = "83231673ea4d3d6008ac74dc5079e77ab2209d8f" +uuid = "429591f6-91af-11e9-00e2-59fbe8cec110" +version = "2.2.9" + +[[deps.ExceptionUnwrapping]] +deps = ["Test"] +git-tree-sha1 = "d36f682e590a83d63d1c7dbd287573764682d12a" +uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4" +version = "0.1.11" + +[[deps.Expat_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c307cd83373868391f3ac30b41530bc5d5d05d08" +uuid = "2e619515-83b5-522b-bb60-26c02a35a201" +version = "2.8.1+0" + +[[deps.ExproniconLite]] +git-tree-sha1 = "c13f0b150373771b0fdc1713c97860f8df12e6c2" +uuid = "55351af7-c7e9-48d6-89ff-24e801d99491" +version = "0.10.14" + +[[deps.Extents]] +git-tree-sha1 = "b309b36a9e02fe7be71270dd8c0fd873625332b4" +uuid = "411431e0-e8b7-467b-b5e0-f676ba4f2910" +version = "0.1.6" + +[[deps.EzXML]] +deps = ["Printf", "XML2_jll"] +git-tree-sha1 = "7ea1aa5869e2626ccae84480e4f37185bc6f41d3" +uuid = "8f5d6c58-4d21-5cfd-889c-e3ad7ee6a615" +version = "1.2.3" + +[[deps.FFMPEG]] +deps = ["FFMPEG_jll"] +git-tree-sha1 = "95ecf07c2eea562b5adbd0696af6db62c0f52560" +uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a" +version = "0.4.5" + +[[deps.FFMPEG_jll]] +deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libva_jll", "libvorbis_jll", "x264_jll", "x265_jll"] +git-tree-sha1 = "cac41ca6b2d399adfc95e51240566f8a60a80806" +uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5" +version = "8.1.0+0" + +[[deps.FFTA]] +deps = ["AbstractFFTs", "DocStringExtensions", "LinearAlgebra", "MuladdMacro", "Primes", "Random", "Reexport"] +git-tree-sha1 = "65e55303b72f4a567a51b174dd2c47496efeb95a" +uuid = "b86e33f2-c0db-4aa1-a6e0-ab43e668529e" +version = "0.3.1" + +[[deps.FFTViews]] +deps = ["CustomUnitRanges", "FFTW"] +git-tree-sha1 = "cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2" +uuid = "4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd" +version = "0.3.2" + +[[deps.FFTW]] +deps = ["AbstractFFTs", "FFTW_jll", "Libdl", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"] +git-tree-sha1 = "97f08406df914023af55ade2f843c39e99c5d969" +uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" +version = "1.10.0" + +[[deps.FFTW_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6866aec60ef98e3164cd8d6855225684207e9dff" +uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a" +version = "3.3.12+0" + +[[deps.FileIO]] +deps = ["Pkg", "Requires", "UUIDs"] +git-tree-sha1 = "8e9c059d6857607253e837730dbf780b6b151acd" +uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" +version = "1.19.0" +weakdeps = ["HTTP"] + + [deps.FileIO.extensions] + HTTPExt = "HTTP" + +[[deps.FilePaths]] +deps = ["FilePathsBase", "MacroTools", "Reexport"] +git-tree-sha1 = "a1b2fbfe98503f15b665ed45b3d149e5d8895e4c" +uuid = "8fc22ac5-c921-52a6-82fd-178b2807b824" +version = "0.9.0" +weakdeps = ["Glob", "URIParser", "URIs"] + + [deps.FilePaths.extensions] + FilePathsGlobExt = "Glob" + FilePathsURIParserExt = "URIParser" + FilePathsURIsExt = "URIs" + +[[deps.FilePathsBase]] +deps = ["Compat", "Dates"] +git-tree-sha1 = "3bab2c5aa25e7840a4b065805c0cdfc01f3068d2" +uuid = "48062228-2e41-5def-b9a4-89aafe57970f" +version = "0.9.24" +weakdeps = ["Mmap", "Test"] + + [deps.FilePathsBase.extensions] + FilePathsBaseMmapExt = "Mmap" + FilePathsBaseTestExt = "Test" + +[[deps.FileWatching]] +uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" +version = "1.11.0" + +[[deps.FillArrays]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "2f979084d1e13948a3352cf64a25df6bd3b4dca3" +uuid = "1a297f60-69ca-5386-bcde-b61e274b549b" +version = "1.16.0" +weakdeps = ["PDMats", "SparseArrays", "StaticArrays", "Statistics"] + + [deps.FillArrays.extensions] + FillArraysPDMatsExt = "PDMats" + FillArraysSparseArraysExt = "SparseArrays" + FillArraysStaticArraysExt = "StaticArrays" + FillArraysStatisticsExt = "Statistics" + +[[deps.FixedPointNumbers]] +deps = ["Random", "Statistics"] +git-tree-sha1 = "59af96b98217c6ef4ae0dfe065ac7c20831d1a84" +uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" +version = "0.8.6" + +[[deps.Fontconfig_jll]] +deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Zlib_jll"] +git-tree-sha1 = "f85dac9a96a01087df6e3a749840015a0ca3817d" +uuid = "a3f928ae-7b40-5064-980b-68af3947d34b" +version = "2.17.1+0" + +[[deps.Format]] +git-tree-sha1 = "9c68794ef81b08086aeb32eeaf33531668d5f5fc" +uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8" +version = "1.3.7" + +[[deps.FreeType]] +deps = ["CEnum", "FreeType2_jll"] +git-tree-sha1 = "907369da0f8e80728ab49c1c7e09327bf0d6d999" +uuid = "b38be410-82b0-50bf-ab77-7b57e271db43" +version = "4.1.1" + +[[deps.FreeType2_jll]] +deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "70329abc09b886fd2c5d94ad2d9527639c421e3e" +uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7" +version = "2.14.3+1" + +[[deps.FreeTypeAbstraction]] +deps = ["BaseDirs", "ColorVectorSpace", "Colors", "FreeType", "GeometryBasics", "Mmap"] +git-tree-sha1 = "4ebb930ef4a43817991ba35db6317a05e59abd11" +uuid = "663a7486-cb36-511b-a19d-713bb74d65c9" +version = "0.10.8" + +[[deps.FriBidi_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "7a214fdac5ed5f59a22c2d9a885a16da1c74bbc7" +uuid = "559328eb-81f9-559d-9380-de523a88c83c" +version = "1.0.17+0" + +[[deps.Future]] +deps = ["Random"] +uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" +version = "1.11.0" + +[[deps.GLFW]] +deps = ["GLFW_jll"] +git-tree-sha1 = "af06f66cca2b698ab9c482de55977ff8178d025e" +uuid = "f7f18e0c-5ee9-5ccd-a5bf-e8befd85ed98" +version = "3.4.6" + +[[deps.GLFW_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll", "libdecor_jll", "xkbcommon_jll"] +git-tree-sha1 = "9e0fb9e54594c47f278d75063980e43066e26e20" +uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89" +version = "3.4.1+1" + +[[deps.GLMakie]] +deps = ["ColorTypes", "Colors", "FileIO", "FixedPointNumbers", "FreeTypeAbstraction", "GLFW", "GeometryBasics", "LinearAlgebra", "Makie", "Markdown", "MeshIO", "ModernGL", "Observables", "PrecompileTools", "Printf", "ShaderAbstractions", "StaticArrays"] +git-tree-sha1 = "a9964f9ef0b244352e04d30e8c215ec232eee699" +uuid = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a" +version = "0.13.11" + +[[deps.GMP_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "781609d7-10c4-51f6-84f2-b8444358ff6d" +version = "6.3.0+0" + +[[deps.GR]] +deps = ["Artifacts", "Base64", "DelimitedFiles", "Downloads", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Preferences", "Printf", "Qt6Wayland_jll", "Random", "Serialization", "Sockets", "TOML", "Tar", "Test", "p7zip_jll"] +git-tree-sha1 = "44716a1a667cb867ee0e9ec8edc31c3e4aa5afdc" +uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71" +version = "0.73.24" + + [deps.GR.extensions] + IJuliaExt = "IJulia" + + [deps.GR.weakdeps] + IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" + +[[deps.GR_jll]] +deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "FreeType2_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Qt6Base_jll", "Zlib_jll", "libpng_jll"] +git-tree-sha1 = "be8a1b8065959e24fdc1b51402f39f3b6f0f6653" +uuid = "d2c73de3-f751-5644-a686-071e5b155ba9" +version = "0.73.24+0" + +[[deps.GTK3_jll]] +deps = ["ATK_jll", "Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Libepoxy_jll", "Pango_jll", "Pkg", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXcomposite_jll", "Xorg_libXcursor_jll", "Xorg_libXdamage_jll", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll", "Xorg_libXrender_jll", "at_spi2_atk_jll", "gdk_pixbuf_jll", "iso_codes_jll", "xkbcommon_jll"] +git-tree-sha1 = "b080a592525632d287aee4637a62682576b7f5e4" +uuid = "77ec8976-b24b-556a-a1bf-49a033a670a6" +version = "3.24.31+0" + +[[deps.GarishPrint]] +deps = ["Configurations", "Preferences"] +git-tree-sha1 = "41136d24cc02c4d7c2b8c8982823fedac66d0a45" +uuid = "b0ab02a7-8576-43f7-aa76-eaa7c3897c54" +version = "0.5.1" + +[[deps.Genie]] +deps = ["ArgParse", "Base64", "Dates", "Distributed", "DotEnv", "EzXML", "FilePathsBase", "HTTP", "HttpCommon", "Inflector", "JSON", "JuliaFormatter", "Logging", "LoggingExtras", "LoweredCodeUtils", "MIMEs", "Markdown", "Millboard", "Nettle", "OrderedCollections", "Pkg", "REPL", "Random", "Reexport", "Revise", "SHA", "Serialization", "Sockets", "UUIDs", "Unicode", "XML2_jll", "YAML"] +git-tree-sha1 = "a46899376abe9952677f05af653644c87d397fad" +uuid = "c43c736e-a2d1-11e8-161f-af95117fbd1e" +version = "5.35.14" + +[[deps.GenieAutoReload]] +deps = ["Distributed", "Genie", "Logging", "Revise"] +git-tree-sha1 = "d2c018ae2b097631c09a09d9e88cf551e3a378fc" +uuid = "c6228e60-a24f-11e9-1776-c313472ebacc" +version = "2.2.5" + +[[deps.GenieDevTools]] +deps = ["Dates", "Genie", "RemoteREPL", "Revise", "Stipple", "StippleUI", "Tables"] +git-tree-sha1 = "5c84de04cde55e272e760e7ef021bb645f53bd67" +uuid = "4e5d9629-6565-4102-a9ff-45c707eb060e" +version = "2.12.1" + +[[deps.GenieFramework]] +deps = ["GarishPrint", "Genie", "GenieAutoReload", "GenieDevTools", "GeniePackageManager", "Reexport", "Revise", "Stipple", "StipplePivotTable", "StipplePlotly", "StippleTable", "StippleTabs", "StippleUI"] +git-tree-sha1 = "3dcb24f1559dd015e09cb78aa4636b710c60a49e" +uuid = "a59fdf5c-6bf0-4f5d-949c-a137c9e2f353" +version = "3.0.1" + +[[deps.GeniePackageManager]] +deps = ["Base64", "Genie", "Pkg"] +git-tree-sha1 = "3e0a96753f53eab0d15ad837ef1a3742389c928b" +uuid = "3bdcc7f3-4b7d-42a1-be8e-724ecf5e3574" +version = "1.1.0" + +[[deps.GenieSession]] +deps = ["Dates", "Genie", "HTTP", "Logging", "Random", "SHA"] +git-tree-sha1 = "936838b4eccdd5a2b62b695558d5dbc1f5f56560" +uuid = "03cc5b98-4f21-4eb6-99f2-22eced81f962" +version = "1.1.2" + +[[deps.GenieSessionFileSession]] +deps = ["Genie", "GenieSession", "Logging", "Serialization"] +git-tree-sha1 = "5f5ffc33251d0d5f110072f7a0c07717c9453c97" +uuid = "5c4fdc26-39e3-47cf-9034-e533e09961c2" +version = "1.1.0" + +[[deps.GeometryBasics]] +deps = ["EarCut_jll", "Extents", "IterTools", "LinearAlgebra", "PrecompileTools", "Random", "StaticArrays"] +git-tree-sha1 = "1f5a80f4ed9f5a4aada88fc2db456e637676414b" +uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326" +version = "0.5.10" + + [deps.GeometryBasics.extensions] + GeometryBasicsGeoInterfaceExt = "GeoInterface" + + [deps.GeometryBasics.weakdeps] + GeoInterface = "cf35fbd7-0cd7-5166-be24-54bfbe79505f" + +[[deps.GettextRuntime_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll"] +git-tree-sha1 = "45288942190db7c5f760f59c04495064eedf9340" +uuid = "b0724c58-0f36-5564-988d-3bb0596ebc4a" +version = "0.22.4+0" + +[[deps.Ghostscript_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Zlib_jll"] +git-tree-sha1 = "38044a04637976140074d0b0621c1edf0eb531fd" +uuid = "61579ee1-b43e-5ca0-a5da-69d92c66a64b" +version = "9.55.1+0" + +[[deps.Giflib_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6570366d757b50fabae9f4315ad74d2e40c0560a" +uuid = "59f7168a-df46-5410-90c8-f2779963d0ec" +version = "5.2.3+0" + +[[deps.Git]] +deps = ["Git_LFS_jll", "Git_jll", "JLLWrappers", "OpenSSH_jll"] +git-tree-sha1 = "824a1890086880696fc908fe12a17bcf61738bd8" +uuid = "d7ba0133-e1db-5d97-8f8c-041e4b3a1eb2" +version = "1.5.0" + +[[deps.Git_LFS_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "8c66e385d631bb934ff05e76d4a566c640c8df69" +uuid = "020c3dae-16b3-5ae5-87b3-4cb189e250b2" +version = "3.7.1+0" + +[[deps.Git_jll]] +deps = ["Artifacts", "Expat_jll", "JLLWrappers", "LibCURL_jll", "Libdl", "Libiconv_jll", "OpenSSL_jll", "PCRE2_jll", "Zlib_jll"] +git-tree-sha1 = "0dd4cfb426924210c8f42742751cbde74b27bfa3" +uuid = "f8c6e375-362e-5223-8a59-34ff63f689eb" +version = "2.54.0+0" + +[[deps.Glib_jll]] +deps = ["Artifacts", "GettextRuntime_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE2_jll", "Zlib_jll"] +git-tree-sha1 = "24f6def62397474a297bfcec22384101609142ed" +uuid = "7746bdde-850d-59dc-9ae8-88ece973131d" +version = "2.86.3+0" + +[[deps.Glob]] +git-tree-sha1 = "246c628cec062230b7d183aab88841fa94fcabe9" +uuid = "c27321d9-0574-5035-807b-f59d2c89b15c" +version = "1.5.0" + +[[deps.Graphics]] +deps = ["Colors", "LinearAlgebra", "NaNMath"] +git-tree-sha1 = "a641238db938fff9b2f60d08ed9030387daf428c" +uuid = "a2bd30eb-e257-5431-a919-1863eab51364" +version = "1.1.3" + +[[deps.Graphite2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "8a6dbda1fd736d60cc477d99f2e7a042acfa46e8" +uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472" +version = "1.3.15+0" + +[[deps.Graphs]] +deps = ["ArnoldiMethod", "DataStructures", "Distributed", "Inflate", "LinearAlgebra", "Random", "SharedArrays", "SimpleTraits", "SparseArrays", "Statistics"] +git-tree-sha1 = "7a98c6502f4632dbe9fb1973a4244eaa3324e84d" +uuid = "86223c79-3864-5bf0-83f7-82e725a168b6" +version = "1.13.1" + +[[deps.GridLayoutBase]] +deps = ["GeometryBasics", "InteractiveUtils", "Observables"] +git-tree-sha1 = "93d5c27c8de51687a2c70ec0716e6e76f298416f" +uuid = "3955a311-db13-416c-9275-1d80ed98e5e9" +version = "0.11.2" + +[[deps.Grisu]] +git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2" +uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe" +version = "1.0.2" + +[[deps.HTTP]] +deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "PrecompileTools", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"] +git-tree-sha1 = "51059d23c8bb67911a2e6fd5130229113735fc7e" +uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" +version = "1.11.0" + +[[deps.HarfBuzz_jll]] +deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll"] +git-tree-sha1 = "f923f9a774fcf3f5cb761bfa43aeadd689714813" +uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566" +version = "8.5.1+0" + +[[deps.HashArrayMappedTries]] +git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae" +uuid = "076d061b-32b6-4027-95e0-9a2c6f6d7e74" +version = "0.2.0" + +[[deps.HistogramThresholding]] +deps = ["ImageBase", "LinearAlgebra", "MappedArrays"] +git-tree-sha1 = "7194dfbb2f8d945abdaf68fa9480a965d6661e69" +uuid = "2c695a8d-9458-5d45-9878-1b8a99cf7853" +version = "0.3.1" + +[[deps.HostCPUFeatures]] +deps = ["BitTwiddlingConvenienceFunctions", "IfElse", "Libdl", "Preferences", "Static"] +git-tree-sha1 = "af9ab7d1f70739a47f03be78771ebda38c3c71bf" +uuid = "3e5b6fbb-0976-4d2c-9146-d79de83f2fb0" +version = "0.1.18" + +[[deps.HttpCommon]] +deps = ["Dates", "Nullables", "Test", "URIParser"] +git-tree-sha1 = "46313284237aa6ca67a6bce6d6fbd323d19cff59" +uuid = "77172c1b-203f-54ac-aa54-3f1198fe9f90" +version = "0.5.0" + +[[deps.HypergeometricFunctions]] +deps = ["LinearAlgebra", "OpenLibm_jll", "SpecialFunctions"] +git-tree-sha1 = "68c173f4f449de5b438ee67ed0c9c748dc31a2ec" +uuid = "34004b35-14d8-5ef3-9330-4cdb6864b03a" +version = "0.3.28" + +[[deps.IOCapture]] +deps = ["Logging", "Random"] +git-tree-sha1 = "0ee181ec08df7d7c911901ea38baf16f755114dc" +uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89" +version = "1.0.0" + +[[deps.IfElse]] +git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1" +uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173" +version = "0.1.1" + +[[deps.ImageAxes]] +deps = ["AxisArrays", "ImageBase", "ImageCore", "Reexport", "SimpleTraits"] +git-tree-sha1 = "e12629406c6c4442539436581041d372d69c55ba" +uuid = "2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac" +version = "0.6.12" + +[[deps.ImageBase]] +deps = ["ImageCore", "Reexport"] +git-tree-sha1 = "eb49b82c172811fd2c86759fa0553a2221feb909" +uuid = "c817782e-172a-44cc-b673-b171935fbb9e" +version = "0.1.7" + +[[deps.ImageBinarization]] +deps = ["HistogramThresholding", "ImageCore", "LinearAlgebra", "Polynomials", "Reexport", "Statistics"] +git-tree-sha1 = "33485b4e40d1df46c806498c73ea32dc17475c59" +uuid = "cbc4b850-ae4b-5111-9e64-df94c024a13d" +version = "0.3.1" + +[[deps.ImageComponentAnalysis]] +deps = ["AbstractTrees", "ConvexHulls2d", "DataFrames", "DataStructures", "ImageFiltering", "LeftChildRightSiblingTrees", "LinearAlgebra", "OffsetArrays", "Parameters", "StaticArrays"] +git-tree-sha1 = "0f1e954d54bafec3df4aa9d1ce1f110e311a9043" +uuid = "d9b9e9a0-1569-11e9-2cb5-bbca914b0e89" +version = "0.2.2" + +[[deps.ImageContrastAdjustment]] +deps = ["ImageBase", "ImageCore", "ImageTransformations", "Parameters"] +git-tree-sha1 = "4051d637a9536eb9f4aa731b8e2b31d1cd39ae64" +uuid = "f332f351-ec65-5f6a-b3d1-319c6670881a" +version = "0.3.13" + +[[deps.ImageCore]] +deps = ["ColorVectorSpace", "Colors", "FixedPointNumbers", "MappedArrays", "MosaicViews", "OffsetArrays", "PaddedViews", "PrecompileTools", "Reexport"] +git-tree-sha1 = "8c193230235bbcee22c8066b0374f63b5683c2d3" +uuid = "a09fc81d-aa75-5fe9-8630-4744c3626534" +version = "0.10.5" + +[[deps.ImageCorners]] +deps = ["ImageCore", "ImageFiltering", "PrecompileTools", "StaticArrays", "StatsBase"] +git-tree-sha1 = "24c52de051293745a9bad7d73497708954562b79" +uuid = "89d5987c-236e-4e32-acd0-25bd6bd87b70" +version = "0.1.3" + +[[deps.ImageDistances]] +deps = ["Distances", "ImageCore", "ImageMorphology", "LinearAlgebra", "Statistics"] +git-tree-sha1 = "08b0e6354b21ef5dd5e49026028e41831401aca8" +uuid = "51556ac3-7006-55f5-8cb3-34580c88182d" +version = "0.2.17" + +[[deps.ImageFiltering]] +deps = ["CatIndices", "ComputationalResources", "DataStructures", "FFTViews", "FFTW", "ImageBase", "ImageCore", "LinearAlgebra", "OffsetArrays", "PrecompileTools", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "TiledIteration"] +git-tree-sha1 = "52116260a234af5f69969c5286e6a5f8dc3feab8" +uuid = "6a3955dd-da59-5b1f-98d4-e7296123deb5" +version = "0.7.12" + +[[deps.ImageIO]] +deps = ["FileIO", "IndirectArrays", "JpegTurbo", "LazyModules", "Netpbm", "OpenEXR", "PNGFiles", "QOI", "Sixel", "TiffImages", "UUIDs", "WebP"] +git-tree-sha1 = "696144904b76e1ca433b886b4e7edd067d76cbf7" +uuid = "82e4d734-157c-48bb-816b-45c225c6df19" +version = "0.6.9" + +[[deps.ImageMagick]] +deps = ["FileIO", "ImageCore", "ImageMagick_jll", "InteractiveUtils"] +git-tree-sha1 = "8e64ab2f0da7b928c8ae889c514a52741debc1c2" +uuid = "6218d12a-5da1-5696-b52f-db25d2ecc6d1" +version = "1.4.2" + +[[deps.ImageMagick_jll]] +deps = ["Artifacts", "Bzip2_jll", "FFTW_jll", "Ghostscript_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "OpenJpeg_jll", "Zlib_jll", "Zstd_jll", "libpng_jll", "libwebp_jll", "libzip_jll"] +git-tree-sha1 = "61fb149224a297ea6c180d4f77c04fd77304faf0" +uuid = "c73af94c-d91f-53ed-93a7-00f77d67a9d7" +version = "7.1.2023+0" + +[[deps.ImageMetadata]] +deps = ["AxisArrays", "ImageAxes", "ImageBase", "ImageCore"] +git-tree-sha1 = "2a81c3897be6fbcde0802a0ebe6796d0562f63ec" +uuid = "bc367c6b-8a6b-528e-b4bd-a4b897500b49" +version = "0.9.10" + +[[deps.ImageMorphology]] +deps = ["DataStructures", "ImageCore", "LinearAlgebra", "LoopVectorization", "OffsetArrays", "Requires", "TiledIteration"] +git-tree-sha1 = "cffa21df12f00ca1a365eb8ed107614b40e8c6da" +uuid = "787d08f9-d448-5407-9aad-5290dd7ab264" +version = "0.4.6" + +[[deps.ImageQualityIndexes]] +deps = ["ImageContrastAdjustment", "ImageCore", "ImageDistances", "ImageFiltering", "LazyModules", "OffsetArrays", "PrecompileTools", "Statistics"] +git-tree-sha1 = "783b70725ed326340adf225be4889906c96b8fd1" +uuid = "2996bd0c-7a13-11e9-2da2-2f5ce47296a9" +version = "0.3.7" + +[[deps.ImageSegmentation]] +deps = ["Clustering", "DataStructures", "Distances", "Graphs", "ImageCore", "ImageFiltering", "ImageMorphology", "LinearAlgebra", "MetaGraphs", "RegionTrees", "SimpleWeightedGraphs", "StaticArrays", "Statistics"] +git-tree-sha1 = "7196039573b6f312864547eb7a74360d6c0ab8e6" +uuid = "80713f31-8817-5129-9cf8-209ff8fb23e1" +version = "1.9.0" + +[[deps.ImageShow]] +deps = ["Base64", "ColorSchemes", "FileIO", "ImageBase", "ImageCore", "OffsetArrays", "StackViews"] +git-tree-sha1 = "3b5344bcdbdc11ad58f3b1956709b5b9345355de" +uuid = "4e3cecfd-b093-5904-9786-8bbb286a6a31" +version = "0.3.8" + +[[deps.ImageTransformations]] +deps = ["AxisAlgorithms", "CoordinateTransformations", "ImageBase", "ImageCore", "Interpolations", "OffsetArrays", "Rotations", "StaticArrays"] +git-tree-sha1 = "dfde81fafbe5d6516fb864dc79362c5c6b973c82" +uuid = "02fcd773-0e25-5acc-982a-7f6622650795" +version = "0.10.2" + +[[deps.Images]] +deps = ["Base64", "FileIO", "Graphics", "ImageAxes", "ImageBase", "ImageBinarization", "ImageContrastAdjustment", "ImageCore", "ImageCorners", "ImageDistances", "ImageFiltering", "ImageIO", "ImageMagick", "ImageMetadata", "ImageMorphology", "ImageQualityIndexes", "ImageSegmentation", "ImageShow", "ImageTransformations", "IndirectArrays", "IntegralArrays", "Random", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "TiledIteration"] +git-tree-sha1 = "a49b96fd4a8d1a9a718dfd9cde34c154fc84fcd5" +uuid = "916415d5-f1e6-5110-898d-aaa5f9f070e0" +version = "0.26.2" + +[[deps.Imath_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "dcc8d0cd653e55213df9b75ebc6fe4a8d3254c65" +uuid = "905a6f67-0a94-5f89-b386-d35d92009cd1" +version = "3.2.2+0" + +[[deps.IndirectArrays]] +git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f" +uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959" +version = "1.0.0" + +[[deps.Inflate]] +git-tree-sha1 = "d1b1b796e47d94588b3757fe84fbf65a5ec4a80d" +uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9" +version = "0.1.5" + +[[deps.Inflector]] +deps = ["Unicode"] +git-tree-sha1 = "c82a172a07c94887709e613cc67cec0b472fb742" +uuid = "6d011eab-0732-4556-8808-e463c76bf3b6" +version = "1.1.0" + +[[deps.InlineStrings]] +git-tree-sha1 = "8f3d257792a522b4601c24a577954b0a8cd7334d" +uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" +version = "1.4.5" + + [deps.InlineStrings.extensions] + ArrowTypesExt = "ArrowTypes" + ParsersExt = "Parsers" + + [deps.InlineStrings.weakdeps] + ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" + Parsers = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" + +[[deps.IntegerMathUtils]] +git-tree-sha1 = "4c1acff2dc6b6967e7e750633c50bc3b8d83e617" +uuid = "18e54dd8-cb9d-406c-a71d-865a43cbb235" +version = "0.1.3" + +[[deps.IntegralArrays]] +deps = ["ColorTypes", "FixedPointNumbers", "IntervalSets"] +git-tree-sha1 = "b842cbff3f44804a84fda409745cc8f04c029a20" +uuid = "1d092043-8f09-5a30-832f-7509e371ab51" +version = "0.1.6" + +[[deps.IntelOpenMP_jll]] +deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl"] +git-tree-sha1 = "ec1debd61c300961f98064cfb21287613ad7f303" +uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0" +version = "2025.2.0+0" + +[[deps.InteractiveUtils]] +deps = ["Markdown"] +uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" +version = "1.11.0" + +[[deps.Interpolations]] +deps = ["Adapt", "AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"] +git-tree-sha1 = "65d505fa4c0d7072990d659ef3fc086eb6da8208" +uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" +version = "0.16.2" + + [deps.Interpolations.extensions] + InterpolationsForwardDiffExt = "ForwardDiff" + InterpolationsUnitfulExt = "Unitful" + + [deps.Interpolations.weakdeps] + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.IntervalArithmetic]] +deps = ["CRlibm", "CoreMath", "MacroTools", "OpenBLASConsistentFPCSR_jll", "Printf", "Random", "RoundingEmulator"] +git-tree-sha1 = "921d7e91687e15a2c7c269c226960491fc041832" +uuid = "d1acc4aa-44c8-5952-acd4-ba5d80a2a253" +version = "1.0.9" + + [deps.IntervalArithmetic.extensions] + IntervalArithmeticArblibExt = "Arblib" + IntervalArithmeticDiffRulesExt = "DiffRules" + IntervalArithmeticForwardDiffExt = "ForwardDiff" + IntervalArithmeticIntervalSetsExt = "IntervalSets" + IntervalArithmeticIrrationalConstantsExt = "IrrationalConstants" + IntervalArithmeticLinearAlgebraExt = "LinearAlgebra" + IntervalArithmeticRecipesBaseExt = "RecipesBase" + IntervalArithmeticSparseArraysExt = "SparseArrays" + + [deps.IntervalArithmetic.weakdeps] + Arblib = "fb37089c-8514-4489-9461-98f9c8763369" + DiffRules = "b552c78f-8df3-52c6-915a-8e097449b14b" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + IrrationalConstants = "92d709cd-6900-40b7-9082-c6be49f344b6" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + RecipesBase = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + +[[deps.IntervalSets]] +git-tree-sha1 = "79d6bd28c8d9bccc2229784f1bd637689b256377" +uuid = "8197267c-284f-5f27-9208-e0e47529a953" +version = "0.7.14" +weakdeps = ["Random", "RecipesBase", "Statistics"] + + [deps.IntervalSets.extensions] + IntervalSetsRandomExt = "Random" + IntervalSetsRecipesBaseExt = "RecipesBase" + IntervalSetsStatisticsExt = "Statistics" + +[[deps.InverseFunctions]] +git-tree-sha1 = "a779299d77cd080bf77b97535acecd73e1c5e5cb" +uuid = "3587e190-3f89-42d0-90ee-14403ec27112" +version = "0.1.17" +weakdeps = ["Dates", "Test"] + + [deps.InverseFunctions.extensions] + InverseFunctionsDatesExt = "Dates" + InverseFunctionsTestExt = "Test" + +[[deps.InvertedIndices]] +git-tree-sha1 = "6da3c4316095de0f5ee2ebd875df8721e7e0bdbe" +uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" +version = "1.3.1" + +[[deps.IrrationalConstants]] +git-tree-sha1 = "b2d91fe939cae05960e760110b328288867b5758" +uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" +version = "0.2.6" + +[[deps.Isoband]] +deps = ["isoband_jll"] +git-tree-sha1 = "f9b6d97355599074dc867318950adaa6f9946137" +uuid = "f1662d9f-8043-43de-a69a-05efc1cc6ff4" +version = "0.1.1" + +[[deps.IterTools]] +git-tree-sha1 = "42d5f897009e7ff2cf88db414a389e5ed1bdd023" +uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e" +version = "1.10.0" + +[[deps.IteratorInterfaceExtensions]] +git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" +uuid = "82899510-4779-5014-852e-03e436cf321d" +version = "1.0.0" + +[[deps.JLD2]] +deps = ["ChunkCodecLibZlib", "ChunkCodecLibZstd", "FileIO", "MacroTools", "Mmap", "OrderedCollections", "PrecompileTools", "ScopedValues"] +git-tree-sha1 = "941f87a0ae1b14d1ac2fa57245425b23a9d7a516" +uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819" +version = "0.6.4" +weakdeps = ["UnPack"] + + [deps.JLD2.extensions] + UnPackExt = "UnPack" + +[[deps.JLFzf]] +deps = ["REPL", "Random", "fzf_jll"] +git-tree-sha1 = "82f7acdc599b65e0f8ccd270ffa1467c21cb647b" +uuid = "1019f520-868f-41f5-a6de-eb00f4b6a39c" +version = "0.1.11" + +[[deps.JLLWrappers]] +deps = ["Artifacts", "Preferences"] +git-tree-sha1 = "7204148362dafe5fe6a273f855b8ccbe4df8173e" +uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" +version = "1.8.0" + +[[deps.JSON]] +deps = ["Dates", "Logging", "Parsers", "PrecompileTools", "StructUtils", "UUIDs", "Unicode"] +git-tree-sha1 = "c89d196f5ffb64bfbf80985b699ea913b0d2c211" +uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +version = "1.6.1" + + [deps.JSON.extensions] + JSONArrowExt = ["ArrowTypes"] + + [deps.JSON.weakdeps] + ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" + +[[deps.JpegTurbo]] +deps = ["CEnum", "FileIO", "ImageCore", "JpegTurbo_jll", "TOML"] +git-tree-sha1 = "9496de8fb52c224a2e3f9ff403947674517317d9" +uuid = "b835a17e-a41a-41e7-81f0-2f016b05efe0" +version = "0.1.6" + +[[deps.JpegTurbo_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c0c9b76f3520863909825cbecdef58cd63de705a" +uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8" +version = "3.1.5+0" + +[[deps.JuliaFormatter]] +deps = ["CommonMark", "Glob", "JuliaSyntax", "PrecompileTools", "TOML"] +git-tree-sha1 = "061c36ac4aa4e75fddfe40e22da3167a6271c7ce" +uuid = "98e50ef6-434e-11e9-1051-2b60c6c9e899" +version = "2.5.5" + +[[deps.JuliaInterpreter]] +deps = ["CodeTracking", "InteractiveUtils", "Random", "UUIDs"] +git-tree-sha1 = "58927c485919bf17ea308d9d82156de1adf4b006" +uuid = "aa1ae85d-cabe-5617-a682-6adf51b2e16a" +version = "0.10.12" + +[[deps.JuliaSyntax]] +git-tree-sha1 = "0d4b3dab95018bcf3925204475693d9f09dc45b8" +uuid = "70703baa-626e-46a2-a12c-08ffd08c73b4" +version = "1.0.2" + +[[deps.KernelDensity]] +deps = ["Distributions", "DocStringExtensions", "FFTA", "Interpolations", "StatsBase"] +git-tree-sha1 = "9eda8292dd3268b3b7ec9df21bbfac24e177ec52" +uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b" +version = "0.6.12" + +[[deps.LAME_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "059aabebaa7c82ccb853dd4a0ee9d17796f7e1bc" +uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d" +version = "3.100.3+0" + +[[deps.LERC_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "17b94ecafcfa45e8360a4fc9ca6b583b049e4e37" +uuid = "88015f11-f218-50d7-93a8-a6af411a945d" +version = "4.1.0+0" + +[[deps.LLVMOpenMP_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "eb62a3deb62fc6d8822c0c4bef73e4412419c5d8" +uuid = "1d63c593-3942-5779-bab2-d838dc0a180e" +version = "18.1.8+0" + +[[deps.LaTeXStrings]] +git-tree-sha1 = "dda21b8cbd6a6c40d9d02a73230f9d70fed6918c" +uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" +version = "1.4.0" + +[[deps.Latexify]] +deps = ["Format", "Ghostscript_jll", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "OrderedCollections", "Requires"] +git-tree-sha1 = "44f93c47f9cd6c7e431f2f2091fcba8f01cd7e8f" +uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" +version = "0.16.10" + + [deps.Latexify.extensions] + DataFramesExt = "DataFrames" + SparseArraysExt = "SparseArrays" + SymEngineExt = "SymEngine" + TectonicExt = "tectonic_jll" + + [deps.Latexify.weakdeps] + DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + SymEngine = "123dc426-2d89-5057-bbad-38513e3affd8" + tectonic_jll = "d7dd28d6-a5e6-559c-9131-7eb760cdacc5" + +[[deps.LayoutPointers]] +deps = ["ArrayInterface", "LinearAlgebra", "ManualMemory", "SIMDTypes", "Static", "StaticArrayInterface"] +git-tree-sha1 = "a9eaadb366f5493a5654e843864c13d8b107548c" +uuid = "10f19ff3-798f-405d-979b-55457f8fc047" +version = "0.1.17" + +[[deps.LazilyInitializedFields]] +git-tree-sha1 = "0f2da712350b020bc3957f269c9caad516383ee0" +uuid = "0e77f7df-68c5-4e49-93ce-4cd80f5598bf" +version = "1.3.0" + +[[deps.LazyArtifacts]] +deps = ["Artifacts", "Pkg"] +uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3" +version = "1.11.0" + +[[deps.LazyModules]] +git-tree-sha1 = "a560dd966b386ac9ae60bdd3a3d3a326062d3c3e" +uuid = "8cdb02fc-e678-4876-92c5-9defec4f444e" +version = "0.3.1" + +[[deps.LeftChildRightSiblingTrees]] +deps = ["AbstractTrees"] +git-tree-sha1 = "95ba48564903b43b2462318aa243ee79d81135ff" +uuid = "1d6d02ad-be62-4b6b-8a6d-2f90e265016e" +version = "0.2.1" + +[[deps.LibCURL]] +deps = ["LibCURL_jll", "MozillaCACerts_jll"] +uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" +version = "0.6.4" + +[[deps.LibCURL_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] +uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" +version = "8.6.0+0" + +[[deps.LibGit2]] +deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] +uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" +version = "1.11.0" + +[[deps.LibGit2_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] +uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" +version = "1.7.2+0" + +[[deps.LibSSH2_jll]] +deps = ["Artifacts", "Libdl", "MbedTLS_jll"] +uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" +version = "1.11.0+1" + +[[deps.Libdl]] +uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" +version = "1.11.0" + +[[deps.Libepoxy_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Xorg_libX11_jll"] +git-tree-sha1 = "94d068f57b4241dd090693b6aba63416892298de" +uuid = "42c93a91-0102-5b3f-8f9d-e41de60ac950" +version = "1.5.11+0" + +[[deps.Libffi_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c8da7e6a91781c41a863611c7e966098d783c57a" +uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490" +version = "3.4.7+0" + +[[deps.Libglvnd_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll", "Xorg_libXext_jll"] +git-tree-sha1 = "d36c21b9e7c172a44a10484125024495e2625ac0" +uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29" +version = "1.7.1+1" + +[[deps.Libiconv_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "be484f5c92fad0bd8acfef35fe017900b0b73809" +uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" +version = "1.18.0+0" + +[[deps.Libmount_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "cc3ad4faf30015a3e8094c9b5b7f19e85bdf2386" +uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9" +version = "2.42.0+0" + +[[deps.Libtiff_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "LERC_jll", "Libdl", "XZ_jll", "Zlib_jll", "Zstd_jll"] +git-tree-sha1 = "f04133fe05eff1667d2054c53d59f9122383fe05" +uuid = "89763e89-9b03-5906-acba-b20f662cd828" +version = "4.7.2+0" + +[[deps.Libuuid_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "d620582b1f0cbe2c72dd1d5bd195a9ce73370ab1" +uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700" +version = "2.42.0+0" + +[[deps.Libz]] +deps = ["BufferedStreams", "Random", "Test"] +git-tree-sha1 = "bf1510e80f1e0dba2297b05b59a3a7c8175a9517" +uuid = "2ec943e9-cfe8-584d-b93d-64dcb6d567b7" +version = "1.0.1" + +[[deps.LinearAlgebra]] +deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] +uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +version = "1.11.0" + +[[deps.LittleCMS_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll"] +git-tree-sha1 = "70bd263e082a236c8c2661a474616d95ba59d2cf" +uuid = "d3a379c0-f9a3-5b72-a4c0-6bf4d2e8af0f" +version = "2.19.0+0" + +[[deps.Loess]] +deps = ["Distances", "LinearAlgebra", "Statistics", "StatsAPI", "StatsFuns"] +git-tree-sha1 = "aac61f60ed2b1561ae1bbef4e6d7b75c27f1f9e3" +uuid = "4345ca2d-374a-55d4-8d30-97f9976e7612" +version = "0.6.6" + +[[deps.LogExpFunctions]] +deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"] +git-tree-sha1 = "13ca9e2586b89836fd20cccf56e57e2b9ae7f38f" +uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" +version = "0.3.29" + + [deps.LogExpFunctions.extensions] + LogExpFunctionsChainRulesCoreExt = "ChainRulesCore" + LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables" + LogExpFunctionsInverseFunctionsExt = "InverseFunctions" + + [deps.LogExpFunctions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + +[[deps.Logging]] +uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" +version = "1.11.0" + +[[deps.LoggingExtras]] +deps = ["Dates", "Logging"] +git-tree-sha1 = "f00544d95982ea270145636c181ceda21c4e2575" +uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36" +version = "1.2.0" + +[[deps.LoopVectorization]] +deps = ["ArrayInterface", "CPUSummary", "CloseOpenIntervals", "DocStringExtensions", "HostCPUFeatures", "IfElse", "LayoutPointers", "LinearAlgebra", "OffsetArrays", "PolyesterWeave", "PrecompileTools", "SIMDTypes", "SLEEFPirates", "Static", "StaticArrayInterface", "ThreadingUtilities", "UnPack", "VectorizationBase"] +git-tree-sha1 = "514e8475e33c6faf3155efee5f3c10d9e65a11ab" +uuid = "bdcacae8-1622-11e9-2a5c-532679323890" +version = "0.12.174" + + [deps.LoopVectorization.extensions] + ForwardDiffExt = ["ChainRulesCore", "ForwardDiff"] + ForwardDiffNNlibExt = ["ForwardDiff", "NNlib"] + SpecialFunctionsExt = "SpecialFunctions" + + [deps.LoopVectorization.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + NNlib = "872c559c-99b0-510c-b3b7-b6c96a88d5cd" + SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b" + +[[deps.LoweredCodeUtils]] +deps = ["CodeTracking", "Compiler", "JuliaInterpreter"] +git-tree-sha1 = "86492c15dee3182863d7452dd2b2635242dedaca" +uuid = "6f1432cf-f94c-5a45-995e-cdbf5db27b0b" +version = "3.5.2" + +[[deps.MIMEs]] +git-tree-sha1 = "c64d943587f7187e751162b3b84445bbbd79f691" +uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65" +version = "1.1.0" + +[[deps.MKL_jll]] +deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "oneTBB_jll"] +git-tree-sha1 = "282cadc186e7b2ae0eeadbd7a4dffed4196ae2aa" +uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7" +version = "2025.2.0+0" + +[[deps.MacroTools]] +git-tree-sha1 = "1e0228a030642014fe5cfe68c2c0a818f9e3f522" +uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" +version = "0.5.16" + +[[deps.Makie]] +deps = ["Animations", "Base64", "CRC32c", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "ComputePipeline", "Contour", "Dates", "DelaunayTriangulation", "Distributions", "DocStringExtensions", "Downloads", "FFMPEG_jll", "FileIO", "FilePaths", "FixedPointNumbers", "Format", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageBase", "ImageIO", "InteractiveUtils", "Interpolations", "IntervalSets", "InverseFunctions", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MacroTools", "Markdown", "MathTeXEngine", "Observables", "OffsetArrays", "PNGFiles", "Packing", "Pkg", "PlotUtils", "PolygonOps", "PrecompileTools", "Printf", "REPL", "Random", "RelocatableFolders", "Scratch", "ShaderAbstractions", "SignedDistanceFields", "SparseArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "TriplotBase", "UnicodeFun", "Unitful"] +git-tree-sha1 = "1cdb9a8ca42229d1ff880ce85e9b31ef2291bce3" +uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" +version = "0.24.11" + + [deps.Makie.extensions] + MakieDynamicQuantitiesExt = "DynamicQuantities" + + [deps.Makie.weakdeps] + DynamicQuantities = "06fc5a27-2a28-4c7c-a15d-362465fb6821" + +[[deps.ManualMemory]] +git-tree-sha1 = "bcaef4fc7a0cfe2cba636d84cda54b5e4e4ca3cd" +uuid = "d125e4d3-2237-4719-b19c-fa641b8a4667" +version = "0.1.8" + +[[deps.MappedArrays]] +git-tree-sha1 = "0ee4497a4e80dbd29c058fcee6493f5219556f40" +uuid = "dbb5928d-eab1-5f90-85c2-b9b0edb7c900" +version = "0.4.3" + +[[deps.Markdown]] +deps = ["Base64"] +uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" +version = "1.11.0" + +[[deps.MarkdownAST]] +deps = ["AbstractTrees", "Markdown"] +git-tree-sha1 = "93c718d892e73931841089cdc0e982d6dd9cc87b" +uuid = "d0879d2d-cac2-40c8-9cee-1863dc0c7391" +version = "0.1.3" + +[[deps.MathTeXEngine]] +deps = ["AbstractTrees", "Automa", "DataStructures", "FreeTypeAbstraction", "GeometryBasics", "LaTeXStrings", "REPL", "RelocatableFolders", "UnicodeFun"] +git-tree-sha1 = "aa1078778be5a8e5259ff04fbc3d258b3e78d464" +uuid = "0a4f8689-d25c-4efe-a92b-7142dfc1aa53" +version = "0.6.9" + +[[deps.MbedTLS]] +deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"] +git-tree-sha1 = "8785729fa736197687541f7053f6d8ab7fc44f92" +uuid = "739be429-bea8-5141-9913-cc70e7f3736d" +version = "1.1.10" + +[[deps.MbedTLS_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" +version = "2.28.6+0" + +[[deps.Measures]] +git-tree-sha1 = "b513cedd20d9c914783d8ad83d08120702bf2c77" +uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e" +version = "0.3.3" + +[[deps.MeshIO]] +deps = ["ColorTypes", "FileIO", "GeometryBasics", "Printf"] +git-tree-sha1 = "c009236e222df68e554c7ce5c720e4a33cc0c23f" +uuid = "7269a6da-0436-5bbc-96c2-40638cbb6118" +version = "0.5.3" + +[[deps.MetaGraphs]] +deps = ["Graphs", "JLD2", "Random"] +git-tree-sha1 = "3a8f462a180a9d735e340f4e8d5f364d411da3a4" +uuid = "626554b9-1ddb-594c-aa3c-2596fe9399a5" +version = "0.8.1" + +[[deps.Millboard]] +git-tree-sha1 = "ea6a5b7e56e76d8051023faaa11d91d1d881dac3" +uuid = "39ec1447-df44-5f4c-beaa-866f30b4d3b2" +version = "0.2.5" + +[[deps.Missings]] +deps = ["DataAPI"] +git-tree-sha1 = "ec4f7fbeab05d7747bdf98eb74d130a2a2ed298d" +uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" +version = "1.2.0" + +[[deps.Mixers]] +deps = ["MacroTools"] +git-tree-sha1 = "58ec7ac60dad6e8ca4553225251dfd380e3930dd" +uuid = "2a8e4939-dab8-5edc-8f64-72a8776f13de" +version = "0.1.2" + +[[deps.Mmap]] +uuid = "a63ad114-7e13-5084-954f-fe012c677804" +version = "1.11.0" + +[[deps.ModernGL]] +deps = ["Libdl"] +git-tree-sha1 = "ac6cb1d8807a05cf1acc9680e09d2294f9d33956" +uuid = "66fc600b-dfda-50eb-8b99-91cfa97b1301" +version = "1.1.8" + +[[deps.MosaicViews]] +deps = ["MappedArrays", "OffsetArrays", "PaddedViews", "StackViews"] +git-tree-sha1 = "7b86a5d4d70a9f5cdf2dacb3cbe6d251d1a61dbe" +uuid = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389" +version = "0.3.4" + +[[deps.MozillaCACerts_jll]] +uuid = "14a3606d-f60d-562e-9121-12d972cd8159" +version = "2023.12.12" + +[[deps.MuladdMacro]] +git-tree-sha1 = "cac9cc5499c25554cba55cd3c30543cff5ca4fab" +uuid = "46d2c3a1-f734-5fdb-9937-b9b9aeba4221" +version = "0.2.4" + +[[deps.NaNMath]] +deps = ["OpenLibm_jll"] +git-tree-sha1 = "9b8215b1ee9e78a293f99797cd31375471b2bcae" +uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +version = "1.1.3" + +[[deps.NativeFileDialog]] +deps = ["FilePathsBase", "NativeFileDialog_jll"] +git-tree-sha1 = "6964c902c838b214cb4e8b4a94ca45e585c9d47b" +uuid = "e1fe445b-aa65-4df4-81c1-2041507f0fd4" +version = "0.2.1" + +[[deps.NativeFileDialog_jll]] +deps = ["Artifacts", "GTK3_jll", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "916d2db66748820c8e8bc3329a2a23c42c1520de" +uuid = "94d9ae2c-efc7-56f8-9a02-54c47b797961" +version = "1.1.6+3" + +[[deps.NaturalSort]] +git-tree-sha1 = "eda490d06b9f7c00752ee81cfa451efe55521e21" +uuid = "c020b1a1-e9b0-503a-9c33-f039bfc54a85" +version = "1.0.0" + +[[deps.NearestNeighbors]] +deps = ["AbstractTrees", "Distances", "StaticArrays"] +git-tree-sha1 = "e2c3bba08dd6dedfe17a17889131b885b8c082f0" +uuid = "b8a86587-4115-5ab1-83bc-aa920d37bbce" +version = "0.4.27" + +[[deps.Netpbm]] +deps = ["FileIO", "ImageCore", "ImageMetadata"] +git-tree-sha1 = "d92b107dbb887293622df7697a2223f9f8176fcd" +uuid = "f09324ee-3d7c-5217-9330-fc30815ba969" +version = "1.1.1" + +[[deps.Nettle]] +deps = ["Libdl", "Nettle_jll"] +git-tree-sha1 = "6fa48cbae828267848ee32c1bb31d1652e210d7d" +uuid = "49dea1ee-f6fa-5aa6-9a11-8816cee7d4b9" +version = "1.0.0" + +[[deps.Nettle_jll]] +deps = ["Artifacts", "GMP_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "2759db33ad6145e162d49d86360b350c9c79354f" +uuid = "4c82536e-c426-54e4-b420-14f461c4ed8b" +version = "3.10.2+0" + +[[deps.NetworkOptions]] +uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" +version = "1.2.0" + +[[deps.Nullables]] +git-tree-sha1 = "8f87854cc8f3685a60689d8edecaa29d2251979b" +uuid = "4d1e1d77-625e-5b40-9113-a560ec7a8ecd" +version = "1.0.0" + +[[deps.Observables]] +git-tree-sha1 = "7438a59546cf62428fc9d1bc94729146d37a7225" +uuid = "510215fc-4207-5dde-b226-833fc4488ee2" +version = "0.5.5" + +[[deps.OffsetArrays]] +git-tree-sha1 = "117432e406b5c023f665fa73dc26e79ec3630151" +uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881" +version = "1.17.0" +weakdeps = ["Adapt"] + + [deps.OffsetArrays.extensions] + OffsetArraysAdaptExt = "Adapt" + +[[deps.Ogg_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b6aa4566bb7ae78498a5e68943863fa8b5231b59" +uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051" +version = "1.3.6+0" + +[[deps.OpenBLASConsistentFPCSR_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "3287ec88df50429a934ebc6cf14606215e27b987" +uuid = "6cdc7f73-28fd-5e50-80fb-958a8875b1af" +version = "0.3.33+0" + +[[deps.OpenBLAS_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] +uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" +version = "0.3.27+1" + +[[deps.OpenEXR]] +deps = ["Colors", "FileIO", "OpenEXR_jll"] +git-tree-sha1 = "97db9e07fe2091882c765380ef58ec553074e9c7" +uuid = "52e1d378-f018-4a11-a4be-720524705ac7" +version = "0.3.3" + +[[deps.OpenEXR_jll]] +deps = ["Artifacts", "Imath_jll", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "9ac7c730c53b3b5d9a73fb900ac4b4fc263774db" +uuid = "18a262bb-aa17-5467-a713-aee519bc75cb" +version = "3.4.9+0" + +[[deps.OpenJpeg_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libtiff_jll", "LittleCMS_jll", "libpng_jll"] +git-tree-sha1 = "215a6666fee6d6b3a6e75f2cc22cb767e2dd393a" +uuid = "643b3616-a352-519d-856d-80112ee9badc" +version = "2.5.5+0" + +[[deps.OpenLibm_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "05823500-19ac-5b8b-9628-191a04bc5112" +version = "0.8.1+2" + +[[deps.OpenSSH_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "OpenSSL_jll", "Zlib_jll"] +git-tree-sha1 = "57baa4b81a24c2910afbb6d853aa0685e4312bf7" +uuid = "9bd350c2-7e96-507f-8002-3f2e150b4e1b" +version = "10.3.1+0" + +[[deps.OpenSSL]] +deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "NetworkOptions", "OpenSSL_jll", "Sockets"] +git-tree-sha1 = "1d1aaa7d449b58415f97d2839c318b70ffb525a0" +uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c" +version = "1.6.1" + +[[deps.OpenSSL_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "2ac022577e5eac7da040de17776d51bb770cd895" +uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" +version = "3.5.6+0" + +[[deps.OpenSpecFun_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1346c9208249809840c91b26703912dff463d335" +uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" +version = "0.5.6+0" + +[[deps.Opus_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e2bb57a313a74b8104064b7efd01406c0a50d2ff" +uuid = "91d4177d-7536-5919-b921-800302f37372" +version = "1.6.1+0" + +[[deps.OrderedCollections]] +git-tree-sha1 = "94ba93778373a53bfd5a0caaf7d809c445292ff4" +uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" +version = "1.8.2" + +[[deps.PCRE2_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "efcefdf7-47ab-520b-bdef-62a2eaa19f15" +version = "10.42.0+1" + +[[deps.PDMats]] +deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"] +git-tree-sha1 = "e4cff168707d441cd6bf3ff7e4832bdf34278e4a" +uuid = "90014a1f-27ba-587c-ab20-58faa44d9150" +version = "0.11.37" +weakdeps = ["StatsBase"] + + [deps.PDMats.extensions] + StatsBaseExt = "StatsBase" + +[[deps.PNGFiles]] +deps = ["Base64", "CEnum", "ImageCore", "IndirectArrays", "OffsetArrays", "libpng_jll"] +git-tree-sha1 = "32b657a0d57c310a1a172bfc8c8cf68c5e674323" +uuid = "f57f5aa1-a3ce-4bc8-8ab9-96f992907883" +version = "0.4.5" + +[[deps.PackageCompiler]] +deps = ["Artifacts", "Glob", "LazyArtifacts", "Libdl", "Pkg", "Printf", "RelocatableFolders", "TOML", "UUIDs", "p7zip_jll"] +git-tree-sha1 = "5193091a937c1e84cab042d55f8071dd2116c6f2" +uuid = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d" +version = "2.3.0" + +[[deps.Packing]] +deps = ["GeometryBasics"] +git-tree-sha1 = "bc5bf2ea3d5351edf285a06b0016788a121ce92c" +uuid = "19eb6ba3-879d-56ad-ad62-d5c202156566" +version = "0.5.1" + +[[deps.PaddedViews]] +deps = ["OffsetArrays"] +git-tree-sha1 = "0fac6313486baae819364c52b4f483450a9d793f" +uuid = "5432bcbf-9aad-5242-b902-cca2824c8663" +version = "0.5.12" + +[[deps.Pango_jll]] +deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "58e5ed5e386e156bd93e86b305ebd21ac63d2d04" +uuid = "36c8627f-9965-5494-a995-c6b170f724f3" +version = "1.57.1+0" + +[[deps.Parameters]] +deps = ["OrderedCollections", "UnPack"] +git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe" +uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a" +version = "0.12.3" + +[[deps.Parsers]] +deps = ["Dates", "PrecompileTools", "UUIDs"] +git-tree-sha1 = "5d5e0a78e971354b1c7bff0655d11fdc1b0e12c8" +uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" +version = "2.8.4" + +[[deps.Pixman_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "LLVMOpenMP_jll", "Libdl"] +git-tree-sha1 = "e4a6721aa89e62e5d4217c0b21bd714263779dda" +uuid = "30392449-352a-5448-841d-b1acce4e97dc" +version = "0.46.4+0" + +[[deps.Pkg]] +deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "Random", "SHA", "TOML", "Tar", "UUIDs", "p7zip_jll"] +uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +version = "1.11.0" +weakdeps = ["REPL"] + + [deps.Pkg.extensions] + REPLExt = "REPL" + +[[deps.PkgVersion]] +deps = ["Pkg"] +git-tree-sha1 = "f9501cc0430a26bc3d156ae1b5b0c1b47af4d6da" +uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688" +version = "0.3.3" + +[[deps.PlotThemes]] +deps = ["PlotUtils", "Statistics"] +git-tree-sha1 = "41031ef3a1be6f5bbbf3e8073f210556daeae5ca" +uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a" +version = "3.3.0" + +[[deps.PlotUtils]] +deps = ["ColorSchemes", "Colors", "Dates", "PrecompileTools", "Printf", "Random", "Reexport", "StableRNGs", "Statistics"] +git-tree-sha1 = "26ca162858917496748aad52bb5d3be4d26a228a" +uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043" +version = "1.4.4" + +[[deps.PlotlyBase]] +deps = ["ColorSchemes", "Colors", "Dates", "DelimitedFiles", "DocStringExtensions", "JSON", "LaTeXStrings", "Logging", "Parameters", "Pkg", "REPL", "Requires", "Statistics", "UUIDs"] +git-tree-sha1 = "6256ab3ee24ef079b3afa310593817e069925eeb" +uuid = "a03496cd-edff-5a9b-9e67-9cda94a718b5" +version = "0.8.23" + + [deps.PlotlyBase.extensions] + DataFramesExt = "DataFrames" + DistributionsExt = "Distributions" + IJuliaExt = "IJulia" + JSON3Ext = "JSON3" + + [deps.PlotlyBase.weakdeps] + DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" + Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f" + IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" + JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" + +[[deps.Plots]] +deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "JLFzf", "JSON", "LaTeXStrings", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "Pkg", "PlotThemes", "PlotUtils", "PrecompileTools", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "RelocatableFolders", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "TOML", "UUIDs", "UnicodeFun", "Unzip"] +git-tree-sha1 = "cb20a4eacda080e517e4deb9cfb6c7c518131265" +uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" +version = "1.41.6" + + [deps.Plots.extensions] + FileIOExt = "FileIO" + GeometryBasicsExt = "GeometryBasics" + IJuliaExt = "IJulia" + ImageInTerminalExt = "ImageInTerminal" + UnitfulExt = "Unitful" + + [deps.Plots.weakdeps] + FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" + GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326" + IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" + ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.PolyesterWeave]] +deps = ["BitTwiddlingConvenienceFunctions", "CPUSummary", "IfElse", "Static", "ThreadingUtilities"] +git-tree-sha1 = "645bed98cd47f72f67316fd42fc47dee771aefcd" +uuid = "1d0040c9-8b98-4ee7-8388-3f51789ca0ad" +version = "0.2.2" + +[[deps.PolygonOps]] +git-tree-sha1 = "77b3d3605fc1cd0b42d95eba87dfcd2bf67d5ff6" +uuid = "647866c9-e3ac-4575-94e7-e3d426903924" +version = "0.1.2" + +[[deps.Polynomials]] +deps = ["LinearAlgebra", "OrderedCollections", "Setfield", "SparseArrays"] +git-tree-sha1 = "2d99b4c8a7845ab1342921733fa29366dae28b24" +uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45" +version = "4.1.1" + + [deps.Polynomials.extensions] + PolynomialsChainRulesCoreExt = "ChainRulesCore" + PolynomialsFFTWExt = "FFTW" + PolynomialsMakieExt = "Makie" + PolynomialsMutableArithmeticsExt = "MutableArithmetics" + PolynomialsRecipesBaseExt = "RecipesBase" + + [deps.Polynomials.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" + Makie = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" + MutableArithmetics = "d8a4904e-b15c-11e9-3269-09a3773c0cb0" + RecipesBase = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" + +[[deps.PooledArrays]] +deps = ["DataAPI", "Future"] +git-tree-sha1 = "36d8b4b899628fb92c2749eb488d884a926614d3" +uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" +version = "1.4.3" + +[[deps.PrecompileTools]] +deps = ["Preferences"] +git-tree-sha1 = "5aa36f7049a63a1528fe8f7c3f2113413ffd4e1f" +uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +version = "1.2.1" + +[[deps.Preferences]] +deps = ["TOML"] +git-tree-sha1 = "8b770b60760d4451834fe79dd483e318eee709c4" +uuid = "21216c6a-2e73-6563-6e65-726566657250" +version = "1.5.2" + +[[deps.PrettyTables]] +deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "REPL", "Reexport", "StringManipulation", "Tables"] +git-tree-sha1 = "624de6279ab7d94fc9f672f0068107eb6619732c" +uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" +version = "3.3.2" + + [deps.PrettyTables.extensions] + PrettyTablesTypstryExt = "Typstry" + + [deps.PrettyTables.weakdeps] + Typstry = "f0ed7684-a786-439e-b1e3-3b82803b501e" + +[[deps.Primes]] +deps = ["IntegerMathUtils"] +git-tree-sha1 = "25cdd1d20cd005b52fc12cb6be3f75faaf59bb9b" +uuid = "27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae" +version = "0.5.7" + +[[deps.Printf]] +deps = ["Unicode"] +uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" +version = "1.11.0" + +[[deps.Profile]] +uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" +version = "1.11.0" + +[[deps.ProgressMeter]] +deps = ["Distributed", "Printf"] +git-tree-sha1 = "fbb92c6c56b34e1a2c4c36058f68f332bec840e7" +uuid = "92933f4c-e287-5a05-a399-4b506db050ca" +version = "1.11.0" + +[[deps.PtrArrays]] +git-tree-sha1 = "4fbbafbc6251b883f4d2705356f3641f3652a7fe" +uuid = "43287f4e-b6f4-7ad1-bb20-aadabca52c3d" +version = "1.4.0" + +[[deps.QOI]] +deps = ["ColorTypes", "FileIO", "FixedPointNumbers"] +git-tree-sha1 = "472daaa816895cb7aee81658d4e7aec901fa1106" +uuid = "4b34888f-f399-49d4-9bb3-47ed5cae4e65" +version = "1.0.2" + +[[deps.Qt6Base_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Vulkan_Loader_jll", "Xorg_libSM_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_cursor_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "libinput_jll", "xkbcommon_jll"] +git-tree-sha1 = "144895f6166994730ee7ff8113b981fc360638f1" +uuid = "c0090381-4147-56d7-9ebc-da0b1113ec56" +version = "6.10.2+2" + +[[deps.Qt6Declarative_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll", "Qt6ShaderTools_jll", "Qt6Svg_jll"] +git-tree-sha1 = "d5b7dd0e226774cbd87e2790e34def09245c7eab" +uuid = "629bc702-f1f5-5709-abd5-49b8460ea067" +version = "6.10.2+1" + +[[deps.Qt6ShaderTools_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll"] +git-tree-sha1 = "4d85eedf69d875982c46643f6b4f66919d7e157b" +uuid = "ce943373-25bb-56aa-8eca-768745ed7b5a" +version = "6.10.2+1" + +[[deps.Qt6Svg_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll"] +git-tree-sha1 = "81587ff5ff25a4e1115ce191e36285ede0334c9d" +uuid = "6de9746b-f93d-5813-b365-ba18ad4a9cf3" +version = "6.10.2+0" + +[[deps.Qt6Wayland_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll", "Qt6Declarative_jll"] +git-tree-sha1 = "672c938b4b4e3e0169a07a5f227029d4905456f2" +uuid = "e99dba38-086e-5de3-a5b1-6e4c66e897c3" +version = "6.10.2+1" + +[[deps.QuadGK]] +deps = ["DataStructures", "LinearAlgebra"] +git-tree-sha1 = "5e8e8b0ab68215d7a2b14b9921a946fee794749e" +uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc" +version = "2.11.3" + + [deps.QuadGK.extensions] + QuadGKEnzymeExt = "Enzyme" + + [deps.QuadGK.weakdeps] + Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" + +[[deps.Quaternions]] +deps = ["LinearAlgebra", "Random", "RealDot"] +git-tree-sha1 = "4d8c1b7c3329c1885b857abb50d08fa3f4d9e3c8" +uuid = "94ee1d12-ae83-5a48-8b1c-48b8ff168ae0" +version = "0.7.7" + +[[deps.REPL]] +deps = ["InteractiveUtils", "Markdown", "Sockets", "StyledStrings", "Unicode"] +uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" +version = "1.11.0" + +[[deps.Random]] +deps = ["SHA"] +uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +version = "1.11.0" + +[[deps.RangeArrays]] +git-tree-sha1 = "b9039e93773ddcfc828f12aadf7115b4b4d225f5" +uuid = "b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d" +version = "0.3.2" + +[[deps.Ratios]] +deps = ["Requires"] +git-tree-sha1 = "1342a47bf3260ee108163042310d26f2be5ec90b" +uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439" +version = "0.4.5" +weakdeps = ["FixedPointNumbers"] + + [deps.Ratios.extensions] + RatiosFixedPointNumbersExt = "FixedPointNumbers" + +[[deps.RealDot]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9" +uuid = "c1ae055f-0cd5-4b69-90a6-9a35b1a98df9" +version = "0.1.0" + +[[deps.RecipesBase]] +deps = ["PrecompileTools"] +git-tree-sha1 = "5c3d09cc4f31f5fc6af001c250bf1278733100ff" +uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" +version = "1.3.4" + +[[deps.RecipesPipeline]] +deps = ["Dates", "NaNMath", "PlotUtils", "PrecompileTools", "RecipesBase"] +git-tree-sha1 = "45cf9fd0ca5839d06ef333c8201714e888486342" +uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c" +version = "0.6.12" + +[[deps.Reexport]] +git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" +uuid = "189a3867-3050-52da-a836-e630ba90ab69" +version = "1.2.2" + +[[deps.RegionTrees]] +deps = ["IterTools", "LinearAlgebra", "StaticArrays"] +git-tree-sha1 = "4618ed0da7a251c7f92e869ae1a19c74a7d2a7f9" +uuid = "dee08c22-ab7f-5625-9660-a9af2021b33f" +version = "0.3.2" + +[[deps.RegistryInstances]] +deps = ["LazilyInitializedFields", "Pkg", "TOML", "Tar"] +git-tree-sha1 = "ffd19052caf598b8653b99404058fce14828be51" +uuid = "2792f1a3-b283-48e8-9a74-f99dce5104f3" +version = "0.1.0" + +[[deps.RelocatableFolders]] +deps = ["SHA", "Scratch"] +git-tree-sha1 = "ffdaf70d81cf6ff22c2b6e733c900c3321cab864" +uuid = "05181044-ff0b-4ac5-8273-598c1e38db00" +version = "1.0.1" + +[[deps.RemoteREPL]] +deps = ["Logging", "OpenSSH_jll", "REPL", "ReplMaker", "Serialization", "Sockets", "UUIDs"] +git-tree-sha1 = "4dc40bec45f3c2dc8648e50438753a6be1b87f40" +uuid = "1bd9f7bb-701c-4338-bec7-ac987af7c555" +version = "0.3.1" + +[[deps.ReplMaker]] +deps = ["REPL", "Unicode"] +git-tree-sha1 = "f8bb680b97ee232c4c6591e213adc9c1e4ba0349" +uuid = "b873ce64-0db9-51f5-a568-4457d8e49576" +version = "0.2.7" + +[[deps.Requires]] +deps = ["UUIDs"] +git-tree-sha1 = "62389eeff14780bfe55195b7204c0d8738436d64" +uuid = "ae029012-a4dd-5104-9daa-d747884805df" +version = "1.3.1" + +[[deps.Revise]] +deps = ["CodeTracking", "FileWatching", "InteractiveUtils", "JuliaInterpreter", "LibGit2", "LoweredCodeUtils", "OrderedCollections", "Preferences", "REPL", "UUIDs"] +git-tree-sha1 = "2f722c6581f297014be42c95d36f862e9bc2d668" +uuid = "295af30f-e4ad-537b-8983-00126c2a3abe" +version = "3.14.5" +weakdeps = ["Distributed"] + + [deps.Revise.extensions] + DistributedExt = "Distributed" + +[[deps.Rmath]] +deps = ["Random", "Rmath_jll"] +git-tree-sha1 = "5b3d50eb374cea306873b371d3f8d3915a018f0b" +uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa" +version = "0.9.0" + +[[deps.Rmath_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "58cdd8fb2201a6267e1db87ff148dd6c1dbd8ad8" +uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f" +version = "0.5.1+0" + +[[deps.Rotations]] +deps = ["LinearAlgebra", "Quaternions", "Random", "StaticArrays"] +git-tree-sha1 = "5680a9276685d392c87407df00d57c9924d9f11e" +uuid = "6038ab10-8711-5258-84ad-4b1120ba62dc" +version = "1.7.1" +weakdeps = ["RecipesBase"] + + [deps.Rotations.extensions] + RotationsRecipesBaseExt = "RecipesBase" + +[[deps.RoundingEmulator]] +git-tree-sha1 = "40b9edad2e5287e05bd413a38f61a8ff55b9557b" +uuid = "5eaf0fd0-dfba-4ccb-bf02-d820a40db705" +version = "0.2.1" + +[[deps.SHA]] +uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" +version = "0.7.0" + +[[deps.SIMD]] +deps = ["PrecompileTools"] +git-tree-sha1 = "e24dc23107d426a096d3eae6c165b921e74c18e4" +uuid = "fdea26ae-647d-5447-a871-4b548cad5224" +version = "3.7.2" + +[[deps.SIMDTypes]] +git-tree-sha1 = "330289636fb8107c5f32088d2741e9fd7a061a5c" +uuid = "94e857df-77ce-4151-89e5-788b33177be4" +version = "0.1.0" + +[[deps.SLEEFPirates]] +deps = ["IfElse", "Static", "VectorizationBase"] +git-tree-sha1 = "72312aa278823c0e99ce31186e22d917d2d11f99" +uuid = "476501e8-09a2-5ece-8869-fb82de89a1fa" +version = "0.6.46" + +[[deps.SavitzkyGolay]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "7bbc5949a42f53f4fca1a0157c72f9d3f78050d1" +uuid = "c4bf5708-b6a6-4fbe-bcd0-6850ed671584" +version = "0.9.1" + +[[deps.SciMLPublic]] +git-tree-sha1 = "0ba076dbdce87ba230fff48ca9bca62e1f345c9b" +uuid = "431bcebd-1456-4ced-9d72-93c2757fff0b" +version = "1.0.1" + +[[deps.ScopedValues]] +deps = ["HashArrayMappedTries", "Logging"] +git-tree-sha1 = "67a144433c4ce877ee6d1ada69a124d6b1ecf7be" +uuid = "7e506255-f358-4e82-b7e4-beb19740aa63" +version = "1.6.2" + +[[deps.Scratch]] +deps = ["Dates"] +git-tree-sha1 = "9b81b8393e50b7d4e6d0a9f14e192294d3b7c109" +uuid = "6c6a2e73-6563-6170-7368-637461726353" +version = "1.3.0" + +[[deps.SentinelArrays]] +deps = ["Dates", "Random"] +git-tree-sha1 = "084c47c7c5ce5cfecefa0a98dff69eb3646b5a80" +uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" +version = "1.4.10" + +[[deps.Serialization]] +uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" +version = "1.11.0" + +[[deps.Setfield]] +deps = ["ConstructionBase", "Future", "MacroTools", "StaticArraysCore"] +git-tree-sha1 = "c5391c6ace3bc430ca630251d02ea9687169ca68" +uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46" +version = "1.1.2" + +[[deps.ShaderAbstractions]] +deps = ["ColorTypes", "FixedPointNumbers", "GeometryBasics", "LinearAlgebra", "Observables", "StaticArrays"] +git-tree-sha1 = "818554664a2e01fc3784becb2eb3a82326a604b6" +uuid = "65257c39-d410-5151-9873-9b3e5be5013e" +version = "0.5.0" + +[[deps.SharedArrays]] +deps = ["Distributed", "Mmap", "Random", "Serialization"] +uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" +version = "1.11.0" + +[[deps.Showoff]] +deps = ["Dates", "Grisu"] +git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de" +uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f" +version = "1.0.3" + +[[deps.SignedDistanceFields]] +deps = ["Statistics"] +git-tree-sha1 = "3949ad92e1c9d2ff0cd4a1317d5ecbba682f4b92" +uuid = "73760f76-fbc4-59ce-8f25-708e95d2df96" +version = "0.4.1" + +[[deps.SimpleBufferStream]] +git-tree-sha1 = "f305871d2f381d21527c770d4788c06c097c9bc1" +uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7" +version = "1.2.0" + +[[deps.SimpleTraits]] +deps = ["InteractiveUtils", "MacroTools"] +git-tree-sha1 = "7ddb0b49c109481b046972c0e4ab02b2127d6a75" +uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d" +version = "0.9.6" + +[[deps.SimpleWeightedGraphs]] +deps = ["Graphs", "LinearAlgebra", "Markdown", "SparseArrays"] +git-tree-sha1 = "749a2b719ec7f34f280c0d97ac3dab5c89818631" +uuid = "47aef6b3-ad0c-573a-a1e2-d07658019622" +version = "1.5.1" + +[[deps.Sixel]] +deps = ["Dates", "FileIO", "ImageCore", "IndirectArrays", "OffsetArrays", "REPL", "libsixel_jll"] +git-tree-sha1 = "0494aed9501e7fb65daba895fb7fd57cc38bc743" +uuid = "45858cf5-a6b0-47a3-bbea-62219f50df47" +version = "0.1.5" + +[[deps.Sockets]] +uuid = "6462fe0b-24de-5631-8697-dd941f90decc" +version = "1.11.0" + +[[deps.SortingAlgorithms]] +deps = ["DataStructures"] +git-tree-sha1 = "64d974c2e6fdf07f8155b5b2ca2ffa9069b608d9" +uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" +version = "1.2.2" + +[[deps.SparseArrays]] +deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] +uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +version = "1.11.0" + +[[deps.SpecialFunctions]] +deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] +git-tree-sha1 = "6547cbdd8ce32efba0d21c5a40fa96d1a3548f9f" +uuid = "276daf66-3868-5448-9aa4-cd146d93841b" +version = "2.8.0" +weakdeps = ["ChainRulesCore"] + + [deps.SpecialFunctions.extensions] + SpecialFunctionsChainRulesCoreExt = "ChainRulesCore" + +[[deps.StableRNGs]] +deps = ["Random"] +git-tree-sha1 = "4f96c596b8c8258cc7d3b19797854d368f243ddc" +uuid = "860ef19b-820b-49d6-a774-d7a799459cd3" +version = "1.0.4" + +[[deps.StackViews]] +deps = ["OffsetArrays"] +git-tree-sha1 = "be1cf4eb0ac528d96f5115b4ed80c26a8d8ae621" +uuid = "cae243ae-269e-4f55-b966-ac2d0dc13c15" +version = "0.1.2" + +[[deps.Static]] +deps = ["CommonWorldInvalidations", "IfElse", "PrecompileTools", "SciMLPublic"] +git-tree-sha1 = "bb072715f158b59ad8819ff80da5ffa90cce6ceb" +uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3" +version = "1.4.0" + +[[deps.StaticArrayInterface]] +deps = ["ArrayInterface", "Compat", "IfElse", "LinearAlgebra", "PrecompileTools", "SciMLPublic", "Static"] +git-tree-sha1 = "2a635e15d5035c53b345077c947f31ff91744078" +uuid = "0d7ed370-da01-4f52-bd93-41d350b8b718" +version = "1.10.0" +weakdeps = ["OffsetArrays", "StaticArrays"] + + [deps.StaticArrayInterface.extensions] + StaticArrayInterfaceOffsetArraysExt = "OffsetArrays" + StaticArrayInterfaceStaticArraysExt = "StaticArrays" + +[[deps.StaticArrays]] +deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"] +git-tree-sha1 = "246a8bb2e6667f832eea063c3a56aef96429a3db" +uuid = "90137ffa-7385-5640-81b9-e52037218182" +version = "1.9.18" +weakdeps = ["ChainRulesCore", "Statistics"] + + [deps.StaticArrays.extensions] + StaticArraysChainRulesCoreExt = "ChainRulesCore" + StaticArraysStatisticsExt = "Statistics" + +[[deps.StaticArraysCore]] +git-tree-sha1 = "6ab403037779dae8c514bad259f32a447262455a" +uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" +version = "1.4.4" + +[[deps.Statistics]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0" +uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" +version = "1.11.1" +weakdeps = ["SparseArrays"] + + [deps.Statistics.extensions] + SparseArraysExt = ["SparseArrays"] + +[[deps.StatsAPI]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "178ed29fd5b2a2cfc3bd31c13375ae925623ff36" +uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" +version = "1.8.0" + +[[deps.StatsBase]] +deps = ["AliasTables", "DataAPI", "DataStructures", "IrrationalConstants", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] +git-tree-sha1 = "c6f18e5a52a176a383f6f6c635e0f81feed1d6d4" +uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" +version = "0.34.11" + +[[deps.StatsFuns]] +deps = ["HypergeometricFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"] +git-tree-sha1 = "91f091a8716a6bb38417a6e6f274602a19aaa685" +uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c" +version = "1.5.2" +weakdeps = ["ChainRulesCore", "InverseFunctions"] + + [deps.StatsFuns.extensions] + StatsFunsChainRulesCoreExt = "ChainRulesCore" + StatsFunsInverseFunctionsExt = "InverseFunctions" + +[[deps.Stipple]] +deps = ["Dates", "FilePathsBase", "Genie", "GenieSession", "GenieSessionFileSession", "JSON", "Logging", "MacroTools", "Mixers", "Observables", "OrderedCollections", "Parameters", "Pkg", "PrecompileTools", "Random", "Reexport", "Requires", "StructTypes", "Tables", "UUIDs"] +git-tree-sha1 = "64e23643aa0588543d876ab471dca4e717bb5e60" +uuid = "4acbeb90-81a0-11ea-1966-bdaff8155998" +version = "0.31.59" +weakdeps = ["DataFrames", "OffsetArrays"] + + [deps.Stipple.extensions] + StippleDataFramesExt = "DataFrames" + StippleOffsetArraysExt = "OffsetArrays" + +[[deps.StipplePivotTable]] +deps = ["Stipple", "StippleUI", "Tables"] +git-tree-sha1 = "98d96b177125630eb5d273b3e705aec22bb4ec86" +uuid = "adab0226-ee3c-44de-8f2f-393b1bf1e936" +version = "0.4.3" + +[[deps.StipplePlotly]] +deps = ["DataFrames", "Genie", "Requires", "Stipple"] +git-tree-sha1 = "ebeddabf8bf4c6c34070bd4f74f96937cb884d00" +uuid = "ec984513-233d-481d-95b0-a3b58b97af2b" +version = "0.14.12" +weakdeps = ["PlotlyBase", "Plots"] + + [deps.StipplePlotly.extensions] + StipplePlotlyPlotlyBaseExt = "PlotlyBase" + StipplePlotlyPlotsExt = ["Plots", "PlotlyBase"] + +[[deps.StippleTable]] +deps = ["Stipple", "StippleUI"] +git-tree-sha1 = "f4a36ed4b56181d459b47bd16429308a03e05c1c" +uuid = "5bb4b094-0818-496d-ae94-fd777e10e8ba" +version = "1.0.3" + +[[deps.StippleTabs]] +deps = ["Stipple", "StippleUI"] +git-tree-sha1 = "cf1440b0d7510c98553ed75c7ba0842780a45319" +uuid = "29f11006-3202-4091-a17b-0a26282d76dd" +version = "1.1.0" + +[[deps.StippleUI]] +deps = ["Colors", "Dates", "Genie", "OrderedCollections", "PrecompileTools", "Stipple", "Tables"] +git-tree-sha1 = "af3df0a29e3615477b468b7b28db25e59c72ee21" +uuid = "a3c5d34a-b254-4859-a8fa-b86abb7e84a3" +version = "0.24.21" +weakdeps = ["DataFrames"] + + [deps.StippleUI.extensions] + StippleUIDataFramesExt = "DataFrames" + +[[deps.StringEncodings]] +deps = ["Libiconv_jll"] +git-tree-sha1 = "b765e46ba27ecf6b44faf70df40c57aa3a547dcb" +uuid = "69024149-9ee7-55f6-a4c4-859efe599b68" +version = "0.3.7" + +[[deps.StringManipulation]] +deps = ["PrecompileTools"] +git-tree-sha1 = "d05693d339e37d6ab134c5ab53c29fce5ee5d7d5" +uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e" +version = "0.4.4" + +[[deps.StructArrays]] +deps = ["ConstructionBase", "DataAPI", "Tables"] +git-tree-sha1 = "ad8002667372439f2e3611cfd14097e03fa4bccd" +uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" +version = "0.7.3" + + [deps.StructArrays.extensions] + StructArraysAdaptExt = "Adapt" + StructArraysGPUArraysCoreExt = ["GPUArraysCore", "KernelAbstractions"] + StructArraysLinearAlgebraExt = "LinearAlgebra" + StructArraysSparseArraysExt = "SparseArrays" + StructArraysStaticArraysExt = "StaticArrays" + + [deps.StructArrays.weakdeps] + Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" + GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" + KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + +[[deps.StructTypes]] +deps = ["Dates", "UUIDs"] +git-tree-sha1 = "159331b30e94d7b11379037feeb9b690950cace8" +uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" +version = "1.11.0" + +[[deps.StructUtils]] +deps = ["Dates", "UUIDs"] +git-tree-sha1 = "82bee338d650aa515f31866c460cb7e3bcef90b8" +uuid = "ec057cc2-7a8d-4b58-b3b3-92acb9f63b42" +version = "2.8.2" + + [deps.StructUtils.extensions] + StructUtilsMeasurementsExt = ["Measurements"] + StructUtilsStaticArraysCoreExt = ["StaticArraysCore"] + StructUtilsTablesExt = ["Tables"] + + [deps.StructUtils.weakdeps] + Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7" + StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" + Tables = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" + +[[deps.StyledStrings]] +uuid = "f489334b-da3d-4c2e-b8f0-e476e12c162b" +version = "1.11.0" + +[[deps.SuiteSparse]] +deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"] +uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" + +[[deps.SuiteSparse_jll]] +deps = ["Artifacts", "Libdl", "libblastrampoline_jll"] +uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" +version = "7.7.0+0" + +[[deps.TOML]] +deps = ["Dates"] +uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" +version = "1.0.3" + +[[deps.TableTraits]] +deps = ["IteratorInterfaceExtensions"] +git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" +uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" +version = "1.0.1" + +[[deps.Tables]] +deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "OrderedCollections", "TableTraits"] +git-tree-sha1 = "f2c1efbc8f3a609aadf318094f8fc5204bdaf344" +uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" +version = "1.12.1" + +[[deps.Tar]] +deps = ["ArgTools", "SHA"] +uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" +version = "1.10.0" + +[[deps.TensorCore]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" +uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" +version = "0.1.1" + +[[deps.Test]] +deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] +uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" +version = "1.11.0" + +[[deps.TextWrap]] +git-tree-sha1 = "43044b737fa70bc12f6105061d3da38f881a3e3c" +uuid = "b718987f-49a8-5099-9789-dcd902bef87d" +version = "1.0.2" + +[[deps.ThreadingUtilities]] +deps = ["ManualMemory"] +git-tree-sha1 = "7c73336785b21f723f5b143f6e99cf6c43b37dc1" +uuid = "8290d209-cae3-49c0-8002-c8c24d57dab5" +version = "0.5.6" + +[[deps.TiffImages]] +deps = ["CodecZstd", "ColorTypes", "DataStructures", "DocStringExtensions", "FileIO", "FixedPointNumbers", "IndirectArrays", "Inflate", "Mmap", "OffsetArrays", "PkgVersion", "PrecompileTools", "ProgressMeter", "SIMD", "UUIDs"] +git-tree-sha1 = "9ca5f1f2d42f80df4b8c9f6ab5a64f438bbd9976" +uuid = "731e570b-9d59-4bfa-96dc-6df516fadf69" +version = "0.11.9" + +[[deps.TiledIteration]] +deps = ["OffsetArrays", "StaticArrayInterface"] +git-tree-sha1 = "1176cc31e867217b06928e2f140c90bd1bc88283" +uuid = "06e1c1a7-607b-532d-9fad-de7d9aa2abac" +version = "0.5.0" + +[[deps.TranscodingStreams]] +git-tree-sha1 = "0c45878dcfdcfa8480052b6ab162cdd138781742" +uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" +version = "0.11.3" + +[[deps.TriplotBase]] +git-tree-sha1 = "4d4ed7f294cda19382ff7de4c137d24d16adc89b" +uuid = "981d1d27-644d-49a2-9326-4793e63143c3" +version = "0.1.0" + +[[deps.URIParser]] +deps = ["Unicode"] +git-tree-sha1 = "53a9f49546b8d2dd2e688d216421d050c9a31d0d" +uuid = "30578b45-9adc-5946-b283-645ec420af67" +version = "0.4.1" + +[[deps.URIs]] +git-tree-sha1 = "bef26fb046d031353ef97a82e3fdb6afe7f21b1a" +uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" +version = "1.6.1" + +[[deps.UUIDs]] +deps = ["Random", "SHA"] +uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" +version = "1.11.0" + +[[deps.UnPack]] +git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b" +uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" +version = "1.0.2" + +[[deps.Unicode]] +uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" +version = "1.11.0" + +[[deps.UnicodeFun]] +deps = ["REPL"] +git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf" +uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1" +version = "0.4.1" + +[[deps.Unitful]] +deps = ["Dates", "LinearAlgebra", "Random"] +git-tree-sha1 = "57e1b2c9de4bd6f40ecb9de4ac1797b81970d008" +uuid = "1986cc42-f94f-5a68-af5c-568840ba703d" +version = "1.28.0" + + [deps.Unitful.extensions] + ConstructionBaseUnitfulExt = "ConstructionBase" + ForwardDiffExt = "ForwardDiff" + InverseFunctionsUnitfulExt = "InverseFunctions" + LatexifyExt = ["Latexify", "LaTeXStrings"] + NaNMathExt = "NaNMath" + PrintfExt = "Printf" + + [deps.Unitful.weakdeps] + ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" + Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" + NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" + Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" + +[[deps.Unzip]] +git-tree-sha1 = "ca0969166a028236229f63514992fc073799bb78" +uuid = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d" +version = "0.2.0" + +[[deps.VectorizationBase]] +deps = ["ArrayInterface", "CPUSummary", "HostCPUFeatures", "IfElse", "LayoutPointers", "Libdl", "LinearAlgebra", "SIMDTypes", "Static", "StaticArrayInterface"] +git-tree-sha1 = "807a234dc5e6132dd6cf4c9317ca0917c4001ab3" +uuid = "3d5dd08c-fd9d-11e8-17fa-ed2836048c2f" +version = "0.21.74" + +[[deps.Vulkan_Loader_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXrandr_jll", "xkbcommon_jll"] +git-tree-sha1 = "2f0486047a07670caad3a81a075d2e518acc5c59" +uuid = "a44049a8-05dd-5a78-86c9-5fde0876e88c" +version = "1.3.243+0" + +[[deps.Wavelets]] +deps = ["DSP", "FFTW", "LinearAlgebra", "Reexport", "SpecialFunctions", "Statistics"] +git-tree-sha1 = "d0ec97a100abbe47a5e9a02361841da49cce6029" +uuid = "29a6e085-ba6d-5f35-a997-948ac2efa89a" +version = "0.10.1" + +[[deps.Wayland_jll]] +deps = ["Artifacts", "EpollShim_jll", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll"] +git-tree-sha1 = "96478df35bbc2f3e1e791bc7a3d0eeee559e60e9" +uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89" +version = "1.24.0+0" + +[[deps.WeakRefStrings]] +deps = ["DataAPI", "InlineStrings", "Parsers"] +git-tree-sha1 = "0716e01c3b40413de5dedbc9c5c69f27cddfddfc" +uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5" +version = "1.4.3" + +[[deps.WebP]] +deps = ["CEnum", "ColorTypes", "FileIO", "FixedPointNumbers", "ImageCore", "libwebp_jll"] +git-tree-sha1 = "aa1ca3c47f119fbdae8770c29820e5e6119b83f2" +uuid = "e3aaa7dc-3e4b-44e0-be63-ffb868ccd7c1" +version = "0.1.3" + +[[deps.WoodburyMatrices]] +deps = ["LinearAlgebra", "SparseArrays"] +git-tree-sha1 = "248a7031b3da79a127f14e5dc5f417e26f9f6db7" +uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6" +version = "1.1.0" + +[[deps.WorkerUtilities]] +git-tree-sha1 = "cd1659ba0d57b71a464a29e64dbc67cfe83d54e7" +uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60" +version = "1.6.1" + +[[deps.XML2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"] +git-tree-sha1 = "80d3930c6347cfce7ccf96bd3bafdf079d9c0390" +uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" +version = "2.13.9+0" + +[[deps.XZ_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b29c22e245d092b8b4e8d3c09ad7baa586d9f573" +uuid = "ffd25f8a-64ca-5728-b0f7-c24cf3aae800" +version = "5.8.3+0" + +[[deps.Xorg_libICE_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "a3ea76ee3f4facd7a64684f9af25310825ee3668" +uuid = "f67eecfb-183a-506d-b269-f58e52b52d7c" +version = "1.1.2+0" + +[[deps.Xorg_libSM_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libICE_jll"] +git-tree-sha1 = "9c7ad99c629a44f81e7799eb05ec2746abb5d588" +uuid = "c834827a-8449-5923-a945-d239c165b7dd" +version = "1.2.6+0" + +[[deps.Xorg_libX11_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll", "Xorg_xtrans_jll"] +git-tree-sha1 = "808090ede1d41644447dd5cbafced4731c56bd2f" +uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc" +version = "1.8.13+0" + +[[deps.Xorg_libXau_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "aa1261ebbac3ccc8d16558ae6799524c450ed16b" +uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec" +version = "1.0.13+0" + +[[deps.Xorg_libXcomposite_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXfixes_jll"] +git-tree-sha1 = "025180ce2163cdd71ba6e5a227bd06cf203b559c" +uuid = "3c9796d7-64a0-5134-86ad-79f8eb684845" +version = "0.4.7+0" + +[[deps.Xorg_libXcursor_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"] +git-tree-sha1 = "6c74ca84bbabc18c4547014765d194ff0b4dc9da" +uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724" +version = "1.2.4+0" + +[[deps.Xorg_libXdamage_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXfixes_jll"] +git-tree-sha1 = "45917154defafcbff585d6c04f323b5797da1ecf" +uuid = "0aeada51-83db-5f97-b67e-184615cfc6f6" +version = "1.1.7+0" + +[[deps.Xorg_libXdmcp_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "52858d64353db33a56e13c341d7bf44cd0d7b309" +uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05" +version = "1.1.6+0" + +[[deps.Xorg_libXext_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "1a4a26870bf1e5d26cd585e38038d399d7e65706" +uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3" +version = "1.3.8+0" + +[[deps.Xorg_libXfixes_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "75e00946e43621e09d431d9b95818ee751e6b2ef" +uuid = "d091e8ba-531a-589c-9de9-94069b037ed8" +version = "6.0.2+0" + +[[deps.Xorg_libXi_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll", "Xorg_libXfixes_jll"] +git-tree-sha1 = "a376af5c7ae60d29825164db40787f15c80c7c54" +uuid = "a51aa0fd-4e3c-5386-b890-e753decda492" +version = "1.8.3+0" + +[[deps.Xorg_libXinerama_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll"] +git-tree-sha1 = "0ba01bc7396896a4ace8aab67db31403c71628f4" +uuid = "d1454406-59df-5ea1-beac-c340f2130bc3" +version = "1.1.7+0" + +[[deps.Xorg_libXrandr_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll", "Xorg_libXrender_jll"] +git-tree-sha1 = "6c174ef70c96c76f4c3f4d3cfbe09d018bcd1b53" +uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484" +version = "1.5.6+0" + +[[deps.Xorg_libXrender_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "7ed9347888fac59a618302ee38216dd0379c480d" +uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa" +version = "0.9.12+0" + +[[deps.Xorg_libXtst_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll"] +git-tree-sha1 = "58c2e8f49733034d33b461d45a7e874b4135b644" +uuid = "b6f176f1-7aea-5357-ad67-1d3e565ea1c6" +version = "1.2.5+0" + +[[deps.Xorg_libpciaccess_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "58972370b81423fc546c56a60ed1a009450177c3" +uuid = "a65dc6b1-eb27-53a1-bb3e-dea574b5389e" +version = "0.19.0+0" + +[[deps.Xorg_libxcb_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXau_jll", "Xorg_libXdmcp_jll"] +git-tree-sha1 = "bfcaf7ec088eaba362093393fe11aa141fa15422" +uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b" +version = "1.17.1+0" + +[[deps.Xorg_libxkbfile_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "ed756a03e95fff88d8f738ebc2849431bdd4fd1a" +uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a" +version = "1.2.0+0" + +[[deps.Xorg_xcb_util_cursor_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_jll", "Xorg_xcb_util_renderutil_jll"] +git-tree-sha1 = "9750dc53819eba4e9a20be42349a6d3b86c7cdf8" +uuid = "e920d4aa-a673-5f3a-b3d7-f755a4d47c43" +version = "0.1.6+0" + +[[deps.Xorg_xcb_util_image_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_jll"] +git-tree-sha1 = "f4fc02e384b74418679983a97385644b67e1263b" +uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b" +version = "0.4.1+0" + +[[deps.Xorg_xcb_util_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll"] +git-tree-sha1 = "68da27247e7d8d8dafd1fcf0c3654ad6506f5f97" +uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5" +version = "0.4.1+0" + +[[deps.Xorg_xcb_util_keysyms_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_jll"] +git-tree-sha1 = "44ec54b0e2acd408b0fb361e1e9244c60c9c3dd4" +uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7" +version = "0.4.1+0" + +[[deps.Xorg_xcb_util_renderutil_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_jll"] +git-tree-sha1 = "5b0263b6d080716a02544c55fdff2c8d7f9a16a0" +uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e" +version = "0.3.10+0" + +[[deps.Xorg_xcb_util_wm_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_jll"] +git-tree-sha1 = "f233c83cad1fa0e70b7771e0e21b061a116f2763" +uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361" +version = "0.4.2+0" + +[[deps.Xorg_xkbcomp_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxkbfile_jll"] +git-tree-sha1 = "801a858fc9fb90c11ffddee1801bb06a738bda9b" +uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4" +version = "1.4.7+0" + +[[deps.Xorg_xkeyboard_config_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xkbcomp_jll"] +git-tree-sha1 = "ed349d26affcacafbc7fc2941ace1fb98f71e715" +uuid = "33bec58e-1273-512f-9401-5d533626f822" +version = "2.47.0+1" + +[[deps.Xorg_xtrans_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "a63799ff68005991f9d9491b6e95bd3478d783cb" +uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10" +version = "1.6.0+0" + +[[deps.YAML]] +deps = ["Base64", "Dates", "Printf", "StringEncodings"] +git-tree-sha1 = "a1c0c7585346251353cddede21f180b96388c403" +uuid = "ddb6d928-2868-570f-bddf-ab3f9cf99eb6" +version = "0.4.16" + +[[deps.Zlib_jll]] +deps = ["Libdl"] +uuid = "83775a58-1f1d-513f-b197-d71354ab007a" +version = "1.2.13+1" + +[[deps.Zstd_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "446b23e73536f84e8037f5dce465e92275f6a308" +uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" +version = "1.5.7+1" + +[[deps.at_spi2_atk_jll]] +deps = ["ATK_jll", "Artifacts", "JLLWrappers", "Libdl", "XML2_jll", "Xorg_libX11_jll", "at_spi2_core_jll"] +git-tree-sha1 = "249ab7c4da34d86d3d66b524705b1c07fe96b815" +uuid = "de012916-1e3f-58c2-8f29-df3ef51d412d" +version = "2.38.0+0" + +[[deps.at_spi2_core_jll]] +deps = ["Artifacts", "Dbus_jll", "Glib_jll", "JLLWrappers", "Libdl", "Xorg_libXtst_jll"] +git-tree-sha1 = "75a09aa217cbd6e81a8c337462a335ab78556bd7" +uuid = "0fc3237b-ac94-5853-b45c-d43d59a06200" +version = "2.60.3+0" + +[[deps.eudev_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c3b0e6196d50eab0c5ed34021aaa0bb463489510" +uuid = "35ca27e7-8b34-5b7f-bca9-bdc33f59eb06" +version = "3.2.14+0" + +[[deps.fzf_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b6a34e0e0960190ac2a4363a1bd003504772d631" +uuid = "214eeab7-80f7-51ab-84ad-2988db7cef09" +version = "0.61.1+0" + +[[deps.gdk_pixbuf_jll]] +deps = ["Artifacts", "Glib_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Xorg_libX11_jll", "libpng_jll"] +git-tree-sha1 = "895f21b699121d1a57ecac57e65a852caf569254" +uuid = "da03df04-f53b-5353-a52f-6a8b0620ced0" +version = "2.42.13+0" + +[[deps.iso_codes_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6d3b2c8a4870c50f41bbd58131ed9af581c675b5" +uuid = "bf975903-5238-5d20-8243-bc370bc1e7e5" +version = "4.20.1+0" + +[[deps.isoband_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "51b5eeb3f98367157a7a12a1fb0aa5328946c03c" +uuid = "9a68df92-36a6-505f-a73e-abb412b6bfb4" +version = "0.2.3+0" + +[[deps.libaom_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "850b06095ee71f0135d644ffd8a52850699581ed" +uuid = "a4ae2306-e953-59d6-aa16-d00cac43593b" +version = "3.13.3+0" + +[[deps.libass_jll]] +deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "125eedcb0a4a0bba65b657251ce1d27c8714e9d6" +uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0" +version = "0.17.4+0" + +[[deps.libblastrampoline_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" +version = "5.11.0+0" + +[[deps.libdecor_jll]] +deps = ["Artifacts", "Dbus_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pango_jll", "Wayland_jll", "xkbcommon_jll"] +git-tree-sha1 = "9bf7903af251d2050b467f76bdbe57ce541f7f4f" +uuid = "1183f4f0-6f2a-5f1a-908b-139f9cdfea6f" +version = "0.2.2+0" + +[[deps.libdrm_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libpciaccess_jll"] +git-tree-sha1 = "63aac0bcb0b582e11bad965cef4a689905456c03" +uuid = "8e53e030-5e6c-5a89-a30b-be5b7263a166" +version = "2.4.125+1" + +[[deps.libevdev_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "56d643b57b188d30cccc25e331d416d3d358e557" +uuid = "2db6ffa8-e38f-5e21-84af-90c45d0032cc" +version = "1.13.4+0" + +[[deps.libfdk_aac_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "646634dd19587a56ee2f1199563ec056c5f228df" +uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280" +version = "2.0.4+0" + +[[deps.libinput_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "eudev_jll", "libevdev_jll", "mtdev_jll"] +git-tree-sha1 = "91d05d7f4a9f67205bd6cf395e488009fe85b499" +uuid = "36db933b-70db-51c0-b978-0f229ee0e533" +version = "1.28.1+0" + +[[deps.libpng_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "e51150d5ab85cee6fc36726850f0e627ad2e4aba" +uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f" +version = "1.6.58+0" + +[[deps.libsixel_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "libpng_jll"] +git-tree-sha1 = "c1733e347283df07689d71d61e14be986e49e47a" +uuid = "075b6546-f08a-558a-be8f-8157d0f608a5" +version = "1.10.5+0" + +[[deps.libva_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "libdrm_jll"] +git-tree-sha1 = "7dbf96baae3310fe2fa0df0ccbb3c6288d5816c9" +uuid = "9a156e7d-b971-5f62-b2c9-67348b8fb97c" +version = "2.23.0+0" + +[[deps.libvorbis_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll"] +git-tree-sha1 = "11e1772e7f3cc987e9d3de991dd4f6b2602663a5" +uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a" +version = "1.3.8+0" + +[[deps.libwebp_jll]] +deps = ["Artifacts", "Giflib_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libglvnd_jll", "Libtiff_jll", "libpng_jll"] +git-tree-sha1 = "4e4282c4d846e11dce56d74fa8040130b7a95cb3" +uuid = "c5f90fcd-3b7e-5836-afba-fc50a0988cb2" +version = "1.6.0+0" + +[[deps.libzip_jll]] +deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "OpenSSL_jll", "XZ_jll", "Zlib_jll", "Zstd_jll"] +git-tree-sha1 = "86addc139bca85fdf9e7741e10977c45785727b7" +uuid = "337d8026-41b4-5cde-a456-74a10e5b31d1" +version = "1.11.3+0" + +[[deps.mtdev_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b4d631fd51f2e9cdd93724ae25b2efc198b059b1" +uuid = "009596ad-96f7-51b1-9f1b-5ce2d5e8a71e" +version = "1.1.7+0" + +[[deps.nghttp2_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" +version = "1.59.0+0" + +[[deps.oneTBB_jll]] +deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl"] +git-tree-sha1 = "da8c1f6eee04831f14edcfa5dae611d309807e57" +uuid = "1317d2d5-d96f-522e-a858-c73665f53c3e" +version = "2022.3.0+0" + +[[deps.p7zip_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" +version = "17.4.0+2" + +[[deps.x264_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "14cc7083fc6dff3cc44f2bc435ee96d06ed79aa7" +uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a" +version = "10164.0.1+0" + +[[deps.x265_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e7b67590c14d487e734dcb925924c5dc43ec85f3" +uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76" +version = "4.1.0+0" + +[[deps.xkbcommon_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"] +git-tree-sha1 = "a1fc6507a40bf504527d0d4067d718f8e179b2b8" +uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd" +version = "1.13.0+0" diff --git a/run_full_pipeline.sh b/run_full_pipeline.sh new file mode 100755 index 0000000..07e87dc --- /dev/null +++ b/run_full_pipeline.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# ============================================================================= +# run_full_pipeline.sh -- seven-stage MSI pipeline (one or many datasets) +# +# bash run_full_pipeline.sh # every dataset under datos_para_ai/ +# bash run_full_pipeline.sh Datura_leaf # a single dataset +# MSI_K=5 bash run_full_pipeline.sh Datura_leaf +# +# Each dataset lives in datos_para_ai// 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/datos_para_ai}" +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 datos_para_ai//.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 + if ls "$d"*.imzML "$d"*.imzml >/dev/null 2>&1; then basename "$d"; fi + done | sort) +fi + +if [ "${#DATASETS[@]}" -eq 0 ]; then + echo "ERROR: no datasets with an .imzML found under '$DATA_ROOT'." >&2 + 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/" diff --git a/scripts_julia/plot_mass_spectra.jl b/scripts_julia/plot_mass_spectra.jl index aa9dadc..90ea909 100644 --- a/scripts_julia/plot_mass_spectra.jl +++ b/scripts_julia/plot_mass_spectra.jl @@ -13,7 +13,9 @@ using CSV, DataFrames, Statistics using Plots.Measures 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/datos_para_ai/Datura_leaf`. +data_dir = length(ARGS) >= 2 ? ARGS[2] : joinpath(project_root, "datos_para_ai", dataset_name) output_dir = joinpath(project_root, "outputs", dataset_name) figures_dir = joinpath(output_dir, "figures") cluster_csv = joinpath(output_dir, "msi_clusters_results.csv") diff --git a/scripts_python/make_ion_carpet.py b/scripts_python/make_ion_carpet.py index b4ac51f..2ff79a1 100644 --- a/scripts_python/make_ion_carpet.py +++ b/scripts_python/make_ion_carpet.py @@ -103,10 +103,12 @@ def main(): ap.add_argument("dataset") 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("--data-dir", default=None, + help="dataset directory (default: /datos_para_ai/)") args = ap.parse_args() root = os.path.dirname(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, "datos_para_ai", args.dataset) viridis_dir = os.path.join(root, "outputs", "ion_images_viridis", args.dataset) ions = load_ions(viridis_dir, args.tile_size, args.dataset) out_dir = os.path.join(root, "outputs", args.dataset, "figures") diff --git a/scripts_python/msi_preprocess_python.py b/scripts_python/msi_preprocess_python.py index 5e3d669..1494e4a 100644 --- a/scripts_python/msi_preprocess_python.py +++ b/scripts_python/msi_preprocess_python.py @@ -214,7 +214,7 @@ def extract_ion_images(spectra_info, ibd_path, target_mzs, tolerance, mz_format, return exported 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, "datos_para_ai", "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) diff --git a/src/BloomFilters.jl b/src/BloomFilters.jl new file mode 100644 index 0000000..3570da7 --- /dev/null +++ b/src/BloomFilters.jl @@ -0,0 +1,279 @@ +# 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 + h1 = hash(item, seed) + h2 = hash(item, 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 diff --git a/src/Common.jl b/src/Common.jl new file mode 100644 index 0000000..629aed2 --- /dev/null +++ b/src/Common.jl @@ -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{Float64} + +Creates an empty Bloom filter for spectra with no data. + +# Returns: +- An empty `BloomFilter{Float64}`. +""" +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 diff --git a/src/ImageProcessing.jl b/src/ImageProcessing.jl new file mode 100644 index 0000000..d47ea6a --- /dev/null +++ b/src/ImageProcessing.jl @@ -0,0 +1,109 @@ +# 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 if it's a color image + gray_img = Gray.(img) + + # 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. + smoothing_kernel = ones(Bool, (smoothing, smoothing)) + 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 diff --git a/src/LICENSE b/src/LICENSE new file mode 100644 index 0000000..675aa01 --- /dev/null +++ b/src/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2025 The LabABI, Cinvestav Irapuato, Mexico, + +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. diff --git a/src/MSIData.jl b/src/MSIData.jl new file mode 100644 index 0000000..1e88fa3 --- /dev/null +++ b/src/MSIData.jl @@ -0,0 +1,1772 @@ +# src/MSIData.jl + +""" +This file defines the unified MSIData object and the associated data access layer, +including caching and iteration logic, for handling large mzML and imzML datasets +efficiently. +""" + +using Base64, Libz, Serialization, Printf, DataFrames, Base.Threads, StatsBase, Mmap + +const FILE_HANDLE_LOCK = ReentrantLock() + + +# Abstract type for different data sources (e.g., mzML, imzML) +# This allows dispatching to the correct binary reading logic. +abstract type MSDataSource end + +# Concrete type for imzML data sources +""" + ImzMLSource <: MSDataSource + +A data source for `.imzML` files, holding a handle to the binary `.ibd` file +and the expected format for m/z and intensity arrays. +""" +struct ImzMLSource <: MSDataSource + ibd_handles::Vector{IO} # HandlePool: One handle per thread + mz_format::Type + intensity_format::Type + mmap_data::Union{Vector{UInt8}, Nothing} + is_any_compressed::Bool # Cached for zero-allocation dispatch +end + +""" + MzMLSource <: MSDataSource + +A data source for `.mzML` files, holding a handle to the `.mzML` file itself +(which contains the binary data encoded in Base64) and the expected data formats. +""" +struct MzMLSource <: MSDataSource + file_handles::Vector{IO} # HandlePool: One handle per thread + mz_format::Type + intensity_format::Type + mmap_data::Union{Vector{UInt8}, Nothing} +end + +# --- HandlePool Helpers --- # +""" + get_handle(source::ImzMLSource) -> IO + get_handle(source::MzMLSource) -> IO + +Retrieves a thread-local file handle from the source's pool. +""" +function get_handle(source::ImzMLSource) + tid = Threads.threadid() + if tid <= length(source.ibd_handles) + return source.ibd_handles[tid] + else + return source.ibd_handles[1] + end +end + +function get_handle(source::MzMLSource) + tid = Threads.threadid() + if tid <= length(source.file_handles) + return source.file_handles[tid] + else + return source.file_handles[1] + end +end + +""" + SpectrumAsset + +Contains metadata for a single binary data array (m/z or intensity) within a spectrum. + +# Fields +- `format`: The data type of the elements (e.g., `Float32`, `Int64`). +- `is_compressed`: A boolean flag indicating if the data is compressed (e.g., with zlib). +- `offset`: The byte offset of the data within the file (`.ibd` for imzML, `.mzML` for mzML). +- `encoded_length`: The length of the data, which has different meanings depending on the format: + - **Uncompressed imzML**: The number of elements (points) in the array. + - **Compressed imzML**: The number of bytes of the compressed data chunk in the `.ibd` file. + - **mzML**: The number of characters in the Base64 encoded string within the `.mzML` file. +- `axis_type`: A symbol (`:mz` or `:intensity`) indicating the type of data. +""" +struct SpectrumAsset + format::Type + is_compressed::Bool + offset::Int64 + encoded_length::Int32 + # For mzML, axis_type is needed to distinguish mz from intensity. + # For imzML, this can be ignored as the order is fixed. + axis_type::Symbol + + # Pre-computed analytics + min_val::Float64 + max_val::Float64 +end + +""" + SpectrumMode + +An enum representing the type of a spectrum's data. + +- `CENTROID`: The spectrum contains centroided data (i.e., processed peaks). +- `PROFILE`: The spectrum contains raw profile data. +- `UNKNOWN`: The spectrum type is not specified. +""" +@enum SpectrumMode CENTROID=1 PROFILE=2 UNKNOWN=3 + +""" + InstrumentMetadata + +Contains metadata about the instrument configuration and acquisition parameters. +This information is parsed from the file header and is crucial for guiding +preprocessing steps. + +# Fields +- `resolution`: Instrument resolution at a specific m/z, if available. +- `acquisition_mode`: The overall data acquisition mode (`:profile`, `:centroid`, or `:mixed`). +- `mz_axis_type`: The nature of the m/z axis (`:regular`, `:irregular`, `:mixed`). +- `calibration_status`: The calibration state of the data (`:internal`, `:external`, `:uncalibrated`). +- `instrument_model`: The vendor and model of the instrument. +- `mass_accuracy_ppm`: Manufacturer-specified mass accuracy in parts-per-million. +- `laser_settings`: A dictionary of MSI-specific laser parameters. +- `polarity`: The polarity of the acquisition (`:positive`, `:negative`, `:unknown`). +""" +struct InstrumentMetadata + resolution::Union{Float64, Nothing} + acquisition_mode::Symbol + mz_axis_type::Symbol + calibration_status::Symbol + instrument_model::String + mass_accuracy_ppm::Union{Float64, Nothing} + laser_settings::Union{Dict, Nothing} + polarity::Symbol + vendor_preprocessing_steps::Union{Vector{String}, Nothing} # New field for provenance +end + +# Default constructor for initializing with unknown values +function InstrumentMetadata() + return InstrumentMetadata( + nothing, # resolution + :unknown, # acquisition_mode + :unknown, # mz_axis_type + :uncalibrated, # calibration_status + "Not Available",# instrument_model + nothing, # mass_accuracy_ppm + nothing, # laser_settings + :unknown, # polarity + nothing # vendor_preprocessing + ) +end + +""" + SpectrumMetadata + +Contains all metadata for a single spectrum, common to both imzML and mzML formats. + +# Fields +- `x`, `y`: The spatial coordinates of the spectrum (for imzML only). +- `id`: The unique identifier string for the spectrum (for mzML only). +- `mode`: The spectrum mode (`CENTROID` or `PROFILE`). +- `mz_asset`: A `SpectrumAsset` for the m/z array. +- `int_asset`: A `SpectrumAsset` for the intensity array. +""" +struct SpectrumMetadata + # For imzML + x::Int32 + y::Int32 + + # For mzML + id::String + type::Symbol # NEW: e.g., :sample, :blank, :qc + + mode::SpectrumMode + # Common binary data info + mz_asset::SpectrumAsset + int_asset::SpectrumAsset +end + +""" + SpectrumMetadataBinary + +A fixed-size version of SpectrumMetadata for high-speed binary serialization. +Used for the metadata cache (.cache files). +""" +struct SpectrumMetadataBinary + x::Int32 + y::Int32 + mode::Int8 + mz_offset::Int64 + mz_encoded_len::Int32 + int_offset::Int64 + int_encoded_len::Int32 + min_mz::Float32 # Persistent analytics + max_mz::Float32 # Persistent analytics +end + +""" + MSIData + +The primary object for interacting with mass spectrometry data. It provides a unified +interface for both `.mzML` and `.imzML` files and includes an LRU cache for +efficient repeated access to spectra. + +# Fields +- `source`: The underlying `MSDataSource` (`ImzMLSource` or `MzMLSource`). +- `spectra_metadata`: A vector of `SpectrumMetadata` for all spectra in the file. +- `image_dims`: A tuple `(width, height)` of the spatial dimensions (for imzML). +- `coordinate_map`: A matrix mapping `(x, y)` coordinates to a linear spectrum index (for imzML). +- `cache`: A dictionary holding cached spectra, mapping index to `(mz, intensity)`. +- `cache_order`: A vector of indices tracking usage for the LRU cache policy. +- `cache_size`: The maximum number of spectra to store in the cache. +- `cache_lock`: A `ReentrantLock` to ensure thread-safe access to the cache. +- `global_min_mz`: Cached global minimum m/z value across all spectra. +- `global_max_mz`: Cached global maximum m/z value across all spectra. +- `spectrum_stats_df`: A `DataFrame` containing pre-computed per-spectrum analytics (e.g., TIC, BPI). +""" +mutable struct MSIData + source::MSDataSource + spectra_metadata::Vector{SpectrumMetadata} + instrument_metadata::Union{InstrumentMetadata, Nothing} + image_dims::Tuple{Int, Int} + coordinate_map::Union{Matrix{Int}, Nothing} + + # LRU Cache for GetSpectrum + cache::Dict{Int, Tuple{Vector{Float64}, Vector{Float64}}} + cache_order::Vector{Int} + cache_size::Int + cache_lock::ReentrantLock + + # Buffer Pool for binary data operations + buffer_pool::SimpleBufferPool # Existing UInt8 pool (mostly for mzML base64) + + # Pre-computed analytics/metadata - use Base.Threads.Atomic for compatibility + global_min_mz::Base.Threads.Atomic{Float64} + global_max_mz::Base.Threads.Atomic{Float64} + spectrum_stats_df::Union{DataFrame, Nothing} + bloom_filters::Union{Vector{Union{BloomFilter{Int}, Nothing}}, Nothing} + analytics_ready::AtomicFlag + preprocessing_hints::Union{Dict{Symbol, Any}, Nothing} # For auto-determined parameters + + function MSIData(source, metadata, instrument_meta, dims, coordinate_map, cache_size) + obj = new(source, metadata, instrument_meta, dims, coordinate_map, + Dict(), [], min(10, cache_size), ReentrantLock(), + SimpleBufferPool(), + Base.Threads.Atomic{Float64}(0.0), Base.Threads.Atomic{Float64}(0.0), + nothing, nothing, AtomicFlag(), nothing) + + # Initialize mz bounds cleanly instead of Inf + Base.Threads.atomic_xchg!(obj.global_min_mz, 1e9) + Base.Threads.atomic_xchg!(obj.global_max_mz, -1e9) + + + # Ensure all file handles in the pool are closed when the object is garbage collected + finalizer(obj) do o + if o.source isa ImzMLSource + for h in o.source.ibd_handles + isopen(h) && close(h) + end + elseif o.source isa MzMLSource + for h in o.source.file_handles + isopen(h) && close(h) + end + end + end + return obj + end +end + +""" + set_global_mz_range!(data::MSIData, min_mz::Float64, max_mz::Float64) + +Sets the global m/z range for the MSIData object. + +# Arguments + +- `data::MSIData`: The MSIData object. +- `min_mz::Float64`: The minimum m/z value. +- `max_mz::Float64`: The maximum m/z value. + +# Returns +- `nothing` +""" +function set_global_mz_range!(data::MSIData, min_mz::Float64, max_mz::Float64) + Base.Threads.atomic_xchg!(data.global_min_mz, min_mz) + Base.Threads.atomic_xchg!(data.global_max_mz, max_mz) +end + +""" + get_global_mz_range(data::MSIData) + +Gets the global m/z range for the MSIData object. + +# Arguments + +- `data::MSIData`: The MSIData object. + +# Returns +- `(min_mz, max_mz)`: The global m/z range. +""" +function get_global_mz_range(data::MSIData) + # Atomic read using atomic_add! with zero + min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0) + max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0) + return (min_mz, max_mz) +end + +""" + set_analytics_data!(data::MSIData, stats_df::DataFrame, bloom_filters::Vector) + +Sets the analytics data for the MSIData object. + +# Arguments + +- `data::MSIData`: The MSIData object. +- `stats_df::DataFrame`: The statistics DataFrame. +- `bloom_filters::Vector`: The bloom filters. + +# Returns +- `nothing` +""" +function set_analytics_data!(data::MSIData, stats_df::DataFrame, bloom_filters::Vector) + lock(data.cache_lock) do + data.spectrum_stats_df = stats_df + data.bloom_filters = bloom_filters + end +end + +""" + get_bloom_filters(data::MSIData) + +Gets the bloom filters for the MSIData object. + +# Arguments + +- `data::MSIData`: The MSIData object. + +# Returns +- `bloom_filters::Vector`: The bloom filters. +""" +function get_bloom_filters(data::MSIData) + lock(data.cache_lock) do + return data.bloom_filters + end +end + +""" + get_spectrum_stats(data::MSIData) + +Gets the spectrum statistics for the MSIData object. + +# Arguments + +- `data::MSIData`: The MSIData object. + +# Returns +- `stats_df::DataFrame`: The statistics DataFrame. +""" +function get_spectrum_stats(data::MSIData) + return data.spectrum_stats_df +end + +""" + Base.close(data::MSIData) + +Explicitly closes the file handles associated with the `MSIData` object and clears the spectrum cache. +It is good practice to call this method when you are finished with an `MSIData` object to release resources immediately. + +# Arguments + +- `data::MSIData`: The MSIData object. + +# Returns +- `nothing` +""" +function Base.close(data::MSIData) + if data.source isa ImzMLSource + for handle in data.source.ibd_handles + isopen(handle) && close(handle) + end + elseif data.source isa MzMLSource + for handle in data.source.file_handles + isopen(handle) && close(handle) + end + end + + # Clear cache + empty!(data.cache) + empty!(data.cache_order) + + println("MSIData object closed and resources released.") +end + + + +""" + get_masked_spectrum_indices(data::MSIData, mask_matrix::BitMatrix) -> Set{Int} + +Converts a 2D boolean mask matrix (e.g., loaded from a PNG) into a `Set` of linear +spectrum indices that fall within the `true` regions of the mask. + +# Arguments +- `data`: The `MSIData` object containing the `coordinate_map`. +- `mask_matrix`: A `BitMatrix` where `true` indicates a pixel is part of the ROI. + +# Returns +- A `Set{Int}` containing the linear indices of spectra within the mask. +""" +function get_masked_spectrum_indices(data::MSIData, mask_matrix::BitMatrix) + if data.coordinate_map === nothing + throw(ArgumentError("Coordinate map not available. Cannot apply mask to non-imaging data.")) + end + + width, height = data.image_dims + mask_height, mask_width = size(mask_matrix) + + if mask_width != width || mask_height != height + throw(ArgumentError("Mask dimensions ($(mask_width)x$(mask_height)) do not match image dimensions ($(width)x$(height)).")) + end + + masked_indices = Set{Int}() + for y in 1:height + for x in 1:width + if mask_matrix[y, x] # If this pixel is part of the mask + idx = data.coordinate_map[x, y] + if idx != 0 # Ensure there's an actual spectrum at this coordinate + push!(masked_indices, idx) + end + end + end + end + return masked_indices +end + + +# --- Internal function for reading binary data --- # + +""" + read_binary_vector(io::IO, asset::SpectrumAsset) + +Reads and decodes a single binary data vector (e.g., m/z or intensity array) +from a `.mzML` file. The data is expected to be Base64-encoded and may be +compressed. + +This internal function handles: +1. Reading the raw Base64 string from the file at the specified offset. +2. Decoding the Base64 string into bytes. +3. Decompressing the bytes using zlib if `asset.is_compressed` is true. +4. Interpreting the resulting bytes as a vector of the specified format. + +Note: Byte order conversion (e.g., from little-endian to host) is not performed +by this function and is assumed to be handled by the caller if necessary. + +# Arguments +- `io`: The IO stream of the `.mzML` file. +- `asset`: The `SpectrumAsset` containing metadata for the array. + +# Returns +- A `Vector` of the appropriate type containing the decoded data. +""" +function read_binary_vector(data::MSIData, io::IO, asset::SpectrumAsset) + if asset.offset < 0 + throw(FileFormatError("Invalid asset offset: $(asset.offset)")) + end + + # Use mmap view if available for Base64 (mzML) + b64_string = (data.source isa MzMLSource && data.source.mmap_data !== nothing) ? + String(view(data.source.mmap_data, (asset.offset + 1):(asset.offset + asset.encoded_length))) : + String(read(seek(io, asset.offset), asset.encoded_length)) + + local decoded_bytes::Vector{UInt8} + + if asset.is_compressed + temp_decoded = Base64.base64decode(b64_string) + decoded_bytes = Libz.inflate(temp_decoded) + else + decoded_bytes = Base64.base64decode(b64_string) + end + + alignment = sizeof(asset.format) + n_elements = length(decoded_bytes) ÷ alignment + + if n_elements * alignment != length(decoded_bytes) + throw(FileFormatError("Size of decoded byte array is not a multiple of the element size.")) + end + + reinterpreted_array = reinterpret(asset.format, decoded_bytes) + + # Optimization: Use a temporary array for byte order conversion. + # We could use the ResourcePool here if we wanted to return a Float64 vector, + # but currently we return the native format. + out_array = [ltoh(x) for x in reinterpreted_array] + + return out_array +end + + + +# Overload for different source types +""" + read_spectrum_from_disk(source::ImzMLSource, meta::SpectrumMetadata) + +Reads a single spectrum's m/z and intensity arrays directly from the `.ibd` +binary file for an `.imzML` dataset. It handles reading the raw binary data +and converting it from little-endian to the host's native byte order. + +# Arguments +- `source`: An `ImzMLSource` containing the file handle and data formats. +- `meta`: The `SpectrumMetadata` for the spectrum to be read. + +# Returns +- A tuple `(mz, intensity)` containing the two requested data arrays. +""" +@inline function read_spectrum_from_disk(source::ImzMLSource, meta::SpectrumMetadata) + # 1. Use Mmap logic if available (implemented in previous step) + if source.mmap_data !== nothing + mz_offset = meta.mz_asset.offset + mz_byte_len = sizeof(source.mz_format) * meta.mz_asset.encoded_length + int_offset = meta.int_asset.offset + int_byte_len = sizeof(source.intensity_format) * meta.int_asset.encoded_length + + mz_view_raw = view(source.mmap_data, (mz_offset + 1):(mz_offset + mz_byte_len)) + int_view_raw = view(source.mmap_data, (int_offset + 1):(int_offset + int_byte_len)) + + mz_reinterpreted = reinterpret(source.mz_format, mz_view_raw) + int_reinterpreted = reinterpret(source.intensity_format, int_view_raw) + + # TRUE Zero-copy logic: avoid allocations if host matches file endianness (LE for .ibd) + if Base.ENDIAN_BOM == 0x04030201 # Little Endian Host (Common for Linux/X86) + mz = mz_reinterpreted + intensity = int_reinterpreted + else + # On Big Endian hosts, we MUST allocate and byte-swap + mz = ltoh.(mz_reinterpreted) + intensity = ltoh.(int_reinterpreted) + end + + validate_spectrum_data(mz, intensity, meta.id) + return mz, intensity + end + + # 2. Use HandlePool logic if Mmap is not available + handle = get_handle(source) + + mz = Array{source.mz_format}(undef, meta.mz_asset.encoded_length) + intensity = Array{source.intensity_format}(undef, meta.int_asset.encoded_length) + + # Note: No lock() required here because we are using a thread-local handle! + seek(handle, meta.mz_asset.offset) + read!(handle, mz) + + seek(handle, meta.int_asset.offset) + read!(handle, intensity) + + mz .= ltoh.(mz) + intensity .= ltoh.(intensity) + + validate_spectrum_data(mz, intensity, meta.id) + return mz, intensity +end + +""" + read_spectrum_from_disk(source::MzMLSource, meta::SpectrumMetadata) + +Reads a single spectrum's m/z and intensity arrays from a `.mzML` file. +This is a high-level function that orchestrates the reading process by calling +`read_binary_vector` for each of the m/z and intensity arrays. + +# Arguments +- `source`: A `MzMLSource` containing the file handle. +- `meta`: The `SpectrumMetadata` for the spectrum to be read. + +# Returns +- A tuple `(mz, intensity)` containing the two requested data arrays. +""" +function read_spectrum_from_disk(data::MSIData, source::MzMLSource, meta::SpectrumMetadata) + handle = get_handle(source) + # For mzML, data is Base64 encoded within the XML + mz = read_binary_vector(data, handle, meta.mz_asset) + intensity = read_binary_vector(data, handle, meta.int_asset) + + mz_f64, intensity_f64 = Float64.(mz), Float64.(intensity) + + validate_spectrum_data(mz, intensity, meta.id) + + return mz, intensity +end + +# --- Metadata Caching (Sprint 1: Milestone 4) --- # + +""" + save_metadata_cache(data::MSIData, cache_path::String) + +Serializes the spectrum metadata to a custom binary format for near-instant loading. +""" +function save_metadata_cache(data::MSIData, cache_path::String) + open(cache_path, "w") do io + # Write magic number and version (v2 adds min_mz/max_mz to SpectrumMetadataBinary) + write(io, "JMSI") + write(io, Int32(2)) + + # Write number of spectra + num_spectra = length(data.spectra_metadata) + write(io, Int32(num_spectra)) + + # Write global formats (assuming uniform for now) + # We'll write the names of the types as strings for safety + write(io, string(data.source.mz_format)) + write(io, "\n") + write(io, string(data.source.intensity_format)) + write(io, "\n") + + # Convert to binary structs and write in one block + binary_metadata = Vector{SpectrumMetadataBinary}(undef, num_spectra) + for i in 1:num_spectra + m = data.spectra_metadata[i] + binary_metadata[i] = SpectrumMetadataBinary( + m.x, m.y, Int8(m.mode), + m.mz_asset.offset, m.mz_asset.encoded_length, + m.int_asset.offset, m.int_asset.encoded_length, + Float32(m.mz_asset.min_val), Float32(m.mz_asset.max_val) + ) + end + write(io, binary_metadata) + end + @debug "Metadata cache saved to $cache_path" +end + +""" + load_metadata_cache(cache_path::String, mz_format::Type, int_format::Type) -> Vector{SpectrumMetadata} + +Loads spectrum metadata from a custom binary cache file. +""" +function load_metadata_cache(cache_path::String, mz_format::Type, int_format::Type) + open(cache_path, "r") do io + magic = read(io, 4) + if String(magic) != "JMSI" + error("Invalid cache file format.") + end + version = read(io, Int32) + if version != 2 + error("Unsupported cache version $version (expected 2). Delete the .cache file to regenerate.") + end + num_spectra = read(io, Int32) + + # Skip format strings (we already have them from the header or caller) + readline(io) + readline(io) + + # Read all binary metadata in one swoop + binary_metadata = Vector{SpectrumMetadataBinary}(undef, num_spectra) + read!(io, binary_metadata) + + # Convert back to SpectrumMetadata + spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra) + for i in 1:num_spectra + b = binary_metadata[i] + mz_asset = SpectrumAsset(mz_format, false, b.mz_offset, b.mz_encoded_len, :mz, Float64(b.min_mz), Float64(b.max_mz)) + int_asset = SpectrumAsset(int_format, false, b.int_offset, b.int_encoded_len, :intensity, 0.0, 0.0) + + spectra_metadata[i] = SpectrumMetadata( + b.x, b.y, "", :sample, SpectrumMode(b.mode), + mz_asset, int_asset + ) + end + return spectra_metadata + end +end + +# --- Public API --- # + +""" + GetSpectrum(data::MSIData, index::Int) + +Retrieves a single spectrum by its index, utilizing a thread-safe LRU cache for performance. + +If the spectrum is not in the cache, it is read from disk, and the cache is updated. +This function is the core of the "Indexed" and "Cache" access patterns. + +# Arguments +- `data`: The `MSIData` object. +- `index`: The linear index of the spectrum to retrieve. + +# Returns +- A tuple `(mz, intensity)` containing the spectrum's data arrays. +""" +function GetSpectrum(data::MSIData, index::Int) + if index < 1 || index > length(data.spectra_metadata) + throw(SpectrumNotFoundError(index)) + end + + # Phase 1: Check the cache (with lock) + lock(data.cache_lock) + try + if haskey(data.cache, index) + # Cache Hit: Move item to the end of the LRU list and return from cache + filter!(x -> x != index, data.cache_order) + push!(data.cache_order, index) + return data.cache[index] + end + finally + unlock(data.cache_lock) + end + + # Phase 2: Cache Miss - Read from disk (no lock) + meta = data.spectra_metadata[index] + + local spectrum + if data.source isa ImzMLSource + spectrum = read_spectrum_from_disk(data.source, meta) + else # MzMLSource + spectrum = read_spectrum_from_disk(data, data.source, meta) + end + + # Phase 3: Update cache (with lock) and get final value + return lock(data.cache_lock) do + if haskey(data.cache, index) + # Another thread got here first, use its result + return data.cache[index] + end + + # This thread is first to update cache + if data.cache_size > 0 + if length(data.cache) >= data.cache_size + # Evict the least recently used item (at the front of the list) + lru_index = popfirst!(data.cache_order) + delete!(data.cache, lru_index) + end + data.cache[index] = spectrum + push!(data.cache_order, index) + end + return spectrum + end +end + +""" + GetSpectrum(data::MSIData, x::Int, y::Int) + +Retrieves a single spectrum by its (x, y) coordinates for imaging data (`.imzML`). +This method uses the `coordinate_map` for efficient index lookup and then calls +the indexed `GetSpectrum` method, benefiting from caching. + +# Arguments +- `data`: The `MSIData` object. +- `x`: The x-coordinate of the spectrum. +- `y`: The y-coordinate of the spectrum. + +# Returns +- A tuple `(mz, intensity)` containing the spectrum's data arrays. +""" +function GetSpectrum(data::MSIData, x::Int, y::Int) + if data.coordinate_map === nothing + throw(ArgumentError("Coordinate map not available. This method is only for imaging data loaded from .imzML files.")) + end + width, height = data.image_dims + if x < 1 || x > width || y < 1 || y > height + throw(ArgumentError("Coordinates ($x, $y) out of bounds for image dimensions ($width, $height).")) + end + + index = data.coordinate_map[x, y] + if index == 0 + throw(SpectrumNotFoundError((x, y))) + end + + return GetSpectrum(data, index) # Call the existing method +end + +""" + process_spectrum(f::Function, data::MSIData, index::Int) + +A "function barrier" helper for safely processing a single spectrum. + +This function retrieves a spectrum and then immediately calls the provided function `f` +with the resulting `(mz, intensity)` arrays. While the `GetSpectrum` API is now type-stable, +this pattern remains good practice for separating data access from data processing. + +Use this function when you need to perform performance-critical operations on a +single spectrum. Your logic should be inside the function passed to this helper. + +For bulk processing of all spectra, consider using the `_iterate_spectra_fast` +function, which is optimized for sequential access and avoids cache overhead. + +# Arguments + +- `f::Function`: The function to apply to the spectrum. +- `data::MSIData`: The MSIData object. +- `index::Int`: The index of the spectrum. + +# Returns +- `result::Any`: The result of applying the function to the spectrum. + +# Example + +```julia +process_spectrum(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function process_spectrum(f::Function, data::MSIData, index::Int) + # This call is type-unstable. + mz, intensity = GetSpectrum(data, index) + + # By immediately calling `f`, we create a "function barrier". + # Julia will compile a specialized version of `f` for the + # concrete types of `mz` and `intensity`. + return f(mz, intensity) +end + +""" + process_spectrum(f::Function, data::MSIData, x::Int, y::Int) + +A coordinate-based version of the "function barrier" helper. See `process_spectrum` +for details on the performance pattern. + +# Arguments + +- `f::Function`: The function to apply to the spectrum. +- `data::MSIData`: The MSIData object. +- `x::Int`: The x-coordinate of the spectrum. +- `y::Int`: The y-coordinate of the spectrum. + +# Returns +- `result::Any`: The result of applying the function to the spectrum. + +# Example + +```julia +process_spectrum(data, 1, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function process_spectrum(f::Function, data::MSIData, x::Int, y::Int) + mz, intensity = GetSpectrum(data, x, y) + return f(mz, intensity) +end + +""" + precompute_analytics(msi_data::MSIData) + +Performs a single pass over the entire dataset to pre-compute and cache important +analytics. This function populates the `global_min_mz`, `global_max_mz`, and +`spectrum_stats_df` fields of the `MSIData` object. + +The computed statistics include: +- Global minimum and maximum m/z values. +- Per-spectrum: + - Total Ion Count (TIC) + - Base Peak Intensity (BPI) + - m/z of the base peak + - Number of data points + - Minimum and maximum m/z + +Subsequent calls to functions like `get_total_spectrum` will be much faster +as they can use this cached data. This function modifies the `MSIData` object in-place +and is idempotent. + +# Arguments + +- `msi_data::MSIData`: The MSIData object. + +# Returns +- `nothing` +""" +function precompute_analytics(msi_data::MSIData) + # Double-checked locking pattern + if is_set(msi_data.analytics_ready) + return + end + + lock(msi_data.cache_lock) do + if is_set(msi_data.analytics_ready) + return + end + + println("Pre-computing analytics (streaming mode)...") + start_time = time_ns() + + num_spectra = length(msi_data.spectra_metadata) + + # Initialize thread-local variables for global stats + thread_local_min_mz = [Inf for _ in 1:Base.Threads.nthreads()] + thread_local_max_mz = [-Inf for _ in 1:Base.Threads.nthreads()] + + # Initialize vectors for per-spectrum stats + tics = Vector{Float64}(undef, num_spectra) + bpis = Vector{Float64}(undef, num_spectra) + bp_mzs = Vector{Float64}(undef, num_spectra) + num_points = Vector{Int}(undef, num_spectra) + min_mzs = Vector{Float64}(undef, num_spectra) + max_mzs = Vector{Float64}(undef, num_spectra) + modes = Vector{SpectrumMode}(undef, num_spectra) + + # Precompute Bloom filters during this pass + bloom_filters = Vector{Union{BloomFilter{Int}, Nothing}}(undef, num_spectra) + fill!(bloom_filters, nothing) + + # Process in chunks to reduce memory pressure + chunk_size = min(10000, num_spectra) + + for chunk_start in 1:chunk_size:num_spectra + chunk_end = min(chunk_start + chunk_size - 1, num_spectra) + chunk_range = chunk_start:chunk_end + + println("Processing chunk $chunk_start - $chunk_end / $num_spectra") + + # Process current chunk + _iterate_spectra_fast(msi_data, chunk_range) do idx, mz, intensity + # Store metadata + modes[idx] = msi_data.spectra_metadata[idx].mode + + if isempty(mz) + tics[idx] = 0.0 + bpis[idx] = 0.0 + bp_mzs[idx] = 0.0 + num_points[idx] = 0 + min_mzs[idx] = Inf + max_mzs[idx] = -Inf + return + end + + # Update thread-local global m/z range + local_min, local_max = extrema(mz) + thread_id = Base.Threads.threadid() + thread_local_min_mz[thread_id] = min(thread_local_min_mz[thread_id], local_min) + thread_local_max_mz[thread_id] = max(thread_local_max_mz[thread_id], local_max) + min_mzs[idx] = local_min + max_mzs[idx] = local_max + + # Calculate per-spectrum stats + tics[idx] = sum(intensity) + max_int, max_idx = findmax(intensity) + bpis[idx] = max_int + bp_mzs[idx] = mz[max_idx] + num_points[idx] = length(mz) + bloom_filters[idx] = create_bloom_filter_for_spectrum(mz) + end + + # Force GC between chunks to control memory + if chunk_end % 5000 == 0 + GC.gc() + end + end + + # Combine thread-local global stats + g_min_mz = minimum(thread_local_min_mz) + g_max_mz = maximum(thread_local_max_mz) + + # Only update if we found valid ranges + if isfinite(g_min_mz) && isfinite(g_max_mz) && g_min_mz < g_max_mz + Base.Threads.atomic_xchg!(msi_data.global_min_mz, g_min_mz) + Base.Threads.atomic_xchg!(msi_data.global_max_mz, g_max_mz) + else + # Fallback: calculate from first spectrum + try + if num_spectra > 0 + mz, _ = GetSpectrum(msi_data, 1) + if !isempty(mz) + Base.Threads.atomic_xchg!(msi_data.global_min_mz, minimum(mz)) + Base.Threads.atomic_xchg!(msi_data.global_max_mz, maximum(mz)) + end + end + catch e + @warn "Could not determine global m/z range from first spectrum: $e" + end + end + + # Create results + computed_stats_df = DataFrame( + SpectrumID = 1:num_spectra, + TIC = tics, + BPI = bpis, + BasePeakMZ = bp_mzs, + NumPoints = num_points, + MinMZ = min_mzs, + MaxMZ = max_mzs, + Mode = modes + ) + + # Set other data + msi_data.spectrum_stats_df = computed_stats_df + msi_data.bloom_filters = bloom_filters # Will be created on-demand + + set!(msi_data.analytics_ready) + + duration = (time_ns() - start_time) / 1e9 + @printf "Streaming analytics complete in %.2f seconds.\n" duration + end + + return +end + + + + +""" + get_total_spectrum_core(msi_data::MSIData; num_bins::Int=2000, masked_indices::Union{Set{Int}, Nothing}=nothing) + +Internal function to calculate the total spectrum. + +It uses a two-pass approach: +1. The first pass finds the global m/z range by iterating through all spectra. +2. The second pass sums intensities into a pre-defined number of bins. + +This function is called by `get_total_spectrum`. + +# Arguments + +- `msi_data::MSIData`: The MSIData object. +- `num_bins::Int`: The number of bins to use for the total spectrum. +- `masked_indices::Union{Set{Int}, Nothing}`: The indices of the spectra to mask. + +# Returns +- `(mz_range, total_spectrum, num_spectra_processed)`: A tuple containing the m/z range, total spectrum, and spectrum count. +""" +function get_total_spectrum_core(msi_data::MSIData; num_bins::Int=2000, masked_indices::Union{Set{Int}, Nothing}=nothing) + println("Calculating total spectrum (2-pass method)...") + total_start_time = time_ns() + + local global_min_mz, global_max_mz + + if Base.Threads.atomic_add!(msi_data.global_min_mz, 0.0) !== Inf + println(" Using pre-computed m/z range.") + global_min_mz = Base.Threads.atomic_add!(msi_data.global_min_mz, 0.0) + global_max_mz = Base.Threads.atomic_add!(msi_data.global_max_mz, 0.0) + else + # 1. First Pass: Find the global m/z range + pass1_start_time = time_ns() + println(" Pass 1: Finding global m/z range...") + g_min_mz = Inf + g_max_mz = -Inf + _iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, _ + if !isempty(mz) + local_min, local_max = extrema(mz) + g_min_mz = min(g_min_mz, local_min) + g_max_mz = max(g_max_mz, local_max) + end + end + pass1_duration = (time_ns() - pass1_start_time) / 1e9 + + if !isfinite(g_min_mz) + @warn "Could not determine a valid m/z range. All spectra might be empty." + return (Float64[], Float64[], 0) + end + + # Use and cache the result + global_min_mz = g_min_mz + global_max_mz = g_max_mz + set_global_mz_range!(msi_data, global_min_mz, global_max_mz) + println(" Global m/z range found and cached: [$(global_min_mz), $(global_max_mz)]") + @printf " (Pass 1 took %.2f seconds)\n" pass1_duration + end + + # 2. Define Bins and precompute constants + mz_bins = range(global_min_mz, stop=global_max_mz, length=num_bins) + bin_step = step(mz_bins) + inv_bin_step = 1.0 / bin_step # Precompute reciprocal to avoid division + min_mz = global_min_mz + + # Initialize thread-local intensity sums + thread_local_intensity_sums = [zeros(Float64, num_bins) for _ in 1:Base.Threads.nthreads()] + thread_local_spectra_processed = [0 for _ in 1:Base.Threads.nthreads()] + + # 3. Second Pass: Optimized binning + pass2_start_time = time_ns() + println(" Pass 2: Summing intensities into $num_bins bins...") + _iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, intensity + thread_id = Base.Threads.threadid() + thread_local_spectra_processed[thread_id] += 1 + if isempty(mz) + return + end + + # Use views to avoid bounds checks on the input arrays + mz_view = mz + intensity_view = intensity + + # Manual binning without clamp/round for SIMD + @inbounds @simd for i in eachindex(mz_view) + # Calculate raw bin index (much faster than round+clamp) + raw_index = (mz_view[i] - min_mz) * inv_bin_step + 1.0 + bin_index = trunc(Int, raw_index) + + # Branchless version using clamp + final_index = clamp(bin_index, 1, num_bins) + thread_local_intensity_sums[thread_id][final_index] += intensity_view[i] + end + end + + # Combine thread-local results + intensity_sum = zeros(Float64, num_bins) + num_spectra_processed = 0 + for i in 1:Base.Threads.nthreads() + intensity_sum .+= thread_local_intensity_sums[i] + num_spectra_processed += thread_local_spectra_processed[i] + end + pass2_duration = (time_ns() - pass2_start_time) / 1e9 + + total_duration = (time_ns() - total_start_time) / 1e9 + println("\n--- Profiling (Post-Optimization) ---") + @printf " Pass 2 (I/O + Binning): %.2f seconds\n" pass2_duration + @printf " Total Function Time: %.2f seconds\n" total_duration + println("----------------------------------------\n") + + println("Total spectrum calculation complete.") + return (collect(mz_bins), intensity_sum, num_spectra_processed) +end + +""" + get_total_spectrum(msi_data::MSIData; num_bins::Int=2000) -> Tuple{Vector{Float64}, Vector{Float64}} + +Calculates the sum of all spectra in the dataset by binning. +This function dispatches to a specialized implementation based on the file type +(.imzML or .mzML) for optimal performance. + +Returns a tuple containing two vectors: the binned m/z axis and the summed intensities. + +# Arguments + +- `msi_data::MSIData`: The MSIData object. +- `num_bins::Int`: The number of bins to use for the total spectrum. +- `mask_path::Union{String, Nothing}`: The path to the mask file. + +# Returns +- `(mz_range, total_spectrum)`: A tuple containing the m/z range and the total spectrum. + +# Example + +```julia +get_total_spectrum(msi_data) +``` +""" +function get_total_spectrum(msi_data::MSIData; num_bins::Int=2000, mask_path::Union{String, Nothing}=nothing)::Tuple{Vector{Float64}, Vector{Float64}, Int} + local masked_indices::Union{Set{Int}, Nothing} = nothing + if mask_path !== nothing + mask_matrix = load_and_prepare_mask(mask_path, msi_data.image_dims) + masked_indices = get_masked_spectrum_indices(msi_data, mask_matrix) + println("Calculating total spectrum for masked region (mask from: $(mask_path))") + end + + return get_total_spectrum_core(msi_data, num_bins=num_bins, masked_indices=masked_indices) +end + +""" + get_average_spectrum(msi_data::MSIData; num_bins::Int=2000) -> Tuple{Vector{Float64}, Vector{Float64}} + +Calculates the average of all spectra in the dataset by binning. +This is effectively the total spectrum divided by the number of spectra. + +Returns a tuple containing two vectors: the binned m/z axis and the averaged intensities. + +# Arguments + +- `msi_data::MSIData`: The MSIData object. +- `num_bins::Int`: The number of bins to use for the total spectrum. +- `mask_path::Union{String, Nothing}`: The path to the mask file. + +# Returns +- `(mz_range, average_spectrum)`: A tuple containing the m/z range and the average spectrum. + +# Example + +```julia +get_average_spectrum(msi_data) +``` +""" +function get_average_spectrum(msi_data::MSIData; num_bins::Int=2000, mask_path::Union{String, Nothing}=nothing)::Tuple{Vector{Float64}, Vector{Float64}} + mz_bins, intensity_sum, num_spectra_processed = get_total_spectrum(msi_data, num_bins=num_bins, mask_path=mask_path) + + if isempty(intensity_sum) || num_spectra_processed == 0 + @warn "Cannot calculate average spectrum: no spectra were processed." + return (mz_bins, Float64[]) + end + + average_intensity = intensity_sum ./ num_spectra_processed + + return (mz_bins, average_intensity) +end + +# --- Iterator Implementation --- # + +""" + MSIDataIterator + +A stateful iterator for sequentially accessing spectra from an `MSIData` object. +This is created by the `IterateSpectra` function. + +# Arguments + +- `data::MSIData`: The MSIData object. + +# Returns +- `MSIDataIterator`: An iterator that yields each spectrum. + +# Example + +```julia +IterateSpectra(data) +``` +""" +struct MSIDataIterator + data::MSIData +end + +""" + IterateSpectra(data::MSIData) + +Returns an iterator that yields each spectrum, processing the file sequentially. +This iterator is useful for processing all spectra in a loop and benefits from +the caching implemented in `GetSpectrum`. + +This function is the core of the "Event-driven" access pattern. + +# Arguments + +- `data::MSIData`: The MSIData object. + +# Returns +- `MSIDataIterator`: An iterator that yields each spectrum. + +# Example + +```julia +IterateSpectra(data) +``` +""" +function IterateSpectra(data::MSIData) + return MSIDataIterator(data) +end + +# Define the iteration interface for the custom iterator +Base.length(it::MSIDataIterator) = length(it.data.spectra_metadata) +Base.eltype(it::MSIDataIterator) = Tuple{Int, Tuple{Vector, Vector}} # Index, (mz, intensity) + +""" + Base.iterate(it::MSIDataIterator, state=1) + +Advances the iterator, returning the next spectrum in the sequence. It calls +`GetSpectrum`, which means the iteration process is cached according to the +`MSIData` object's cache settings. + +# Arguments +- `it`: The `MSIDataIterator` instance. +- `state`: The index of the next spectrum to retrieve. + +# Returns +- A tuple `((index, spectrum), next_state)` or `nothing` if iteration is complete. +""" +function Base.iterate(it::MSIDataIterator, state=1) + if state > length(it.data.spectra_metadata) + return nothing # End of iteration + end + + # GetSpectrum uses the cache, so iteration is also cached + spectrum = GetSpectrum(it.data, state) + + # Yield the index and the spectrum + return ((state, spectrum), state + 1) +end + + +# --- High-performance Internal Iterator --- # + +""" + read_compressed_array(data::MSIData, io::IO, asset::SpectrumAsset, ::Type{T}) where {T} + +Reads a single data array (m/z or intensity) from an `.ibd` file stream, +handling both compressed and uncompressed data. + +This is an internal function designed for high-performance reading and decompressing of binary arrays. +Uses type parameters and buffer pooling to minimize allocations and maximize speed. + +# Arguments +- `data`: The `MSIData` object. +- `io`: The IO stream of the `.ibd` file. +- `asset`: The `SpectrumAsset` for the array. +- `::Type{T}`: The target format of the data. + +# Returns +- A `Vector{T}` containing the data. + +# Throws +- An error if zlib decompression fails. +""" +function read_compressed_array(data::MSIData, io::IO, asset::SpectrumAsset, ::Type{T}) where {T} + # Add validation before seeking + if asset.offset < 0 || asset.offset >= filesize(io) + throw(FileFormatError("Invalid asset offset: $(asset.offset) for file size $(filesize(io))")) + end + # Optimization: Use Mmap if available to avoid seek and copy + mmap_data = (data.source isa ImzMLSource) ? data.source.mmap_data : nothing + + if asset.is_compressed + local decompressed_view + if mmap_data !== nothing + # Zero-copy access to the compressed segment + # Base64 should be read using a view as well + compressed_view = view(mmap_data, (asset.offset + 1):(asset.offset + asset.encoded_length)) + decompressed_view = Libz.inflate(compressed_view) + else + # Fallback to standard IO + seek(io, asset.offset) + compressed_bytes_buffer = get_buffer!(data.buffer_pool, Int(asset.encoded_length)) + try + readbytes!(io, compressed_bytes_buffer, asset.encoded_length) + decompressed_view = Libz.inflate(view(compressed_bytes_buffer, 1:asset.encoded_length)) + finally + release_buffer!(data.buffer_pool, compressed_bytes_buffer) + end + end + + local array + try + # Pre-allocate the typed output array + n_elements = length(decompressed_view) ÷ sizeof(T) + array = Vector{T}(undef, n_elements) + + # Use unsafe_copyto! for zero-overhead copy into the typed array + unsafe_copyto!(reinterpret(Ptr{UInt8}, pointer(array)), pointer(decompressed_view), length(decompressed_view)) + + catch e + @error "ZLIB DECOMPRESSION FAILED at offset $(asset.offset)" + rethrow(e) + end + + return array + else + # Read uncompressed data + if mmap_data !== nothing + # SAFETY: Check address alignment (sizeof(T) must divide asset.offset) + # Since mmap_data itself is page-aligned, we only check the offset. + alignment = sizeof(T) + if asset.offset % alignment == 0 + # ZERO-COPY Path + end_pos = asset.offset + asset.encoded_length * alignment + raw_view = view(mmap_data, (asset.offset + 1):end_pos) + return Vector{T}(reinterpret(T, raw_view)) + else + # ALIGNMENT FALLBACK: Memory-to-memory copy (safer than reinterpret) + array = Vector{T}(undef, asset.encoded_length) + # Raw copy from mmap to vector + n_bytes = asset.encoded_length * alignment + unsafe_copyto!(reinterpret(Ptr{UInt8}, pointer(array)), pointer(mmap_data, asset.offset + 1), n_bytes) + return array + end + else + # Fallback to standard IO + seek(io, asset.offset) + array = Vector{T}(undef, asset.encoded_length) + read!(io, array) + return array + end + end +end + + +""" + _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource) + +A highly optimized iterator for uncompressed `.imzML` data. + +It pre-allocates large buffers for m/z and intensity arrays and reuses them +for each spectrum by creating views. This minimizes memory allocations and +is significantly faster for bulk processing than reading spectra one by one. + +# Arguments +- `f`: A function to execute for each spectrum, with the signature `f(index, mz_view, int_view)`. +- `data`: The `MSIData` object. +- `source`: The `ImzMLSource`. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_uncompressed_fast(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" + +""" + _iterate_compressed_fast(f::Function, data::MSIData, source::ImzMLSource) + +An iterator for `.imzML` datasets that contain compressed spectra. + +This function iterates through each spectrum and reads its data individually, +decompressing it on the fly if necessary. Because the size of decompressed +data is not known in advance, this path cannot use the buffer-reuse optimization +and will be slower and allocate more memory than `_iterate_uncompressed_fast`. + +# Arguments +- `f`: A function to execute for each spectrum, with the signature `f(index, mz_array, int_array)`. +- `data`: The `MSIData` object. +- `source`: The `ImzMLSource`. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_compressed_fast(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function _iterate_compressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing}) + # Path for datasets containing at least one compressed spectrum. + # Optimized to minimize allocations by reusing buffers. + + # Determine which indices to iterate over + spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate + + # Pre-allocate large enough buffers for the expected maximum number of points + # We estimate based on metadata if possible, or grow dynamically + max_encoded = maximum(meta -> max(meta.mz_asset.encoded_length, meta.int_asset.encoded_length), data.spectra_metadata) + + # Heuristic: decompressed size is usually larger. We'll start with 10x and grow if needed. + # But read_compressed_array currently returns a Vector, so we'll need to modify it + # to accept an optional target buffer. + + for i in spectrum_indices + meta = data.spectra_metadata[i] + + if meta.mz_asset.encoded_length == 0 && meta.int_asset.encoded_length == 0 + f(i, source.mz_format[], source.intensity_format[]) + continue + end + + # For compressed data, we currently allocate new arrays per spectrum. + # To truly minimize allocations, we'd need read_compressed_array! (in-place version). + # For now, let's ensure we are at least using the optimized type-stable version. + handle = get_handle(source) + mz_array = read_compressed_array(data, handle, meta.mz_asset, source.mz_format) + intensity_array = read_compressed_array(data, handle, meta.int_asset, source.intensity_format) + + mz_array .= ltoh.(mz_array) + intensity_array .= ltoh.(intensity_array) + + f(i, mz_array, intensity_array) + end +end + +""" + _iterate_spectra_fast_impl(f::Function, data::MSIData, source::ImzMLSource) + +Internal implementation of the fast iterator for `.imzML` files. It reads +data directly from the `.ibd` file stream. + +This function acts as a dispatcher: +- If any spectrum is compressed, it uses a slower path that decompresses each spectrum individually. +- If all spectra are uncompressed, it uses a highly optimized path that reuses pre-allocated + buffers to minimize memory allocations and overhead. + +# Arguments + +- `f::Function`: A function to execute for each spectrum, with the signature `f(index, mz_array, int_array)`. +- `data::MSIData`: The `MSIData` object. +- `source::ImzMLSource`: The `ImzMLSource`. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_spectra_fast_impl(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing}) + if isempty(data.spectra_metadata) + return + end + + # Use cached compression status for zero-allocation dispatch + if source.is_any_compressed + _iterate_compressed_fast(f, data, source, indices_to_iterate) + else + _iterate_uncompressed_fast(f, data, source, indices_to_iterate) + end +end + +""" + _iterate_spectra_fast_impl(f::Function, data::MSIData, source::MzMLSource) + +Internal implementation of the fast iterator for `.mzML` files. It iterates +through each spectrum, decodes the Base64 data on the fly, and calls the +provided function. It bypasses the `GetSpectrum` cache to avoid storing +all decoded spectra in memory. + +# Arguments + +- `f::Function`: A function to execute for each spectrum, with the signature `f(index, mz_array, int_array)`. +- `data::MSIData`: The `MSIData` object. +- `source::MzMLSource`: The `MzMLSource`. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_spectra_fast_impl(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::MzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing}) + spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate + indices_with_offsets = [(i, data.spectra_metadata[i].mz_asset.offset) for i in spectrum_indices] + sort!(indices_with_offsets, by = x -> x[2]) + + handle = get_handle(source) + + for (i, _) in indices_with_offsets + meta = data.spectra_metadata[i] + # For MzML, we still have some allocations due to Base64 decoding, + # but we use the thread-local handle. + mz = read_binary_vector(data, handle, meta.mz_asset) + intensity = read_binary_vector(data, handle, meta.int_asset) + f(i, mz, intensity) + end +end + +function _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing}) + spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate + + # Intialize local buffers for this thread's sequential iteration + mz_buf = Vector{Float64}() + int_buf = Vector{Float64}() + + for i in spectrum_indices + meta = data.spectra_metadata[i] + + # Use Mmap views if available (zero-copy if LE) + if source.mmap_data !== nothing + # Optimized Mmap path (same as read_spectrum_from_disk but potentially avoiding copies) + mz, intensity = read_spectrum_from_disk(source, meta) + f(i, mz, intensity) + else + # Read into our loop buffers to avoid continuous allocation + handle = get_handle(source) + + # Resize buffers if necessary (minimal reallocation) + resize!(mz_buf, meta.mz_asset.encoded_length) + resize!(int_buf, meta.int_asset.encoded_length) + + seek(handle, meta.mz_asset.offset) + read!(handle, mz_buf) + seek(handle, meta.int_asset.offset) + read!(handle, int_buf) + + # Convert in-place if possible + mz_buf .= ltoh.(mz_buf) + int_buf .= ltoh.(int_buf) + + f(i, mz_buf, int_buf) + end + end +end + +""" + _iterate_spectra_fast_serial(f::Function, data::MSIData, indices_to_iterate=nothing) + +An internal, high-performance iterator for bulk processing that bypasses the `GetSpectrum` cache. +It provides direct, sequential access to spectral data, making it the most efficient +method for operations that need to process many or all spectra (e.g., calculating +a total spectrum, pre-computing analytics, or exporting data). + +This function dispatches to a specialized implementation based on the data source type +(`ImzMLSource` or `MzMLSource`) and data characteristics (e.g., compressed vs. +uncompressed) to maximize performance. + +# Arguments +- `f`: A function to call for each spectrum, with the signature `f(index, mz, intensity)`. +- `data`: The `MSIData` object. +- `indices_to_iterate`: An optional `AbstractVector{Int}` specifying a subset of + spectrum indices to iterate over. If `nothing`, it iterates over all spectra. + +# Warning +This is a low-level function that bypasses the public `GetSpectrum` API. It does not +use the cache and is not guaranteed to be thread-safe if the same `MSIData` object +is accessed from multiple threads concurrently. +""" +function _iterate_spectra_fast_serial(f::Function, data::MSIData, indices_to_iterate::Union{AbstractVector{Int}, Nothing}=nothing) + # Dispatch to the correct implementation based on the source type + _iterate_spectra_fast_impl(f, data, data.source, indices_to_iterate) +end + +""" + _iterate_spectra_fast(f::Function, data::MSIData, indices_to_iterate=nothing) + +A smart dispatcher for internal, high-performance iteration over spectra. +It automatically chooses between serial and parallel execution based on the +number of available threads (`Base.Threads.nthreads()`). + +# Arguments +- `f`: A function to call for each spectrum, with the signature `f(index, mz, intensity)`. +- `data`: The `MSIData` object. +- `indices_to_iterate`: An optional `AbstractVector{Int}` specifying a subset of + spectrum indices to iterate over. If `nothing`, it iterates over all spectra. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_spectra_fast(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function _iterate_spectra_fast(f::Function, data::MSIData, indices_to_iterate::Union{AbstractVector{Int}, Nothing}=nothing) + # Default to all indices if not specified + all_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate + + if Base.Threads.nthreads() > 1 && length(all_indices) > 100 # Heuristic: only parallelize for enough work + _iterate_spectra_fast_parallel(f, data, all_indices) + else + _iterate_spectra_fast_serial(f, data, all_indices) + end +end + +""" + _iterate_spectra_fast_threadsafe(f::Function, data::MSIData, indices::AbstractVector{Int}) + +Thread-safe version of the fast iterator that uses the cache lock to ensure exclusive file access. +This is safe to use when multiple threads might access the same MSIData object concurrently. + +# Arguments +- `f`: Function to call for each spectrum with signature `f(index, mz, intensity)` +- `data`: The MSIData object +- `indices`: Specific spectrum indices to iterate over + +# Performance +- Slower than non-thread-safe version due to locking +- Safe for concurrent access to same MSIData object +- Good for small to medium datasets where parallel overhead isn't justified +""" +function _iterate_spectra_fast_threadsafe(f::Function, data::MSIData, indices::AbstractVector{Int}) + # Use the cache lock to ensure exclusive access to file + lock(data.cache_lock) do + _iterate_spectra_fast(f, data, indices) + end +end + +""" + _iterate_spectra_fast_parallel(f::Function, data::MSIData, indices::AbstractVector{Int}) + +Parallel version that creates thread-local file handles for maximum performance. +Each thread gets its own file handle, eliminating contention. + +# Arguments +- `f`: Function to call for each spectrum with signature `f(index, mz, intensity)` +- `data`: The MSIData object +- `indices`: Specific spectrum indices to iterate over + +# Performance +- Fastest for large datasets on multi-core systems +- Eliminates file I/O contention between threads +- Higher memory usage due to multiple file handles +- Best for bulk processing operations +""" +function _iterate_spectra_fast_parallel(f::Function, data::MSIData, indices::AbstractVector) + n_total = length(indices) + n_threads = Base.Threads.nthreads() + + # Manual chunking to avoid allocations of Iterators.partition and collect + Base.Threads.@threads for t in 1:n_threads + start_idx = ((t - 1) * n_total ÷ n_threads) + 1 + end_idx = (t * n_total) ÷ n_threads + + if start_idx <= end_idx + chunk = view(indices, start_idx:end_idx) + _iterate_spectra_fast_impl(f, data, data.source, chunk) + end + end +end + +""" + _iterate_spectra_fast_parallel(f::Function, data::MSIData) + +Parallel version that processes all spectra in the dataset. +Convenience wrapper for the indexed version. + +# Arguments + +- `f::Function`: A function to execute for each spectrum, with the signature `f(index, mz_array, int_array)`. +- `data::MSIData`: The `MSIData` object. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_spectra_fast_parallel(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function _iterate_spectra_fast_parallel(f::Function, data::MSIData) + all_indices = collect(1:length(data.spectra_metadata)) + _iterate_spectra_fast_parallel(f, data, all_indices) +end + +""" + _iterate_spectra_fast_threadsafe(f::Function, data::MSIData) + +Thread-safe version that processes all spectra in the dataset. +Convenience wrapper for the indexed version. + +# Arguments + +- `f::Function`: A function to execute for each spectrum, with the signature `f(index, mz_array, int_array)`. +- `data::MSIData`: The `MSIData` object. + +# Returns +- `nothing` + +# Example + +```julia +_iterate_spectra_fast_threadsafe(data, 1) do mz, intensity + # Process the spectrum here +end +``` +""" +function _iterate_spectra_fast_threadsafe(f::Function, data::MSIData) + all_indices = collect(1:length(data.spectra_metadata)) + _iterate_spectra_fast_threadsafe(f, data, all_indices) +end + +""" + get_bloom_filter(data::MSIData, index::Int)::BloomFilter{Int} + +Retrieves the Bloom filter for a specific spectrum by its index. +If the Bloom filter has not yet been created (due to lazy initialization), +it will be created on-demand and cached. + +# Arguments +- `data`: The `MSIData` object. +- `index`: The linear index of the spectrum. + +# Returns +- A `BloomFilter{Int}` for the specified spectrum. +""" +function get_bloom_filter(data::MSIData, index::Int)::BloomFilter{Int} + # Double-checked locking for resilience if not precomputed + if data.bloom_filters === nothing || data.bloom_filters[index] === nothing + lock(data.cache_lock) do + if data.bloom_filters === nothing + data.bloom_filters = Vector{Union{BloomFilter{Int}, Nothing}}(undef, length(data.spectra_metadata)) + fill!(data.bloom_filters, nothing) + end + + if data.bloom_filters[index] === nothing + mz, _ = GetSpectrum(data, index) + data.bloom_filters[index] = create_bloom_filter_for_spectrum(mz) + end + end + end + return data.bloom_filters[index] +end diff --git a/src/MSI_src.jl b/src/MSI_src.jl new file mode 100644 index 0000000..95d1206 --- /dev/null +++ b/src/MSI_src.jl @@ -0,0 +1,150 @@ +# MSI_src.jl + +module MSI_src + +# Export the public MSI API +export OpenMSIData, + GetSpectrum, + IterateSpectra, + ImportMzmlFile, + plot_slice, + get_total_spectrum, + get_average_spectrum, + precompute_analytics, + process_spectrum, + generate_colorbar_image, + 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! + +# 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("BloomFilters.jl") +include("Common.jl") +include("ResourcePool.jl") +include("MSIData.jl") +include("ParserHelpers.jl") +include("mzML.jl") +include("imzML.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 diff --git a/src/MzmlConverter.jl b/src/MzmlConverter.jl new file mode 100644 index 0000000..c20fdcd --- /dev/null +++ b/src/MzmlConverter.jl @@ -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("", 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"(\d+)", footer) + if index_offset_match === nothing + @warn "No 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"", line) || occursin("", 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, """ + +""") + + # CV List, File Description, etc. (static parts) + write(imzml_stream, """ + + + + +""") + write(imzml_stream, """ + + + + + +$( + if instrument_meta.polarity == :positive + """ """ + elseif instrument_meta.polarity == :negative + """ """ + else + "" + end +) + + +""") + write(imzml_stream, """ + + + + + + + + + + + +""") + write(imzml_stream, """ + + + + +""") + write(imzml_stream, """ + + + + +""") + write(imzml_stream, """ + + + + + + + + + +""") + write(imzml_stream, """ + +$( + if instrument_meta.instrument_model != "Not Available" + """ """ + else + "" + end +) +$( + if instrument_meta.resolution !== nothing + """ """ + else + "" + end +) + + + + + + +$( + if instrument_meta.acquisition_mode == :centroid + """ """ + elseif instrument_meta.acquisition_mode == :profile + """ """ + else + "" + end +) + + + + + + + + +""") + write(imzml_stream, """ + + + + +$( + if instrument_meta.vendor_preprocessing_steps !== nothing + join([ + """ + + """ + for (i, step) in enumerate(instrument_meta.vendor_preprocessing_steps) + ], "\n") + else + "" + end +) + + +""") + + # Run and Spectrum List + spectrum_offsets = UInt64[] + write(imzml_stream, """ + +""") + + # 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, """ + +""") + if modes[i] == CENTROID + write(imzml_stream, """ +""") + elseif modes[i] == PROFILE + write(imzml_stream, """ +""") + end + write(imzml_stream, """ + + + + + + + + + + + + + + + + + + + + +""") + end + + write(imzml_stream, """ + + +""") + 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 diff --git a/src/ParserHelpers.jl b/src/ParserHelpers.jl new file mode 100644 index 0000000..7cb28b1 --- /dev/null +++ b/src/ParserHelpers.jl @@ -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"", "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 `` 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* Dict + +Calculates and reports mass accuracy (PPM error) statistics for different spatial regions +defined by masks. This is useful for identifying spatial variations in calibration. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `region_masks::Dict{Symbol, BitMatrix}`: A dictionary mapping region names (e.g., `:tumor`, `:stroma`) + to `BitMatrix` masks. The dimensions of each mask must match `msi_data.image_dims`. +- `reference_peaks::Dict{Float64, String}`: A dictionary of known reference peaks, mapping + theoretical m/z to a name. + +# Returns +- `Dict{Symbol, NamedTuple}`: A dictionary where keys are region names and values are `NamedTuple`s + containing the mass accuracy report for that region, as generated by `analyze_mass_accuracy`. +""" +function find_ppm_error_by_region(msi_data::MSIData, region_masks::Dict, reference_peaks::Dict) + regional_reports = Dict{Symbol, NamedTuple}() + + width, height = msi_data.image_dims + + for (region_name, mask) in region_masks + mask_height, mask_width = size(mask) + if mask_width != width || mask_height != height + @warn "Mask dimensions ($(mask_width)x$(mask_height)) for region '$region_name' do not match image dimensions ($(width)x$(height)). Skipping." + continue + end + + indices = [ + i for i in 1:length(msi_data.spectra_metadata) + if msi_data.spectra_metadata[i].x > 0 && + msi_data.spectra_metadata[i].y > 0 && + mask[msi_data.spectra_metadata[i].y, msi_data.spectra_metadata[i].x] + ] + + if isempty(indices) continue end + + # Call analyze_mass_accuracy with the specific indices for the region + regional_reports[region_name] = analyze_mass_accuracy(msi_data, reference_peaks; spectrum_indices=indices) + end + return regional_reports +end + +""" + analyze_mass_accuracy(msi_data, reference_peaks; ...) -> NamedTuple + +Analyzes the mass accuracy for a given subset of spectra by comparing detected peaks +against a list of known reference masses. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `reference_peaks::Dict{Float64, String}`: A dictionary of known reference peaks, mapping + theoretical m/z to a name. +- `spectrum_indices::AbstractVector{Int}`: A vector of indices for the spectra to be analyzed. +- `peak_detection_snr_threshold::Float64`: The Signal-to-Noise ratio threshold to use for + detecting peaks within the spectra. +- `ppm_tolerance_for_matching::Float64`: The tolerance in Parts Per Million (PPM) used to match + a detected peak to a reference peak. + +# Returns +- `NamedTuple`: A report containing summary statistics of the PPM errors found, including: + - `mean_ppm_error`, `median_ppm_error`, `std_ppm_error`, `min_ppm_error`, `max_ppm_error` + - `total_matched_peaks`: The total count of successful matches between detected and reference peaks. + - `total_spectra_analyzed`: The number of spectra processed. +""" +function analyze_mass_accuracy( + msi_data::MSIData, + reference_peaks::Dict{Float64, String}; # m/z => name + spectrum_indices::AbstractVector{Int}, + peak_detection_snr_threshold::Float64 = 2.0, + ppm_tolerance_for_matching::Float64 = 50.0 + )::NamedTuple + println("Analyzing mass accuracy for $(length(spectrum_indices)) spectra...") + + all_ppm_errors = Float64[] + total_matched_peaks = Base.Threads.Atomic{Int}(0) + total_spectra_processed = Base.Threads.Atomic{Int}(0) + results_lock = ReentrantLock() + + _iterate_spectra_fast(msi_data, spectrum_indices) do idx, mz, intensity + Base.Threads.atomic_add!(total_spectra_processed, 1) + if !validate_spectrum(mz, intensity) + @warn "Spectrum $idx is invalid, skipping mass accuracy analysis for it." + return + end + + detected_peaks = detect_peaks_profile_core(mz, intensity; snr_threshold=peak_detection_snr_threshold) + + for ref_mz in keys(reference_peaks) + # Find the closest detected peak to this reference m/z within tolerance + min_ppm_error = Inf + best_matched_peak_mz = nothing + + for p in detected_peaks + ppm_error = calculate_ppm_error(p.mz, ref_mz) + if ppm_error <= ppm_tolerance_for_matching && ppm_error < min_ppm_error + min_ppm_error = ppm_error + best_matched_peak_mz = p.mz + end + end + + if best_matched_peak_mz !== nothing + lock(results_lock) do + push!(all_ppm_errors, min_ppm_error) + end + Base.Threads.atomic_add!(total_matched_peaks, 1) + end + end + end + + if isempty(all_ppm_errors) + @warn "No reference peaks matched in any of the $(total_spectra_processed) processed spectra." + return ( + mean_ppm_error = NaN, + median_ppm_error = NaN, + std_ppm_error = NaN, + min_ppm_error = NaN, + max_ppm_error = NaN, + total_matched_peaks = 0, + total_spectra_analyzed = total_spectra_processed, + ppm_error_distribution = Float64[] + ) + end + + # Calculate summary statistics + mean_err = mean(all_ppm_errors) + median_err = median(all_ppm_errors) + std_err = std(all_ppm_errors) + min_err = minimum(all_ppm_errors) + max_err = maximum(all_ppm_errors) + + println("Mass accuracy analysis complete for $(total_spectra_processed) spectra.") + return ( + mean_ppm_error = mean_err, + median_ppm_error = median_err, + std_ppm_error = std_err, + min_ppm_error = min_err, + max_ppm_error = max_err, + total_matched_peaks = total_matched_peaks[], + total_spectra_analyzed = total_spectra_processed[], + ppm_error_distribution = all_ppm_errors + ) +end + +# ============================================================================= +# 8) Advanced Peak Quality & Adaptive Parameters +# ============================================================================= + +""" + calculate_adaptive_bin_tolerance(ppm_error_distribution) -> Float64 + +Calculates an appropriate binning tolerance in PPM based on the observed mass accuracy +distribution. The strategy is to set the tolerance to capture the vast majority of +peaks from the same analyte, typically using `mean + 3 * standard_deviation`. + +# Arguments +- `ppm_error_distribution::Vector{Float64}`: A vector of PPM error values from a mass + accuracy analysis. + +# Returns +- `Float64`: The suggested binning tolerance in PPM, capped between 10.0 and 100.0. +""" +function calculate_adaptive_bin_tolerance(ppm_error_distribution::Vector{Float64}) + if isempty(ppm_error_distribution) + return 20.0 # Default if no data + end + + # Filter out NaN and infinite values + valid_errors = filter(x -> isfinite(x), ppm_error_distribution) + + if isempty(valid_errors) + return 20.0 # Default if no valid data + end + + # A robust strategy: mean + 3 * std deviation to capture ~99.7% of peaks + mean_err = mean(valid_errors) + std_err = std(valid_errors) + + # Ensure we don't get NaN + if !isfinite(mean_err) || !isfinite(std_err) + return 20.0 + end + + tolerance = mean_err + 3 * std_err + + # Cap at reasonable value and ensure finite + return min(max(tolerance, 10.0), 100.0) +end + +""" + calculate_preprocessing_hints(data::MSIData; sample_indices)::Dict{Symbol, Any} + +Analyzes a sample of spectra to determine initial "hints" for preprocessing parameters. +This function provides quick, data-driven defaults for noise level, SNR, and smoothing. + +# Arguments +- `data::MSIData`: The main MSI data object. +- `sample_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis. + +# Returns +- `Dict{Symbol, Any}`: A dictionary of hints, including: + - `:estimated_noise`: The mean noise level estimated using Median Absolute Deviation (MAD). + - `:suggested_snr`: A default SNR threshold (typically 3.0). + - `:suggested_smoothing_window`: A suggested window size for smoothing, based on instrument resolution if available. +""" +function calculate_preprocessing_hints(data::MSIData; sample_indices::AbstractVector{Int})::Dict{Symbol, Any} + println("Calculating preprocessing hints from a sample of $(length(sample_indices)) spectra...") + + num_spectra = length(data.spectra_metadata) + if num_spectra == 0 || isempty(sample_indices) + @warn "No spectra in dataset/sample to calculate hints from." + return Dict{Symbol, Any}( + :estimated_noise => 1.0, + :suggested_snr => 3.0, + :suggested_smoothing_window => 9 + ) + end + + # Initialize hints with defaults immediately + hints = Dict{Symbol, Any}( + :estimated_noise => 1.0, + :suggested_snr => 3.0, + :suggested_smoothing_window => 9 + ) + + all_noise_levels = Float64[] + + for idx in sample_indices + try + mz, intensity = GetSpectrum(data, idx) + if !isempty(intensity) + noise = mad(intensity, normalize=true) + if isfinite(noise) && noise > 0 + push!(all_noise_levels, noise) + end + end + catch e + @warn "Could not access spectrum #$idx to calculate hints: $e. Skipping." + end + end + + if !isempty(all_noise_levels) + estimated_noise = mean(all_noise_levels) + hints[:estimated_noise] = estimated_noise + println(" - Estimated Noise Level: $(round(estimated_noise, digits=4))") + println(" - Suggested SNR Threshold: 3.0") + else + @warn "Could not estimate noise from sample. Using default hints." + # Defaults already set in `hints` initialization + end + + # Suggest smoothing window based on resolution (if available) + if data.instrument_metadata !== nothing && data.instrument_metadata.resolution !== nothing + res = data.instrument_metadata.resolution + # Update suggested smoothing window if resolution is known + if res > 40000 + hints[:suggested_smoothing_window] = 5 + elseif res > 10000 + hints[:suggested_smoothing_window] = 7 + else + hints[:suggested_smoothing_window] = 9 + end + end + println(" - Suggested Smoothing Window: $(hints[:suggested_smoothing_window])") + + println("Preprocessing hints calculated.") + return hints +end + +""" + analyze_instrument_characteristics(msi_data::MSIData; sample_indices)::Dict + +Analyzes instrument metadata and spectral data to infer key acquisition properties. +It combines information from the `msi_data.instrument_metadata` with direct analysis +of the spectra. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `sample_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis. + +# Returns +- `Dict{Symbol, Any}`: A dictionary summarizing instrument characteristics: + - `:acquisition_mode`: Inferred as `:profile`, `:centroid`, or `:mixed`. + - `:mz_axis_type`: Inferred as `:regular` or `:irregular` based on m/z step consistency. + - `:dynamic_range`: An estimate of the intensity dynamic range in orders of magnitude. + - Other fields from `instrument_metadata` like `:resolution`, `:polarity`, etc. +""" +function analyze_instrument_characteristics(msi_data::MSIData; sample_indices::AbstractVector{Int})::Dict + results = Dict{Symbol, Any}() + + # Use instrument metadata if available + if msi_data.instrument_metadata !== nothing + inst = msi_data.instrument_metadata + results[:resolution] = inst.resolution + results[:mass_accuracy_ppm] = inst.mass_accuracy_ppm + results[:instrument_model] = inst.instrument_model + results[:polarity] = inst.polarity + results[:calibration_status] = inst.calibration_status + results[:vendor_preprocessing] = inst.vendor_preprocessing_steps + end + + # Analyze data characteristics from spectra + println(" Analyzing data characteristics from spectra...") + + spectrum_modes = Set{SpectrumMode}() + mz_step_sizes = Float64[] + intensity_ranges = Tuple{Float64, Float64}[] # (min, max) per spectrum + + if isempty(sample_indices) + @warn "No indices to sample for instrument characteristics analysis." + results[:acquisition_mode] = :unknown + results[:mz_axis_type] = :unknown + results[:dynamic_range] = 3.0 + return results + end + + results_lock = ReentrantLock() + + _iterate_spectra_fast(msi_data, sample_indices) do idx, mz, intensity + # Record spectrum mode + lock(results_lock) do + push!(spectrum_modes, msi_data.spectra_metadata[idx].mode) + end + + # Calculate m/z step statistics (for profile data) + if length(mz) > 1 && msi_data.spectra_metadata[idx].mode == PROFILE + steps = diff(mz) + if !isempty(steps) + lock(results_lock) do + push!(mz_step_sizes, mean(steps)) + end + end + end + + # Record intensity range + if !isempty(intensity) + lock(results_lock) do + push!(intensity_ranges, (minimum(intensity), maximum(intensity))) + end + end + end + + # Determine acquisition mode + if length(spectrum_modes) == 1 + results[:acquisition_mode] = first(spectrum_modes) == CENTROID ? :centroid : :profile + else + results[:acquisition_mode] = :mixed + end + + # Determine m/z axis regularity + if !isempty(mz_step_sizes) + avg_step = mean(mz_step_sizes) + step_std = std(mz_step_sizes) + results[:mz_axis_type] = step_std / avg_step < 0.01 ? :regular : :irregular + results[:average_mz_step] = avg_step + else + results[:mz_axis_type] = :unknown + end + + # Enhanced dynamic range calculation + if !isempty(intensity_ranges) + println("DEBUG: Found $(length(intensity_ranges)) intensity ranges") + + # FIX: Handle cases where min intensities are zero + max_intensities = Float64[] + min_positive_intensities = Float64[] + + for (min_val, max_val) in intensity_ranges + if max_val > 1e-6 # Valid maximum + push!(max_intensities, max_val) + + # Find the smallest positive intensity in the spectrum + # For now, use a reasonable estimate: 1% of the noise level + # In practice, you'd want to sample the actual spectrum + if max_val > 0 + # Estimate minimum detectable signal as ~3x noise level + estimated_min_signal = max_val * 1e-4 # Conservative estimate + push!(min_positive_intensities, estimated_min_signal) + end + end + end + + println("DEBUG: Valid max intensities: $(length(max_intensities)), estimated min intensities: $(length(min_positive_intensities))") + + if !isempty(max_intensities) && !isempty(min_positive_intensities) + avg_max = mean(max_intensities) + avg_min = mean(min_positive_intensities) + if avg_min > 0 + dynamic_range = log10(avg_max / avg_min) + results[:dynamic_range] = dynamic_range + println("DEBUG: Dynamic range calculated: $dynamic_range (avg_max=$avg_max, avg_min=$avg_min)") + else + results[:dynamic_range] = 0.0 + end + else + # Estimate based on typical values + results[:dynamic_range] = 3.0 # Typical for MS data + end + else + results[:dynamic_range] = 3.0 # Default estimate + end + + println(" - Acquisition mode: $(results[:acquisition_mode])") + println(" - m/z axis type: $(results[:mz_axis_type])") + println(" - Dynamic range: $(round(get(results, :dynamic_range, 0), digits=2))") + + return results +end + +""" + analyze_signal_quality(msi_data::MSIData; sample_indices)::Dict + +Analyzes a sample of spectra to assess signal quality, including noise levels, +Signal-to-Noise Ratio (SNR), and Total Ion Current (TIC) variation. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `sample_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis. + +# Returns +- `Dict{Symbol, Any}`: A dictionary of signal quality metrics: + - `:noise_mean`, `:noise_std`, `:noise_cv`: Statistics of the noise level. + - `:snr_mean`, `:snr_median`, `:snr_95th`: Distribution statistics of the estimated SNR. + - `:tic_mean`, `:tic_std`, `:tic_cv`: Statistics of the Total Ion Current. +""" +function analyze_signal_quality(msi_data::MSIData; sample_indices::AbstractVector{Int})::Dict + results = Dict{Symbol, Any}() + + println(" Analyzing signal quality from $(length(sample_indices)) sample spectra...") + + # Use the existing function for basic noise estimation + hints_from_calc = calculate_preprocessing_hints(msi_data, sample_indices=sample_indices) + + # Copy relevant hints to results, or handle cases where they might be missing + results[:estimated_noise] = get(hints_from_calc, :estimated_noise, 1.0) + results[:suggested_snr] = get(hints_from_calc, :suggested_snr, 3.0) + results[:suggested_smoothing_window] = get(hints_from_calc, :suggested_smoothing_window, 9) + + # Enhanced noise analysis + noise_levels = Float64[] + snr_distribution = Float64[] + tic_values = Float64[] + + if isempty(sample_indices) + @warn "No indices to sample for signal quality analysis." + return results + end + + results_lock = ReentrantLock() + + _iterate_spectra_fast(msi_data, sample_indices) do idx, mz, intensity + if !isempty(intensity) + # Noise estimation using MAD + noise = mad(intensity, normalize=true) + lock(results_lock) do + push!(noise_levels, noise) + end + + # FIX: More robust SNR calculation + valid_intensity = intensity[intensity .> 0] # Remove zeros + if !isempty(valid_intensity) + # Use robust signal estimate (95th percentile instead of max) + signal_estimate = quantile(valid_intensity, 0.95) + noise_robust = max(noise, 1e-6) # Avoid division by zero + + if noise_robust > 0 && isfinite(signal_estimate) + snr_val = signal_estimate / noise_robust + # Cap unrealistic SNR values + lock(results_lock) do + push!(snr_distribution, min(snr_val, 1e6)) + end + end + end + + # Total ion count + lock(results_lock) do + push!(tic_values, sum(intensity)) + end + end + end + + if !isempty(noise_levels) + results[:noise_mean] = mean(noise_levels) + results[:noise_std] = std(noise_levels) + results[:noise_cv] = results[:noise_std] / results[:noise_mean] # Coefficient of variation + end + + if !isempty(snr_distribution) + results[:snr_mean] = mean(snr_distribution) + results[:snr_median] = median(snr_distribution) + results[:snr_95th] = quantile(snr_distribution, 0.95) + end + + if !isempty(tic_values) + results[:tic_mean] = mean(tic_values) + results[:tic_std] = std(tic_values) + results[:tic_cv] = results[:tic_std] / results[:tic_mean] + end + + println(" - Estimated noise level: $(round(get(results, :noise_mean, 0), digits=4))") + println(" - Average SNR: $(round(get(results, :snr_mean, 0), digits=2))") + println(" - TIC CV: $(round(get(results, :tic_cv, 0) * 100, digits=1))%") + + return results +end + +""" + analyze_mass_accuracy_global(msi_data, reference_peaks; spectrum_indices)::Dict + +Performs a global mass accuracy analysis across a sample of spectra and suggests an +adaptive binning tolerance. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `reference_peaks::Dict`: A dictionary of known reference peaks. +- `spectrum_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis. + +# Returns +- `Dict{Symbol, Any}`: A dictionary containing: + - `:global_accuracy`: The `NamedTuple` report from `analyze_mass_accuracy`. + - `:suggested_bin_tolerance`: An adaptive tolerance in PPM for peak binning, derived + from the mass accuracy results. +""" +function analyze_mass_accuracy_global(msi_data::MSIData, reference_peaks::Dict; + spectrum_indices::AbstractVector{Int})::Dict + results = Dict{Symbol, Any}() + + println(" Analyzing mass accuracy using $(length(reference_peaks)) reference peaks on $(length(spectrum_indices)) spectra...") + + if isempty(spectrum_indices) + @warn "No indices to sample for mass accuracy analysis." + # Return a structure indicating no analysis was performed + empty_report = ( + mean_ppm_error = NaN, median_ppm_error = NaN, std_ppm_error = NaN, + min_ppm_error = NaN, max_ppm_error = NaN, total_matched_peaks = 0, + total_spectra_analyzed = 0, ppm_error_distribution = Float64[] + ) + results[:global_accuracy] = empty_report + results[:suggested_bin_tolerance] = 20.0 # Default + return results + end + + # Use the existing analyze_mass_accuracy function with the provided indices + accuracy_report = analyze_mass_accuracy(msi_data, reference_peaks; + spectrum_indices=spectrum_indices) + + results[:global_accuracy] = accuracy_report + results[:suggested_bin_tolerance] = calculate_adaptive_bin_tolerance( + accuracy_report.ppm_error_distribution + ) + + println(" - Mean PPM error: $(round(accuracy_report.mean_ppm_error, digits=2))") + println(" - Suggested bin tolerance: $(round(results[:suggested_bin_tolerance], digits=2)) ppm") + + return results +end + +""" + analyze_spatial_regions(msi_data, region_masks, reference_peaks)::Dict + +Analyzes different spatial regions for variations in mass accuracy. This function is a +wrapper around `find_ppm_error_by_region` and summarizes the results. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `region_masks::Dict`: A dictionary of named `BitMatrix` masks for each region. +- `reference_peaks::Dict`: A dictionary of known reference peaks. + +# Returns +- `Dict{Symbol, Any}`: A dictionary containing: + - `:regional_ppm_errors`: A dictionary mapping each region name to its mass accuracy report. + - `:max_regional_ppm_difference`: The difference between the highest and lowest mean PPM + error across all analyzed regions. +""" +function analyze_spatial_regions(msi_data::MSIData, region_masks::Dict, reference_peaks::Dict)::Dict + results = Dict{Symbol, Any}() + + println(" Analyzing $(length(region_masks)) spatial regions...") + + # Use the existing function + regional_reports = find_ppm_error_by_region(msi_data, region_masks, reference_peaks) + + results[:regional_ppm_errors] = regional_reports + + # Calculate regional variations + if !isempty(regional_reports) + mean_errors = [report.mean_ppm_error for report in values(regional_reports) if isfinite(report.mean_ppm_error)] + if !isempty(mean_errors) + results[:max_regional_ppm_difference] = maximum(mean_errors) - minimum(mean_errors) + end + end + + for (region, report) in regional_reports + println(" - $region: $(round(report.mean_ppm_error, digits=2)) ppm (n=$(report.total_spectra_analyzed))") + end + + return results +end + +""" + analyze_peak_characteristics(msi_data, instrument_analysis, mass_accuracy_results; spectrum_indices)::Dict + +Analyzes peak shape, width, and quality from a sample of spectra. The behavior +adapts based on whether the data is in `:profile` or `:centroid` mode. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `instrument_analysis::Dict`: The output from `analyze_instrument_characteristics`. +- `mass_accuracy_results`: The output from `analyze_mass_accuracy_global`. +- `spectrum_indices::AbstractVector{Int}`: The indices of spectra to sample. + +# Returns +- `Dict{Symbol, Any}`: A dictionary of peak metrics: + - `:mean_fwhm_ppm`, `:median_fwhm_ppm`: Statistics of Full Width at Half Maximum (FWHM). + For centroid data, this is estimated from mass accuracy. + - `:mean_gaussian_r2`: The average goodness-of-fit to a Gaussian shape (profile data only). + - `:peak_resolution_estimate`: An estimate of instrument resolution based on FWHM. + - `:mean_peaks_per_spectrum`: The average number of peaks detected per spectrum. +""" +function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Dict, mass_accuracy_results; + spectrum_indices::AbstractVector{Int})::Dict + results = Dict{Symbol, Any}() + + # Determine acquisition mode from the analysis results, not from metadata + acquisition_mode = get(instrument_analysis, :acquisition_mode, :unknown) + + # Calculate estimated_mean_ppm_error for fallback logic + estimated_mean_ppm_error = 30.0 # Default if mass_accuracy_results is nothing or invalid + if mass_accuracy_results !== nothing && haskey(mass_accuracy_results, :global_accuracy) && isa(mass_accuracy_results[:global_accuracy], NamedTuple) + ppm_error_report = mass_accuracy_results[:global_accuracy] + mean_ppm_error_val = get(ppm_error_report, :mean_ppm_error, 30.0) + if isfinite(mean_ppm_error_val) + estimated_mean_ppm_error = mean_ppm_error_val + end + end + + if isempty(spectrum_indices) + @warn "No indices to sample for peak characteristics analysis." + # Provide sensible defaults if no analysis can be run + if acquisition_mode == :centroid + # Much more permissive defaults for centroid data + results[:mean_fwhm_ppm] = 50.0 + results[:median_fwhm_ppm] = 50.0 + results[:mean_gaussian_r2] = 0.0 # Disable shape filtering for centroids + results[:peak_resolution_estimate] = 20000.0 + results[:mean_peaks_per_spectrum] = 1000 + else + estimated_fwhm = estimated_mean_ppm_error * (acquisition_mode == :profile ? 3 : 2) + results[:mean_fwhm_ppm] = estimated_fwhm + results[:median_fwhm_ppm] = estimated_fwhm + results[:mean_gaussian_r2] = acquisition_mode == :profile ? 0.7 : 0.9 + results[:peak_resolution_estimate] = 1e6 / estimated_fwhm + results[:mean_peaks_per_spectrum] = 0 + end + return results + end + + if acquisition_mode == PROFILE + println(" Analyzing peak characteristics for PROFILE mode from $(length(spectrum_indices)) sample spectra...") + + peak_widths_ppm = Float64[] + r_squared_values = Float64[] + peak_counts = Int[] + fwhm_values = Float64[] + + spectra_analyzed = Base.Threads.Atomic{Int}(0) + peaks_analyzed = Base.Threads.Atomic{Int}(0) + results_lock = ReentrantLock() + + _iterate_spectra_fast(msi_data, spectrum_indices) do idx, mz, intensity + if length(mz) < 10 # Skip spectra with too few points + return + end + + Base.Threads.atomic_add!(spectra_analyzed, 1) + meta = msi_data.spectra_metadata[idx] + + # Detect peaks with lower SNR threshold to find more peaks + peaks = detect_peaks_profile_core(mz, intensity; snr_threshold=2.0) + lock(results_lock) do + push!(peak_counts, length(peaks)) + end + + if !isempty(peaks) + # Analyze the strongest 3 peaks per spectrum + sorted_peaks = sort(peaks, by=p->p.intensity, rev=true) + for peak in sorted_peaks[1:min(3, length(sorted_peaks))] + try + # Find the index of the peak in the original mz array + peak_idx = argmin(abs.(mz .- peak.mz)) + + fwhm_delta_m = calculate_robust_fwhm(mz, intensity, peak_idx) + + if !isnan(fwhm_delta_m) && fwhm_delta_m > 0.001 && fwhm_delta_m < 0.5 # Reasonable range in Da + fwhm_ppm = 1e6 * fwhm_delta_m / peak.mz + if 5.0 < fwhm_ppm < 500.0 # Reasonable ppm range + lock(results_lock) do + push!(peak_widths_ppm, fwhm_ppm) + push!(fwhm_values, fwhm_delta_m) + + r2 = _fit_gaussian_and_r2(mz, intensity, peak_idx, 5) + push!(r_squared_values, r2) + end + Base.Threads.atomic_add!(peaks_analyzed, 1) + + if peaks_analyzed[] <= 3 + println("DEBUG: Peak at m/z $(peak.mz), FWHM = $(fwhm_ppm) ppm, R² = $(r_squared_values[end])") + end + end + end + catch e + continue + end + end + end + end + + println("DEBUG: Analyzed $(peaks_analyzed[]) peaks from $(spectra_analyzed[]) spectra") + + if !isempty(peak_widths_ppm) + results[:mean_fwhm_ppm] = mean(peak_widths_ppm) + results[:median_fwhm_ppm] = median(peak_widths_ppm) + results[:mean_gaussian_r2] = mean(r_squared_values) + results[:peak_resolution_estimate] = 1e6 / results[:mean_fwhm_ppm] + println(" - Actual FWHM measurement: $(round(results[:mean_fwhm_ppm], digits=2)) ppm") + else + # Fallback if no valid peaks found in PROFILE mode + estimated_fwhm = estimated_mean_ppm_error * 3 # FWHM typically wider than mass error + results[:mean_fwhm_ppm] = estimated_fwhm + results[:median_fwhm_ppm] = estimated_fwhm + results[:mean_gaussian_r2] = 0.7 + results[:peak_resolution_estimate] = 1e6 / estimated_fwhm + println(" - Estimated FWHM (from mass accuracy): $estimated_fwhm ppm") + end + + if !isempty(peak_counts) + results[:mean_peaks_per_spectrum] = mean(peak_counts) + else + results[:mean_peaks_per_spectrum] = 0 + end + + else # CENTROID mode + println(" Analyzing peak characteristics for CENTROID mode from $(length(spectrum_indices)) sample spectra...") + + peak_counts = Int[] + + results_lock = ReentrantLock() + + _iterate_spectra_fast(msi_data, spectrum_indices) do idx, mz, intensity + if !isempty(mz) + lock(results_lock) do + push!(peak_counts, length(mz)) + end + end + end + + if !isempty(peak_counts) + results[:mean_peaks_per_spectrum] = mean(peak_counts) + results[:median_peaks_per_spectrum] = median(peak_counts) + results[:total_peaks_detected] = sum(peak_counts) + else + results[:mean_peaks_per_spectrum] = 0 + results[:median_peaks_per_spectrum] = 0 + results[:total_peaks_detected] = 0 + end + + # For centroid data, use much more permissive parameters + # Don't estimate FWHM from mass accuracy - use reasonable defaults + results[:mean_fwhm_ppm] = 50.0 # Reasonable default for centroid data + results[:median_fwhm_ppm] = 50.0 + results[:mean_gaussian_r2] = 0.0 # Disable shape filtering for centroids + results[:peak_resolution_estimate] = 20000.0 # Reasonable estimate + + println(" - Mean peaks per spectrum: $(round(results[:mean_peaks_per_spectrum], digits=1))") + println(" - Using permissive FWHM for centroid data: 50.0 ppm") + println(" - Shape filtering disabled for centroid data") + end + + # Common prints + println(" - Mean Gaussian R²: $(round(get(results, :mean_gaussian_r2, 0.0), digits=3))") + println(" - Mean peaks per spectrum: $(round(get(results, :mean_peaks_per_spectrum, 0.0), digits=1))") + + return results +end + +""" + generate_preprocessing_recommendations(analysis_results::Dict)::Dict{Symbol, Any} + +Generates intelligent preprocessing recommendations by synthesizing the results from +various analysis functions (`analyze_instrument_characteristics`, `analyze_signal_quality`, etc.). + +# Arguments +- `analysis_results::Dict`: A dictionary containing the comprehensive analysis results from + the `run_preprocessing_analysis` pipeline. + +# Returns +- `Dict{Symbol, Any}`: A dictionary where keys are preprocessing step names (e.g., `:smoothing`, + `:peak_picking`) and values are dictionaries of recommended parameters for that step. +""" +function generate_preprocessing_recommendations(analysis_results::Dict)::Dict{Symbol, Any} + recommendations = Dict{Symbol, Any}() + + inst_analysis = get(analysis_results, :instrument_analysis, Dict()) + signal_analysis = get(analysis_results, :signal_analysis, Dict()) + mass_accuracy = get(analysis_results, :mass_accuracy, Dict()) + peak_analysis = get(analysis_results, :peak_analysis, Dict()) + + # Stabilization Recommendations + recommendations[:stabilization] = generate_stabilization_recommendations(signal_analysis) + + # Baseline Correction Recommendations + recommendations[:baseline_correction] = generate_baseline_recommendations(inst_analysis, signal_analysis) + + # Smoothing Recommendations + recommendations[:smoothing] = generate_smoothing_recommendations(inst_analysis, peak_analysis) + + # Peak Picking Recommendations - pass instrument analysis + recommendations[:peak_picking] = generate_peak_picking_recommendations(signal_analysis, peak_analysis, inst_analysis) + + # Normalization Recommendations + recommendations[:normalization] = generate_normalization_recommendations(signal_analysis) + + # Alignment Recommendations + recommendations[:alignment] = generate_alignment_recommendations(mass_accuracy, inst_analysis) + + # Binning Recommendations + recommendations[:binning] = generate_binning_recommendations(peak_analysis, mass_accuracy) + + return recommendations +end + +"""Generate baseline correction recommendations based on data properties.""" +function generate_baseline_recommendations(inst_analysis, signal_analysis) + recommendations = Dict{Symbol, Any}() + + # Determine baseline correction method based on data characteristics + acquisition_mode = get(inst_analysis, :acquisition_mode, :unknown) + noise_level = get(signal_analysis, :noise_mean, 1.0) + + if acquisition_mode == :profile + recommendations[:method] = "SNIP" + recommendations[:window_size] = 200 # Default, can be optimized + recommendations[:iterations] = 100 + else + recommendations[:method] = "linear" + recommendations[:noise_threshold] = noise_level * 3 + end + + return recommendations +end + +"""Generate smoothing recommendations based on peak width and m/z step.""" +function generate_smoothing_recommendations(inst_analysis, peak_analysis) + recommendations = Dict{Symbol, Any}() + + mz_step = get(inst_analysis, :average_mz_step, 0.01) + fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, 20.0) + + # Convert FWHM from ppm to m/z units for typical m/z + typical_mz = 500.0 + fwhm_mz = typical_mz * fwhm_ppm / 1e6 + + # Savitzky-Golay window should be ~FWHM in points + window_points = max(5, min(21, round(Int, fwhm_mz / mz_step))) + # Ensure odd number + window_points = isodd(window_points) ? window_points : window_points + 1 + + recommendations[:method] = "Savitzky-Golay" + recommendations[:window_size] = window_points + recommendations[:polynomial_order] = 3 + + return recommendations +end + +"""Generate peak picking recommendations from signal and peak analyses.""" +function generate_peak_picking_recommendations(signal_analysis, peak_analysis, inst_analysis) + recommendations = Dict{Symbol, Any}() + + acquisition_mode = get(inst_analysis, :acquisition_mode, :profile) + + if acquisition_mode == :centroid + # Much more permissive parameters for centroid data + recommendations[:snr_threshold] = 2.0 # Lower threshold for centroid + recommendations[:min_peak_width_ppm] = 0.0 # No minimum width for centroids + recommendations[:max_peak_width_ppm] = 200.0 # Very wide maximum for centroids + recommendations[:reason] = "Centroid data: using permissive parameters" + else + # Existing profile mode logic + snr_threshold = get(signal_analysis, :suggested_snr, 3.0) + fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, 20.0) + + recommendations[:snr_threshold] = snr_threshold + recommendations[:min_peak_width_ppm] = fwhm_ppm * 0.5 + recommendations[:max_peak_width_ppm] = fwhm_ppm * 3.0 + recommendations[:reason] = "Profile data: using standard parameters" + end + + return recommendations +end + +"""Generate normalization recommendations based on TIC variation.""" +function generate_normalization_recommendations(signal_analysis) + recommendations = Dict{Symbol, Any}() + + tic_cv = get(signal_analysis, :tic_cv, 0.5) + + if tic_cv < 0.3 # Low TIC variation + recommendations[:method] = "TIC" + recommendations[:reason] = "Low TIC variation across spectra" + else # High TIC variation + recommendations[:method] = "RMS" + recommendations[:reason] = "High TIC variation, using robust normalization" + end + + return recommendations +end + +"""Generate alignment recommendations based on calibration status and mass error.""" +function generate_alignment_recommendations(mass_accuracy, inst_analysis) + recommendations = Dict{Symbol, Any}() + + calibration_status = get(inst_analysis, :calibration_status, :uncalibrated) + + mean_ppm_error_val = 10.0 # Default value + if mass_accuracy !== nothing && haskey(mass_accuracy, :global_accuracy) && isa(mass_accuracy[:global_accuracy], NamedTuple) + ppm_error_report = mass_accuracy[:global_accuracy] + mean_ppm_error_val = get(ppm_error_report, :mean_ppm_error, 10.0) + end + + if calibration_status == :uncalibrated || mean_ppm_error_val > 20.0 + recommendations[:method] = "reference_based" + recommendations[:max_ppm_shift] = 50.0 + recommendations[:required] = true + else + recommendations[:method] = "none" + recommendations[:required] = false + end + + return recommendations +end + +"""Generate binning recommendations based on peak width and mass accuracy.""" +function generate_binning_recommendations(peak_analysis, mass_accuracy) + recommendations = Dict{Symbol, Any}() + + fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, 20.0) + + # Handle the case when mass_accuracy is nothing or has NaN values + suggested_tolerance = 20.0 # Default value + if mass_accuracy !== nothing + tol = get(mass_accuracy, :suggested_bin_tolerance, 20.0) + if !isnan(tol) && isfinite(tol) + suggested_tolerance = tol + end + end + + # Ensure fwhm_ppm is valid + if isnan(fwhm_ppm) || !isfinite(fwhm_ppm) + fwhm_ppm = 20.0 + end + + # Bin width should be ~FWHM/2 to preserve resolution while reducing data size + bin_width_ppm = max(fwhm_ppm * 0.5, suggested_tolerance) + + recommendations[:method] = "adaptive" + recommendations[:bin_width_ppm] = bin_width_ppm + recommendations[:min_peaks_per_bin] = 3 + + return recommendations +end + +"""Generate intensity stabilization recommendations.""" +function generate_stabilization_recommendations(signal_analysis) + recommendations = Dict{Symbol, Any}() + # Default to sqrt, as it's a common and generally robust transformation. + # More advanced logic could analyze intensity distribution skewness if needed. + recommendations[:method] = :sqrt + return recommendations +end + +# ============================================================================= +# Pre-Analysis Pipeline for Auto Parameter Determination +# ============================================================================= + +""" + run_preprocessing_analysis(msi_data; ...) + +Runs a comprehensive pre-analysis pipeline to determine optimal preprocessing parameters. +This function orchestrates a series of analysis steps on a sample of the dataset to +provide intelligent defaults for a full preprocessing workflow. + +The pipeline consists of several phases: +1. **Instrument & Data Characteristics**: Infers acquisition mode, m/z axis type, etc. +2. **Noise & Signal Quality**: Estimates noise, SNR, and TIC variation. +3. **Mass Accuracy**: Calculates PPM error against reference peaks (if provided). +4. **Spatial Regions**: Analyzes regional variations (if masks are provided). +5. **Peak Characteristics**: Measures peak width, shape, and density. +6. **Recommendations**: Synthesizes all analysis results into actionable parameter suggestions. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `reference_peaks::Dict`: Optional. Known m/z values for mass accuracy analysis. +- `region_masks::Dict`: Optional. Named `BitMatrix` masks for regional analysis. +- `sample_size::Int`: The number of spectra to sample for the analysis. +- `mask_path::String`: Optional path to a PNG mask to restrict analysis to a specific ROI. +- `spectrum_indices::AbstractVector{Int}`: Optional vector of indices to restrict analysis to, + overriding `mask_path` and `sample_size` for selection. + +# Returns +- `Dict{Symbol, Any}`: A nested dictionary containing the results of each analysis phase + and a final `:recommendations` dictionary. The recommendations are also stored in + `msi_data.preprocessing_hints`. +""" +function run_preprocessing_analysis(msi_data::MSIData; + reference_peaks::Dict{Float64, String}=Dict{Float64, String}(), + region_masks::Dict{Symbol, BitMatrix}=Dict{Symbol, BitMatrix}(), + sample_size::Int=100, + mask_path::Union{String, Nothing}=nothing, + spectrum_indices::Union{AbstractVector{Int}, Nothing}=nothing)::Dict{Symbol, Any} + + println("="^60) + println("RUNNING PRE-ANALYSIS PIPELINE") + println("="^60) + + analysis_results = Dict{Symbol, Any}() + + local all_available_indices::AbstractVector{Int} + + if spectrum_indices !== nothing + println("Using provided list of $(length(spectrum_indices)) spectrum indices.") + all_available_indices = spectrum_indices + elseif mask_path !== nothing + println("Applying mask from: $(mask_path)") + try + mask_matrix = load_and_prepare_mask(mask_path, msi_data.image_dims) + masked_indices_set = get_masked_spectrum_indices(msi_data, mask_matrix) + all_available_indices = collect(masked_indices_set) + println("Mask applied. $(length(all_available_indices)) spectra are within the masked region.") + catch e + @error "Failed to load or apply mask: $e. Proceeding without mask." + all_available_indices = 1:length(msi_data.spectra_metadata) + end + else + all_available_indices = 1:length(msi_data.spectra_metadata) + end + + if isempty(all_available_indices) + @warn "No spectra available for analysis (after applying mask/filter). Returning empty results." + return analysis_results + end + + # Create a single sample set from the available indices + num_available = length(all_available_indices) + indices_to_sample = if num_available > sample_size + # Use StatsBase.sample for sampling without replacement + sample(all_available_indices, sample_size, replace=false) + else + # Use all available indices if they are fewer than the sample size + collect(all_available_indices) + end + + # Ensure analytics are precomputed + if !is_set(msi_data.analytics_ready) + println("Pre-computing basic analytics...") + precompute_analytics(msi_data) + end + + # Phase 1: Instrument and Data Characteristics + println("\n--- Phase 1: Instrument & Data Characteristics ---") + instrument_analysis = analyze_instrument_characteristics(msi_data, sample_indices=indices_to_sample) + analysis_results[:instrument_analysis] = instrument_analysis + + # Phase 2: Noise and Signal Quality Analysis + println("\n--- Phase 2: Noise & Signal Quality Analysis ---") + signal_analysis = analyze_signal_quality(msi_data, sample_indices=indices_to_sample) + analysis_results[:signal_analysis] = signal_analysis + + # Phase 3: Mass Accuracy Analysis + println("\n--- Phase 3: Mass Accuracy Analysis ---") + if !isempty(reference_peaks) + mass_accuracy_analysis = analyze_mass_accuracy_global(msi_data, reference_peaks, spectrum_indices=indices_to_sample) + analysis_results[:mass_accuracy] = mass_accuracy_analysis + else + println("No reference peaks provided - skipping mass accuracy analysis") + analysis_results[:mass_accuracy] = nothing + end + + # Phase 4: Spatial Region Analysis (if masks provided) + # This function is not affected by the global mask, as it analyzes specific, named regions. + println("\n--- Phase 4: Spatial Region Analysis ---") + if !isempty(region_masks) + regional_analysis = analyze_spatial_regions(msi_data, region_masks, reference_peaks) + analysis_results[:regional_analysis] = regional_analysis + else + println("No region masks provided - skipping regional analysis") + analysis_results[:regional_analysis] = nothing + end + + # Phase 5: Peak Characteristics Analysis + println("\n--- Phase 5: Peak Characteristics Analysis ---") + peak_analysis = analyze_peak_characteristics(msi_data, instrument_analysis, analysis_results[:mass_accuracy], spectrum_indices=indices_to_sample) + analysis_results[:peak_analysis] = peak_analysis + + # Phase 6: Generate Preprocessing Recommendations + println("\n--- Phase 6: Generating Preprocessing Recommendations ---") + recommendations = generate_preprocessing_recommendations(analysis_results) + analysis_results[:recommendations] = recommendations + + # Store in MSIData object + msi_data.preprocessing_hints = recommendations + + println("\n" * "="^60) + println("PRE-ANALYSIS COMPLETE") + println("="^60) + + return analysis_results +end + +""" + calculate_ppm_error(measured_mz::Real, theoretical_mz::Real) -> Float64 + +Calculates the mass accuracy error in parts-per-million (PPM) between a measured +and a theoretical m/z value. + +# Arguments +- `measured_mz::Real`: The experimentally measured m/z value. +- `theoretical_mz::Real`: The known, theoretical m/z value of a compound. + +# Returns +- `Float64`: The calculated PPM error. Returns `Inf` if `theoretical_mz` is zero. + +# Formula +`PPM = 10^6 * |measured_mz - theoretical_mz| / theoretical_mz` + +# Example +```julia +calculate_ppm_error(100.005, 100.0) # returns 50.0 +``` +""" +function calculate_ppm_error(measured_mz::Real, theoretical_mz::Real) + if theoretical_mz == 0 + return Inf + end + return 1e6 * abs(Float64(measured_mz) - Float64(theoretical_mz)) / Float64(theoretical_mz) +end + +""" + calculate_ppm_error_bulk(measured_mz::Vector{<:Real}, theoretical_mz::Vector{<:Real}) -> Vector{Float64} + +Calculates PPM errors for multiple pairs of measured and theoretical mass values. + +# Arguments +- `measured_mz::Vector{<:Real}`: A vector of experimentally measured m/z values. +- `theoretical_mz::Vector{<:Real}`: A vector of known, theoretical m/z values. + +# Returns +- `Vector{Float64}`: A vector containing the calculated PPM error for each pair. +""" +function calculate_ppm_error_bulk(measured_mz::Vector{Real}, theoretical_mz::Vector{Real}) + return [calculate_ppm_error(m, t) for (m, t) in zip(measured_mz, theoretical_mz)] +end + +""" + calculate_resolution_fwhm(mz::Real, profile_mz::AbstractVector{<:Real}, profile_intensity::AbstractVector{<:Real}) -> Float64 + +Calculates the mass resolution of a peak in profile-mode data using the Full Width at +Half Maximum (FWHM) method. Resolution is a measure of an instrument's ability to +distinguish between two peaks of slightly different mass-to-charge ratios. + +# Arguments +- `mz::Real`: The m/z value of the peak's centroid. +- `profile_mz::AbstractVector{<:Real}`: The full m/z array from the profile-mode spectrum. +- `profile_intensity::AbstractVector{<:Real}`: The full intensity array from the profile-mode spectrum. + +# Returns +- `Float64`: The calculated resolution (`m / Δm`). Returns `NaN` if the FWHM cannot be determined (e.g., peak is at the edge of the spectrum). + +# Formula +`Resolution = m / Δm`, where `Δm` is the FWHM. +""" +function calculate_resolution_fwhm(mz::Real, profile_mz::AbstractVector{<:Real}, + profile_intensity::AbstractVector{<:Real}) + + # Find peak center index + peak_idx = argmin(abs.(profile_mz .- mz)) + peak_height = Float64(profile_intensity[peak_idx]) + half_max = peak_height / 2 + + # Find left half-maximum point (interpolate for accuracy) + left_idx = find_last_below(profile_intensity[1:peak_idx], half_max) + if left_idx == 0 || left_idx == length(profile_intensity[1:peak_idx]) + return NaN + end + + # Linear interpolation for left FWHM + x1, x2 = Float64(profile_mz[left_idx]), Float64(profile_mz[left_idx+1]) + y1, y2 = Float64(profile_intensity[left_idx]), Float64(profile_intensity[left_idx+1]) + denominator = y2 - y1 + if denominator == 0 + left_fwhm = NaN + else + left_fwhm = x1 + (x2 - x1) * (half_max - y1) / denominator + end + + # Find right half-maximum point + right_slice = profile_intensity[peak_idx:end] + right_offset = find_first_below(right_slice, half_max) + if right_offset == 0 || right_offset == length(right_slice) + return NaN + end + + right_idx = peak_idx + right_offset - 1 + x1, x2 = Float64(profile_mz[right_idx-1]), Float64(profile_mz[right_idx]) + y1, y2 = Float64(profile_intensity[right_idx-1]), Float64(profile_intensity[right_idx]) + denominator = y2 - y1 + if denominator == 0 + right_fwhm = NaN + else + right_fwhm = x1 + (x2 - x1) * (half_max - y1) / denominator + end + + fwhm = right_fwhm - left_fwhm + return fwhm > 0 ? Float64(mz) / fwhm : NaN +end + +"""Helper to find the last index in a vector with a value below a threshold, used for FWHM.""" +function find_last_below(v::AbstractVector{<:Real}, threshold::Real) + for i in length(v):-1:2 + if v[i] >= threshold && v[i-1] < threshold + return i-1 + end + end + return 0 +end + +"""Helper to find the first index in a vector with a value below a threshold, used for FWHM.""" +function find_first_below(v::AbstractVector{<:Real}, threshold::Real) + for i in 1:(length(v)-1) + if v[i] >= threshold && v[i+1] < threshold + return i+1 + end + end + return 0 +end + +""" + _calculate_fwhm_delta_m(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real}, peak_idx::Int) -> Float64 + +Calculates the Full Width at Half Maximum (FWHM) in m/z units (Δm) for a peak. +Returns `NaN` if FWHM cannot be determined. +""" +function _calculate_fwhm_delta_m(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real}, peak_idx::Int) + peak_height = Float64(intensity[peak_idx]) + half_max = peak_height / 2 + + # Find left half-maximum point + left_idx = find_last_below(intensity[1:peak_idx], half_max) + if left_idx == 0 || left_idx == length(intensity[1:peak_idx]) + return NaN + end + + # Linear interpolation for left FWHM m/z + x1, x2 = Float64(mz[left_idx]), Float64(mz[left_idx+1]) + y1, y2 = Float64(intensity[left_idx]), Float64(intensity[left_idx+1]) + denominator = y2 - y1 + if denominator == 0 + left_fwhm_mz = NaN + else + left_fwhm_mz = x1 + (x2 - x1) * (half_max - y1) / denominator + end + + # Find right half-maximum point + right_slice = intensity[peak_idx:end] + right_offset = find_first_below(right_slice, half_max) + if right_offset == 0 || right_offset == length(right_slice) + return NaN + end + + right_idx = peak_idx + right_offset - 1 + x1, x2 = Float64(mz[right_idx-1]), Float64(mz[right_idx]) + y1, y2 = Float64(intensity[right_idx-1]), Float64(intensity[right_idx]) + denominator = y2 - y1 + if denominator == 0 + right_fwhm_mz = NaN + else + right_fwhm_mz = x1 + (x2 - x1) * (half_max - y1) / denominator + end + + return right_fwhm_mz - left_fwhm_mz +end + +""" + _fit_gaussian_and_r2(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real}, peak_idx::Int, half_window::Int) -> Float64 + +Estimates Gaussian parameters for a peak and returns a pseudo R^2 value. +This is an approximation and not a full non-linear least squares fit. +""" +function _fit_gaussian_and_r2(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real}, peak_idx::Int, half_window::Int) + n = length(mz) + if n < 3 || peak_idx <= 0 || peak_idx > n + return 0.0 + end + + # Define the region around the peak + start_idx = max(1, peak_idx - half_window) + end_idx = min(n, peak_idx + half_window) + + # Ensure there's enough data to fit + count = end_idx - start_idx + 1 + if count < 3 + return 0.0 + end + + # Estimate Gaussian parameters + # Amplitude (A): peak intensity + A_est = float(intensity[peak_idx]) + # Mean (μ): m/z at peak intensity + mu_est = float(mz[peak_idx]) + # Standard deviation (σ): related to FWHM. FWHM = 2 * sqrt(2 * ln(2)) * σ ≈ 2.355 * σ + # So, σ ≈ FWHM / 2.355 + fwhm_delta_m = _calculate_fwhm_delta_m(mz, intensity, peak_idx) + if isnan(fwhm_delta_m) || fwhm_delta_m <= 0 + return 0.0 # Cannot estimate sigma without a valid FWHM + end + sigma_est = fwhm_delta_m / 2.355 + + # If sigma is too small, it might lead to division by zero or very sharp peaks + if sigma_est < eps(Float64) + return 0.0 + end + + # Calculate SS_res, mean_y in a single pass to avoid allocations + SS_res = 0.0 + sum_y = 0.0 + + @inbounds for i in start_idx:end_idx + x_val = float(mz[i]) + y_val = float(intensity[i]) + + # Gaussian function estimate + y_est = A_est * exp(-((x_val - mu_est)^2) / (2 * sigma_est^2)) + + SS_res += (y_val - y_est)^2 + sum_y += y_val + end + + mean_y = sum_y / count + SS_tot = 0.0 + + @inbounds for i in start_idx:end_idx + SS_tot += (float(intensity[i]) - mean_y)^2 + end + + if SS_tot == 0 + return 1.0 # Perfect fit if all y_data are the same + end + + r_squared = 1.0 - (SS_res / SS_tot) + return max(0.0, r_squared) # R^2 can be negative if fit is worse than mean, cap at 0 +end + +""" + calculate_robust_fwhm(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real}, peak_idx::Int) -> Float64 + +A more robust FWHM calculation that handles edge cases better. +""" +function calculate_robust_fwhm(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real}, peak_idx::Int) + n = length(mz) + if n < 5 || peak_idx < 3 || peak_idx > n-2 + return NaN + end + + peak_height = Float64(intensity[peak_idx]) + half_max = peak_height / 2.0 + + # Find left half-maximum with bounds checking + left_idx = peak_idx + while left_idx > 1 && intensity[left_idx] >= half_max + left_idx -= 1 + end + + if left_idx == 1 || left_idx >= n-1 + return NaN + end + + # Linear interpolation for left FWHM + x1, x2 = Float64(mz[left_idx]), Float64(mz[left_idx+1]) + y1, y2 = Float64(intensity[left_idx]), Float64(intensity[left_idx+1]) + + if y2 == y1 # Avoid division by zero + left_fwhm_mz = x1 + else + left_fwhm_mz = x1 + (x2 - x1) * (half_max - y1) / (y2 - y1) + end + + # Find right half-maximum + right_idx = peak_idx + while right_idx < n && intensity[right_idx] >= half_max + right_idx += 1 + end + + if right_idx == n || right_idx <= 2 + return NaN + end + + # Linear interpolation for right FWHM + x1, x2 = Float64(mz[right_idx-1]), Float64(mz[right_idx]) + y1, y2 = Float64(intensity[right_idx-1]), Float64(intensity[right_idx]) + + if y2 == y1 # Avoid division by zero + right_fwhm_mz = x1 + else + right_fwhm_mz = x1 + (x2 - x1) * (half_max - y1) / (y2 - y1) + end + + fwhm = right_fwhm_mz - left_fwhm_mz + + # Validate result + if fwhm <= 0 || !isfinite(fwhm) || fwhm > 1.0 # Unreasonably large + return NaN + end + + return fwhm +end + +""" + main_precalculation(msi_data::MSIData; ...) + +Runs the non-verbose pre-analysis pipeline and returns a dictionary of recommended +preprocessing parameters based on data characteristics and heuristics. + +This function serves as a quiet entry point to the analysis engine, translating the +analytical results into a concrete set of parameters for a preprocessing pipeline. +It also categorizes parameters that cannot be automatically determined. + +# Arguments +- `msi_data::MSIData`: The main MSI data object. +- `reference_peaks::Dict`: Optional dictionary of reference m/z values for mass accuracy analysis. +- `region_masks::Dict`: Optional dictionary of named `BitMatrix` masks for regional analysis. +- `sample_size::Int`: The number of spectra to sample for statistical analysis. +- `mask_path::String`: Optional path to a PNG mask file to restrict the analysis to a specific ROI. +- `spectrum_indices::AbstractVector{Int}`: Optional vector of spectrum indices to restrict analysis to. + +# Returns +- A `Dict` with two keys: + - `"recommended_parameters"`: A `Dict{Symbol, Any}` of suggested parameter values. + - `"unsupported_parameters"`: A `Dict` categorizing parameters that could not be determined. +""" +function main_precalculation(msi_data::MSIData; + reference_peaks::Dict{Float64, String}=Dict{Float64, String}(), + region_masks::Dict{Symbol, BitMatrix}=Dict{Symbol, BitMatrix}(), + sample_size::Int=100, + mask_path::Union{String, Nothing}=nothing, + spectrum_indices::Union{AbstractVector{Int}, Nothing}=nothing)::Dict + + # --- Run analysis pipeline quietly --- + local analysis_results + original_stdout = stdout + # Redirect stdout to the system's null device to robustly silence output + null_stream = open(Sys.iswindows() ? "nul" : "/dev/null", "w") + redirect_stdout(null_stream) + try + analysis_results = run_preprocessing_analysis(msi_data, + reference_peaks=reference_peaks, + region_masks=region_masks, + sample_size=sample_size, + mask_path=mask_path, + spectrum_indices=spectrum_indices + ) + finally + redirect_stdout(original_stdout) + close(null_stream) + end + + if isempty(analysis_results) + @warn "Preprocessing analysis returned no results. Cannot generate recommendations." + return Dict() # Return an empty dictionary if no results + end + + # --- Safely get nested dictionaries --- + recs = get(analysis_results, :recommendations, Dict()) + signal_analysis = get(analysis_results, :signal_analysis, Dict()) + peak_analysis = get(analysis_results, :peak_analysis, Dict()) + mass_accuracy = get(analysis_results, :mass_accuracy, nothing) # Can be nothing + inst_analysis = get(analysis_results, :instrument_analysis, Dict()) + + # Initialize parameter dictionaries for each step + stab_params = Dict{Symbol, Any}() + cal_params = Dict{Symbol, Any}() + sm_params = Dict{Symbol, Any}() + bc_params = Dict{Symbol, Any}() + norm_params = Dict{Symbol, Any}() + pp_params = Dict{Symbol, Any}() + pa_params = Dict{Symbol, Any}() + ps_params = Dict{Symbol, Any}() + pb_params = Dict{Symbol, Any}() + + # --- Populate Parameters for each step --- + # Stabilization + if !isempty(recs) && haskey(recs, :stabilization) + stab_rec = recs[:stabilization] + stab_params[:method] = get(stab_rec, :method, :sqrt) + else + stab_params[:method] = :sqrt # Default + end + + # Calibration & Alignment (Note: These are intertwined in the current logic) + calibration_required = false + mean_ppm_error = NaN + suggested_bin_tol = NaN + if mass_accuracy !== nothing + mean_ppm_error = get(get(mass_accuracy, :global_accuracy, Dict()), :mean_ppm_error, NaN) + suggested_bin_tol = get(mass_accuracy, :suggested_bin_tolerance, NaN) + end + + if !isempty(recs) && haskey(recs, :alignment) && get(recs[:alignment], :required, false) + calibration_required = true + cal_params[:method] = :internal_standards + cal_params[:fit_order] = 2 # Default from struct + if isfinite(suggested_bin_tol) + cal_params[:ppm_tolerance] = suggested_bin_tol + else + cal_params[:ppm_tolerance] = nothing + end + cal_params[:internal_standards] = nothing # User input dependent + cal_params[:base_peak_mz_references] = nothing # User input dependent + + if isfinite(mean_ppm_error) + pa_params[:method] = mean_ppm_error > 30.0 ? :lowess : :linear + else + pa_params[:method] = :lowess # Default + end + + tic_cv = get(signal_analysis, :tic_cv, NaN) + if isfinite(tic_cv) && get(pa_params, :method, :none) == :lowess + pa_params[:span] = round(max(0.3, min(0.8, 1.0 - tic_cv / 2)), digits=2) + else + pa_params[:span] = nothing + end + + if isfinite(suggested_bin_tol) + pa_params[:tolerance] = suggested_bin_tol + pa_params[:tolerance_unit] = :ppm + else + pa_params[:tolerance] = nothing + pa_params[:tolerance_unit] = :ppm # Default + end + pa_params[:max_shift_ppm] = get(recs[:alignment], :max_ppm_shift, 50.0) + pa_params[:min_matched_peaks] = nothing # User input dependent + else + cal_params[:method] = :none + cal_params[:ppm_tolerance] = nothing + cal_params[:fit_order] = nothing + cal_params[:internal_standards] = nothing + cal_params[:base_peak_mz_references] = nothing + + pa_params[:method] = :none + pa_params[:span] = nothing + pa_params[:tolerance] = nothing + pa_params[:tolerance_unit] = :ppm + pa_params[:max_shift_ppm] = nothing + pa_params[:min_matched_peaks] = nothing + end + + # Smoothing + if !isempty(recs) && haskey(recs, :smoothing) + sm_rec = recs[:smoothing] + if get(sm_rec, :method, "") == "Savitzky-Golay" + sm_params[:method] = :savitzky_golay + sm_params[:window] = get(sm_rec, :window_size, nothing) + sm_params[:order] = get(sm_rec, :polynomial_order, nothing) + else + sm_params[:method] = :none + sm_params[:window] = nothing + sm_params[:order] = nothing + end + else + sm_params[:method] = :none + sm_params[:window] = nothing + sm_params[:order] = nothing + end + + # Baseline Correction + if !isempty(recs) && haskey(recs, :baseline_correction) + bl_rec = recs[:baseline_correction] + if get(bl_rec, :method, "") == "SNIP" + bc_params[:method] = :snip + bc_params[:iterations] = get(bl_rec, :iterations, nothing) + else + bc_params[:method] = :none + bc_params[:iterations] = nothing + end + else + bc_params[:method] = :none + bc_params[:iterations] = nothing + end + + if get(inst_analysis, :acquisition_mode, :unknown) == :profile + mean_fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, NaN) + avg_mz_step = get(inst_analysis, :average_mz_step, NaN) + if isfinite(mean_fwhm_ppm) && isfinite(avg_mz_step) && avg_mz_step > 0 + fwhm_mz = 500.0 * mean_fwhm_ppm / 1e6 # At typical m/z 500 + bc_params[:window] = ceil(Int, fwhm_mz / avg_mz_step * 2) + else + bc_params[:window] = nothing + end + else + bc_params[:window] = nothing + end + + # Normalization + if !isempty(recs) && haskey(recs, :normalization) + method = get(recs[:normalization], :method, "") + if method == "TIC" + norm_params[:method] = :tic + elseif method == "RMS" + norm_params[:method] = :rms + else + norm_params[:method] = :none + end + else + norm_params[:method] = :none + end + + # Peak Picking + # Robust method selection based on acquisition mode + acquisition_mode = get(inst_analysis, :acquisition_mode, :unknown) + pp_params[:method] = acquisition_mode == :profile ? :profile : :centroid + + if acquisition_mode == :centroid + # Much more permissive parameters for centroid data + pp_params[:snr_threshold] = 2.0 # Lower for centroid + pp_params[:min_peak_width_ppm] = 0.0 # No minimum width + pp_params[:max_peak_width_ppm] = 200.0 # Very wide maximum + pp_params[:min_peak_shape_r2] = 0.0 # Disable shape filtering + + # Much lower prominence threshold for centroid + estimated_noise = get(signal_analysis, :noise_mean, NaN) + if isfinite(estimated_noise) + pp_params[:min_peak_prominence] = max(estimated_noise * 0.5, 0.001) # Much lower + else + pp_params[:min_peak_prominence] = 0.001 # Very permissive + end + + pp_params[:half_window] = 2 # Smaller window for centroid data + pp_params[:merge_peaks_tolerance] = 10.0 # More permissive merging + else # Profile mode logic + if !isempty(recs) && haskey(recs, :peak_picking) + pk_rec = recs[:peak_picking] + pp_params[:snr_threshold] = get(pk_rec, :snr_threshold, 2.0) # Default to 2.0 + pp_params[:min_peak_width_ppm] = get(pk_rec, :min_peak_width_ppm, nothing) + pp_params[:max_peak_width_ppm] = get(pk_rec, :max_peak_width_ppm, nothing) + else + pp_params[:snr_threshold] = 2.0 # Default to 2.0 + pp_params[:min_peak_width_ppm] = nothing + pp_params[:max_peak_width_ppm] = nothing + end + + # Robust prominence calculation with safety cap for profile + estimated_noise = get(signal_analysis, :noise_mean, NaN) + if isfinite(estimated_noise) + calculated_prominence = round(estimated_noise * 2, digits=4) + pp_params[:min_peak_prominence] = min(calculated_prominence, 0.005) + else + pp_params[:min_peak_prominence] = 0.005 + end + + if isfinite(suggested_bin_tol) + pp_params[:merge_peaks_tolerance] = round(suggested_bin_tol / 2, digits=4) + else + pp_params[:merge_peaks_tolerance] = nothing + end + + # Robust half_window calculation with safety floor for profile + mean_fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, NaN) + avg_mz_step = get(inst_analysis, :average_mz_step, NaN) + if isfinite(mean_fwhm_ppm) && isfinite(avg_mz_step) && avg_mz_step > 0 + fwhm_mz = 500.0 * mean_fwhm_ppm / 1e6 # At typical m/z 500 + window_points = fwhm_mz / avg_mz_step + calculated_half_window = ceil(Int, window_points / 2) + pp_params[:half_window] = max(calculated_half_window, 3) + else + pp_params[:half_window] = 5 + end + + # Robust R^2 calculation with floor for profile + mean_r2 = get(peak_analysis, :mean_gaussian_r2, NaN) + if isfinite(mean_r2) + pp_params[:min_peak_shape_r2] = round(max(0.0, mean_r2 * 0.8), digits=2) + else + pp_params[:min_peak_shape_r2] = 0.0 + end + end + + + # Peak Selection + if acquisition_mode == :centroid + # Much more permissive parameters for centroid data + ps_params[:min_snr] = 1.5 # Even lower than picking threshold + ps_params[:min_fwhm_ppm] = 0.0 # No minimum + ps_params[:max_fwhm_ppm] = 500.0 # Very wide maximum + ps_params[:min_shape_r2] = 0.0 # Disable shape filtering + ps_params[:frequency_threshold] = nothing # User input dependent / Hard to determine + ps_params[:correlation_threshold] = nothing # Hard to determine + else # Profile mode logic + if haskey(pp_params, :snr_threshold) && pp_params[:snr_threshold] !== nothing + ps_params[:min_snr] = pp_params[:snr_threshold] + else + ps_params[:min_snr] = nothing + end + if !isempty(peak_analysis) + mean_fwhm = get(peak_analysis, :mean_fwhm_ppm, NaN) + if isfinite(mean_fwhm) + ps_params[:min_fwhm_ppm] = round(mean_fwhm * 0.5, digits=2) + ps_params[:max_fwhm_ppm] = round(mean_fwhm * 2.5, digits=2) + else + ps_params[:min_fwhm_ppm] = nothing + ps_params[:max_fwhm_ppm] = nothing + end + mean_r2 = get(peak_analysis, :mean_gaussian_r2, NaN) + if isfinite(mean_r2) + ps_params[:min_shape_r2] = round(max(0.0, mean_r2 * 0.8), digits=2) + else + ps_params[:min_shape_r2] = 0.0 # Adjusted fallback + end + else + ps_params[:min_fwhm_ppm] = nothing + ps_params[:max_fwhm_ppm] = nothing + ps_params[:min_shape_r2] = nothing + end + ps_params[:frequency_threshold] = nothing + ps_params[:correlation_threshold] = nothing + end + + + # Peak Binning + if !isempty(recs) && haskey(recs, :binning) + bin_rec = recs[:binning] + if get(bin_rec, :method, "") == "adaptive" + pb_params[:method] = :adaptive + bin_width = get(bin_rec, :bin_width_ppm, NaN) + if isfinite(bin_width) + pb_params[:tolerance] = bin_width + pb_params[:max_bin_width_ppm] = round(bin_width * 3, digits=2) + else + pb_params[:tolerance] = nothing + pb_params[:max_bin_width_ppm] = nothing + end + pb_params[:tolerance_unit] = :ppm + pb_params[:min_peak_per_bin] = get(bin_rec, :min_peaks_per_bin, nothing) + pb_params[:intensity_weighted_centers] = true # Default from struct + pb_params[:num_uniform_bins] = nothing # User input dependent + pb_params[:frequency_threshold] = nothing # Hard to determine + else + pb_params[:method] = :none + pb_params[:tolerance] = nothing + pb_params[:max_bin_width_ppm] = nothing + pb_params[:tolerance_unit] = nothing + pb_params[:min_peak_per_bin] = nothing + pb_params[:intensity_weighted_centers] = true + pb_params[:num_uniform_bins] = nothing + pb_params[:frequency_threshold] = nothing + end + else + pb_params[:method] = :none + pb_params[:tolerance] = nothing + pb_params[:max_bin_width_ppm] = nothing + pb_params[:tolerance_unit] = nothing + pb_params[:min_peak_per_bin] = nothing + pb_params[:intensity_weighted_centers] = true + pb_params[:num_uniform_bins] = nothing + pb_params[:frequency_threshold] = nothing + end + + return Dict( + :Stabilization => stab_params, + :Calibration => cal_params, + :Smoothing => sm_params, + :BaselineCorrection => bc_params, + :Normalization => norm_params, + :PeakPicking => pp_params, + :PeakAlignment => pa_params, + :PeakSelection => ps_params, + :PeakBinning => pb_params + ) +end diff --git a/src/Preprocessing.jl b/src/Preprocessing.jl new file mode 100644 index 0000000..ecf977f --- /dev/null +++ b/src/Preprocessing.jl @@ -0,0 +1,1259 @@ +# src/Preprocessing.jl +""" +This module provides a comprehensive workflow for mass spectrometry imaging (MSI) data +preprocessing, inspired by the functionality of the R package MALDIquant and Cardinal. +It includes functions for quality control, intensity transformation, smoothing, +baseline correction, normalization, peak picking, alignment, and feature matrix +generation. +""" + +# ============================================================================= +# Dependencies +# ============================================================================= + +using Statistics # For mean, median +using SparseArrays +using StatsBase # For mad (Median Absolute Deviation) +using SavitzkyGolay # For SavitzkyGolay filtering +using Dates # For now() +using CSV # For writing CSV files +using DataFrames # For creating dataframes +using ContinuousWavelets # For CWT peak detection +using ImageFiltering # For localmaxima in detect_peaks_wavelet +using Interpolations # For calibration +using Loess # For robust peak alignment +using Base.Threads # For multithreading in apply functions + +# ============================================================================= +# Data Structures +# ============================================================================= + +""" + FeatureMatrix + +A struct to hold the final feature matrix generated from the preprocessing pipeline. + +# Fields +- `matrix::Array{Float64,2}`: The feature matrix where rows correspond to samples (spectra) + and columns correspond to features (m/z bins). +- `mz_bins::Vector{Tuple{Float64,Float64}}`: A vector of tuples defining the start and + end m/z for each bin (column) in the `matrix`. +- `sample_ids::Vector{Int}`: A vector of identifiers for each sample (row) in the `matrix`. +""" +struct FeatureMatrix + matrix::AbstractMatrix{Float64} + mz_bins::Vector{Tuple{Float64,Float64}} + sample_ids::Vector{Int} +end + +""" + MutableSpectrum + +A mutable struct to hold spectrum data. Using a mutable struct allows +in-place modification of fields (like intensity or m/z), which dramatically +reduces memory allocations compared to creating new immutable tuples at each step. + +# Fields +- `id::Int`: A unique identifier for the spectrum. +- `mz::AbstractVector{Float64}`: The m/z values of the spectrum. +- `intensity::AbstractVector{Float64}`: The intensity values corresponding to the m/z values. +- `peaks::Vector{NamedTuple}`: A vector of detected peaks, each a `NamedTuple` with fields + like `:mz`, `:intensity`, `:fwhm`, etc. +""" +mutable struct MutableSpectrum + id::Int + mz::AbstractVector{Float64} + intensity::AbstractVector{Float64} + peaks::Vector{NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), NTuple{6, Float64}}} +end + +# --- Core Pipeline Structs --- + +""" +An abstract type for all preprocessing steps. Allows for a modular and extensible +pipeline where users can define a sequence of operations. +""" +abstract type AbstractPreprocessingStep end + +# --- Preprocessing Step Definitions --- + +""" + Calibration(; method=:internal_standards, ...) + +A preprocessing step for mass calibration. Corrects systematic mass errors in the m/z axis. +Set a parameter to `nothing` to use an auto-determined value from the data where applicable. + +# Arguments +- `method::Symbol`: The calibration method. Currently supports `:internal_standards`. +- `internal_standards::Union{Dict{Float64, String}, Nothing}`: A dictionary mapping theoretical + m/z values of internal standards to their names. +- `base_peak_mz_references::Union{Vector{Float64}, Nothing}`: A vector of reference m/z values + for base peak calibration (not yet implemented). +- `ppm_tolerance::Union{Float64, Nothing}`: The tolerance in parts-per-million (ppm) for matching + peaks to internal standards. +- `fit_order::Int`: The polynomial order for the calibration fit (e.g., 1 for linear, 2 for quadratic). +""" +struct Calibration <: AbstractPreprocessingStep + method::Symbol + internal_standards::Union{Dict{Float64, String}, Nothing} + base_peak_mz_references::Union{Vector{Float64}, Nothing} + ppm_tolerance::Union{Float64, Nothing} + fit_order::Int + + function Calibration(; method=:internal_standards, internal_standards=nothing, base_peak_mz_references=nothing, ppm_tolerance=nothing, fit_order=2) + new(method, internal_standards, base_peak_mz_references, ppm_tolerance, fit_order) + end +end + +""" + BaselineCorrection(; method=:snip, ...) + +A preprocessing step for baseline correction. This step estimates and subtracts the +background noise (baseline) from the spectral intensities. + +# Arguments +- `method::Symbol`: The algorithm to use. Options include `:snip` (Sensitive Nonlinear + Iterative Peak clipping), `:convex_hull`, and `:median`. +- `iterations::Union{Int, Nothing}`: The number of iterations for the SNIP algorithm. + A higher number results in a more aggressive baseline. +- `window::Union{Int, Nothing}`: The window size for the `:median` method, determining + the local region for median calculation. +""" +struct BaselineCorrection <: AbstractPreprocessingStep + method::Symbol + iterations::Union{Int, Nothing} # For SNIP + window::Union{Int, Nothing} # For median + + function BaselineCorrection(; method=:snip, iterations=nothing, window=nothing) + new(method, iterations, window) + end +end + +""" + Smoothing(; method=:savitzky_golay, ...) + +A preprocessing step for spectral smoothing. This helps to reduce high-frequency noise +in the intensity data. + +# Arguments +- `method::Symbol`: The smoothing algorithm. Options are `:savitzky_golay` and `:moving_average`. +- `window::Union{Int, Nothing}`: The size of the smoothing window. For Savitzky-Golay, + this must be an odd integer. +- `order::Union{Int, Nothing}`: The polynomial order for the Savitzky-Golay filter. Must be + less than the window size. +""" +struct Smoothing <: AbstractPreprocessingStep + method::Symbol + window::Union{Int, Nothing} + order::Union{Int, Nothing} # For Savitzky-Golay + + function Smoothing(; method=:savitzky_golay, window=nothing, order=nothing) + new(method, window, order) + end +end + + + +""" + Normalization(; method=:tic) + +A preprocessing step for intensity normalization. This corrects for variations in total +ion current between different spectra, making them more comparable. + +# Arguments +- `method::Symbol`: The normalization method. Options include: + - `:tic`: Total Ion Current normalization (divides by the sum of intensities). + - `:median`: Divides by the median intensity. + - `:rms`: Root Mean Square normalization. + - `:none`: No normalization is applied. +""" +struct Normalization <: AbstractPreprocessingStep + method::Symbol + + function Normalization(; method=:tic) + new(method) + end +end + +""" + PeakPicking(; method=nothing, ...) + +A preprocessing step for peak detection. This step identifies peaks (signals of interest) +in the profile or centroided spectra. + +# Arguments +- `method::Union{Symbol, Nothing}`: The peak detection algorithm. + - `:profile`: For profile-mode data, using local maxima and quality filters. + - `:wavelet`: Continuous Wavelet Transform (CWT) based peak detection. + - `:centroid`: For centroid-mode data, essentially a filtering step. +- `snr_threshold::Union{Float64, Nothing}`: Signal-to-Noise Ratio threshold. Peaks with SNR + below this value are discarded. +- `half_window::Union{Int, Nothing}`: The number of data points to the left and right of a + potential peak to consider for local maximum detection (for `:profile`). +- `min_peak_prominence::Union{Float64, Nothing}`: The minimum required prominence of a peak, + expressed as a fraction of its height. +- `merge_peaks_tolerance::Union{Float64, Nothing}`: The m/z tolerance within which to merge + adjacent peaks, keeping the more intense one. +- `min_peak_width_ppm, max_peak_width_ppm`: Minimum and maximum acceptable peak width (FWHM) in ppm. +- `min_peak_shape_r2`: Minimum R-squared value from a Gaussian fit to the peak, used as a + quality measure for peak shape. +""" +struct PeakPicking <: AbstractPreprocessingStep + method::Union{Symbol, Nothing} # :profile, :wavelet, :centroid + snr_threshold::Union{Float64, Nothing} + half_window::Union{Int, Nothing} + min_peak_prominence::Union{Float64, Nothing} + merge_peaks_tolerance::Union{Float64, Nothing} + min_peak_width_ppm::Union{Float64, Nothing} + max_peak_width_ppm::Union{Float64, Nothing} + min_peak_shape_r2::Union{Float64, Nothing} + + function PeakPicking(; method=nothing, snr_threshold=nothing, half_window=nothing, min_peak_prominence=nothing, merge_peaks_tolerance=nothing, min_peak_width_ppm=nothing, max_peak_width_ppm=nothing, min_peak_shape_r2=nothing) + new(method, snr_threshold, half_window, min_peak_prominence, merge_peaks_tolerance, min_peak_width_ppm, max_peak_width_ppm, min_peak_shape_r2) + end +end + +""" + PeakAlignment(; method=:lowess, ...) + +A preprocessing step for peak alignment. This corrects for m/z shifts between spectra, +ensuring that the same analyte peak appears at the same m/z across all samples. + +# Arguments +- `method::Symbol`: The alignment algorithm. Options: `:lowess`, `:linear`, `:ransac`. +- `span::Union{Float64, Nothing}`: The span parameter for LOWESS regression, controlling smoothness. +- `tolerance::Union{Float64, Nothing}`: The tolerance for matching peaks between the target + and reference spectrum. +- `tolerance_unit::Union{Symbol, Nothing}`: The unit for `tolerance`, either `:mz` (absolute) + or `:ppm` (relative). +- `max_shift_ppm::Union{Float64, Nothing}`: The maximum allowed m/z shift in ppm to prevent + spurious peak matches. +- `min_matched_peaks::Union{Int, Nothing}`: The minimum number of matching peaks required + to perform the alignment. +""" +struct PeakAlignment <: AbstractPreprocessingStep + method::Symbol + span::Union{Float64, Nothing} + tolerance::Union{Float64, Nothing} + tolerance_unit::Union{Symbol, Nothing} + max_shift_ppm::Union{Float64, Nothing} + min_matched_peaks::Union{Int, Nothing} + + function PeakAlignment(; method=:lowess, span=nothing, tolerance=nothing, tolerance_unit=nothing, max_shift_ppm=nothing, min_matched_peaks=nothing) + new(method, span, tolerance, tolerance_unit, max_shift_ppm, min_matched_peaks) + end +end + +""" + PeakSelection(; frequency_threshold=nothing, ...) + +A preprocessing step for peak selection (filtering). After peak detection, this step +filters the detected peaks based on various quality criteria to remove noise and +irrelevant signals. + +# Arguments +- `frequency_threshold::Union{Float64, Nothing}`: The minimum fraction of spectra in which a + peak must be present to be kept. +- `min_snr::Union{Float64, Nothing}`: Minimum Signal-to-Noise Ratio. +- `min_fwhm_ppm, max_fwhm_ppm`: Minimum and maximum Full Width at Half Maximum in ppm. +- `min_shape_r2::Union{Float64, Nothing}`: Minimum R-squared value from a Gaussian fit, + filtering for good peak shape. +- `correlation_threshold::Union{Float64, Nothing}`: Minimum correlation with neighboring + peaks (not yet implemented). +""" +struct PeakSelection <: AbstractPreprocessingStep + frequency_threshold::Union{Float64, Nothing} + min_snr::Union{Float64, Nothing} + min_fwhm_ppm::Union{Float64, Nothing} + max_fwhm_ppm::Union{Float64, Nothing} + min_shape_r2::Union{Float64, Nothing} + correlation_threshold::Union{Float64, Nothing} + + function PeakSelection(; frequency_threshold=nothing, min_snr=nothing, min_fwhm_ppm=nothing, max_fwhm_ppm=nothing, min_shape_r2=nothing, correlation_threshold=nothing) + new(frequency_threshold, min_snr, min_fwhm_ppm, max_fwhm_ppm, min_shape_r2, correlation_threshold) + end +end + +""" + PeakBinning(; method=:adaptive, ...) + +A preprocessing step for peak binning. This step groups peaks from all spectra into +common m/z bins to generate a feature matrix. + +# Arguments +- `method::Symbol`: The binning strategy. + - `:adaptive`: Creates bins based on the density of detected peaks. + - `:uniform`: Creates a fixed number of equally spaced bins over the m/z range. +- `tolerance, tolerance_unit`: Tolerance for grouping peaks into a bin in `:adaptive` mode. +- `frequency_threshold`: The minimum fraction of spectra a bin must contain a peak in to be kept. +- `min_peak_per_bin`: The minimum number of individual peaks required to form a bin in `:adaptive` mode. +- `max_bin_width_ppm`: Maximum width of a bin in ppm for `:adaptive` mode. +- `intensity_weighted_centers`: If `true`, calculates bin centers as an intensity-weighted + average of the peaks within it. +- `num_uniform_bins`: The number of bins to create for the `:uniform` method. +""" +struct PeakBinning <: AbstractPreprocessingStep + method::Symbol + tolerance::Union{Float64, Nothing} + tolerance_unit::Union{Symbol, Nothing} + frequency_threshold::Union{Float64, Nothing} + min_peak_per_bin::Union{Int, Nothing} + max_bin_width_ppm::Union{Float64, Nothing} + intensity_weighted_centers::Bool + num_uniform_bins::Union{Int, Nothing} + + function PeakBinning(; method=:adaptive, tolerance=nothing, tolerance_unit=nothing, frequency_threshold=nothing, min_peak_per_bin=nothing, max_bin_width_ppm=nothing, intensity_weighted_centers=true, num_uniform_bins=nothing) + new(method, tolerance, tolerance_unit, frequency_threshold, min_peak_per_bin, max_bin_width_ppm, intensity_weighted_centers, num_uniform_bins) + end +end + +# ============================================================================= +# 0) Quality Control (QC) +# ============================================================================= + +""" + qc_is_empty(mz, intensity) -> Bool + +Returns `true` if the spectrum is empty or contains no finite intensity data. +""" +qc_is_empty(mz::AbstractVector, intensity::AbstractVector)::Bool = + isempty(mz) || isempty(intensity) || all(!isfinite, intensity) + +""" + qc_is_regular(mz) -> Bool + +Checks that the m/z axis is monotonically non-decreasing. +""" +function qc_is_regular(mz::AbstractVector) + n = length(mz) + n < 2 && return true + @inbounds for i in 2:n + if mz[i] < mz[i-1] + return false + end + end + return true +end + +""" + validate_spectrum(mz, intensity) -> Bool + +Performs comprehensive validation on a mass spectrum (m/z and intensity arrays). +Returns `true` if the spectrum is valid, `false` otherwise. + +Checks include: +- Both `mz` and `intensity` are non-empty. +- `mz` and `intensity` have the same length. +- All `m/z` values are finite and non-negative. +- All `intensity` values are finite and non-negative. +- `m/z` values are monotonically non-decreasing. +""" +function validate_spectrum(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real})::Bool + # 1. Check for empty vectors + if isempty(mz) || isempty(intensity) + @warn "Spectrum validation failed: m/z or intensity vector is empty." + return false + end + + # 2. Check for length mismatch + if length(mz) != length(intensity) + @warn "Spectrum validation failed: m/z and intensity vectors have different lengths ($(length(mz)) vs $(length(intensity)))" + return false + end + + # 3. Check for NaN/Inf in mz and non-negativity + if any(!isfinite, mz) || any(<(0), mz) + @warn "Spectrum validation failed: m/z vector contains NaN, Inf, or negative values." + return false + end + + # 4. Check for NaN/Inf in intensity and non-negativity + if any(!isfinite, intensity) || any(<(0), intensity) + #@warn "Spectrum validation failed: intensity vector contains NaN, Inf, or negative values." + return false + end + + # 5. Check for strictly increasing m/z values (and thus no duplicates) + if !qc_is_regular(mz) + #@warn "Spectrum validation failed: m/z vector is not strictly increasing (contains duplicates or decreasing values)." + return false + end + + return true +end + +# ============================================================================= +# 1) Intensity Transformation & Smoothing +# ============================================================================= + +""" + transform_intensity_core(intensity; method=:sqrt) -> Vector + +Applies a variance-stabilizing transformation to the intensity vector. This can +help to make the variance of the signal more constant across the intensity range, +which is often an assumption of downstream statistical methods. + +# Arguments +- `intensity::AbstractVector{<:Real}`: The input intensity values. +- `method::Symbol`: The transformation to apply. Options are: + - `:sqrt`: Square root transformation. + - `:log`: Natural log transformation. + - `:log2`: Base-2 log transformation. + - `:log10`: Base-10 log transformation. + - `:log1p`: Natural log of `1 + x`, useful for data with zeros. +""" +function transform_intensity_core(intensity::AbstractVector{<:Real}; method::Symbol=:sqrt) + if method === :sqrt + return sqrt.(max.(zero(eltype(intensity)), intensity)) + elseif method === :log1p + return log1p.(max.(zero(eltype(intensity)), intensity)) + elseif method === :log + return log.(max.(eps(eltype(intensity)), intensity)) + elseif method === :log2 + return log2.(max.(eps(eltype(intensity)), intensity)) + elseif method === :log10 + return log10.(max.(eps(eltype(intensity)), intensity)) + else + return collect(float.(intensity)) + end +end + +""" + smooth_spectrum_core(y::AbstractVector{<:Real}; method::Symbol=:savitzky_golay, window::Int=9, order::Int=2) -> Vector + +Applies a smoothing filter to the intensity data. + +# Arguments +- `y`: The intensity data. +- `method`: The smoothing method (:savitzky_golay or :moving_average). +- `window`: The window size for the filter. +- `order`: The polynomial order for Savitzky-Golay +""" +function smooth_spectrum_core(y::AbstractVector{<:Real}; method::Symbol=:savitzky_golay, window::Int=9, order::Int=2) + if window < 3 + throw(ArgumentError("Window size must be at least 3")) + end + if order >= window + throw(ArgumentError("Polynomial order must be less than window size")) + end + if order < 0 + throw(ArgumentError("Polynomial order cannot be negative")) + end + if method === :savitzky_golay + win = isodd(window) ? window : window + 1 + if length(y) < win + return y # Cannot smooth if data is smaller than window + end + res = SavitzkyGolay.savitzky_golay(collect(float.(y)), win, order) + return res.y + elseif method === :moving_average + return moving_average_smooth(y, window) + else + @warn "Unsupported smoothing method: $method. Returning original intensity." + return collect(float.(y)) + end +end + +""" + moving_average_smooth(y::AbstractVector{<:Real}, window::Int) -> Vector + +Applies a simple moving average filter to the intensity data. +""" +function moving_average_smooth(y::AbstractVector{<:Real}, window::Int) + n = length(y) + if n < window + return collect(float.(y)) # Cannot smooth if data is smaller than window + end + + smoothed_y = zeros(Float64, n) + half_window = div(window, 2) + + for i in 1:n + start_idx = max(1, i - half_window) + end_idx = min(n, i + half_window) + smoothed_y[i] = mean(@view y[start_idx:end_idx]) + end + return smoothed_y +end + +# ============================================================================= +# 2) Baseline Correction +# ============================================================================= + +""" + _snip_baseline_impl(y, iterations=100) -> Vector + +Estimates the baseline of a spectrum using the SNIP algorithm (internal implementation). +""" +function _snip_baseline_impl(y::AbstractVector{<:Real}; iterations::Int=100) + n = length(y) + + # Initialize the baseline estimate array once + b1 = collect(float.(y)) + + for k in 1:iterations + prev_val = b1[1] + b1[1] = min(b1[1], b1[2]) + + @inbounds for i in 2:n-1 + curr_val = b1[i] + b1[i] = min(curr_val, 0.5 * (prev_val + b1[i+1])) + prev_val = curr_val + end + b1[n] = min(b1[n], prev_val) + end + + # Return the final baseline estimate + return b1 +end + +""" + convex_hull_baseline(y) -> Vector + +Estimates the baseline of a spectrum using the convex hull algorithm. This method +finds the lower convex hull of the spectrum, which is then used as the baseline. +It is generally faster than SNIP but can be less flexible. +""" +function convex_hull_baseline(y::AbstractVector{<:Real}) + n = length(y) + if n < 3 + return zeros(Float64, n) + end + + # Find upper convex hull points + hull_indices = Int[1] + for i in 2:n + while length(hull_indices) >= 2 && + (y[hull_indices[end]] - y[hull_indices[end-1]]) * (i - hull_indices[end]) <= + (y[i] - y[hull_indices[end]]) * (hull_indices[end] - hull_indices[end-1]) + pop!(hull_indices) + end + push!(hull_indices, i) + end + + # Interpolate between hull points + baseline = zeros(Float64, n) + for i in 1:(length(hull_indices)-1) + idx1 = hull_indices[i] + idx2 = hull_indices[i+1] + + # Linear interpolation + for j in idx1:idx2 + baseline[j] = y[idx1] + (y[idx2] - y[idx1]) * (j - idx1) / (idx2 - idx1) + end + end + return baseline +end + +""" + median_baseline(y; window=20) -> Vector + +Estimates the baseline of a spectrum using a moving median filter. +""" +function median_baseline(y::AbstractVector{<:Real}; window::Int=20) + n = length(y) + if n < window + return zeros(Float64, n) + end + + baseline = zeros(Float64, n) + half_window = div(window, 2) + + for i in 1:n + start_idx = max(1, i - half_window) + end_idx = min(n, i + half_window) + baseline[i] = median(@view y[start_idx:end_idx]) + end + return baseline +end + +""" + apply_baseline_correction_core(y::AbstractVector{<:Real}; method::Symbol=:snip, iterations::Int=100, window::Int=20) -> Vector + +Applies a baseline correction algorithm to the intensity data. + +# Arguments +- `y`: The intensity data. +- `method`: The baseline correction method (:snip, :convex_hull, or :median). +- `iterations`: Iterations for SNIP method. +- `window`: Window size for median method. +""" +function apply_baseline_correction_core(y::AbstractVector{<:Real}; method::Symbol=:snip, iterations::Int=100, window::Int=20) + if method === :snip + return _snip_baseline_impl(y, iterations=iterations) + elseif method === :convex_hull + return convex_hull_baseline(y) + elseif method === :median + return median_baseline(y, window=window) + else + @warn "Unsupported baseline correction method: $method. Returning zero baseline." + return zeros(Float64, length(y)) + end +end + +# ============================================================================= +# 3) Intensity Normalization +# ============================================================================= + +""" + tic_normalize(y) -> Vector + +Normalizes spectrum intensities to the Total Ion Current (TIC). Each intensity value +is divided by the sum of all intensities in the spectrum. This method assumes that the +total number of ions produced is similar for all samples. +""" +function tic_normalize(y::AbstractVector{<:Real}) + s = sum(y) + return s <= 0 ? collect(float.(y)) : collect(float.(y)) ./ s +end + +""" + pqn_normalize(M) -> Matrix + +Performs Probabilistic Quotient Normalization (PQN) on a matrix of spectra. +This is a more robust normalization method that is less sensitive to a small +number of highly abundant, variable peaks compared to TIC. + +# Steps: +1. A reference spectrum is calculated (typically the median spectrum across all samples). +2. For each spectrum, the quotients of its intensities and the reference spectrum's + intensities are calculated. +3. The median of these quotients is found for each spectrum. +4. Each spectrum is divided by its median quotient. + +# Arguments +- `M::AbstractMatrix{<:Real}`: A matrix where columns are spectra and rows are m/z bins. +""" +function pqn_normalize(M::AbstractMatrix{<:Real}) + M_float = collect(float.(M)) + ref = mapslices(median, M_float; dims=2)[:,1] + Q = similar(M_float) + @inbounds for j in axes(M_float, 2) + Q[:, j] = M_float[:, j] ./ (ref .+ eps(eltype(M_float))) + end + s = [median(@view Q[:, j]) for j in axes(Q, 2)] + @inbounds for j in axes(M_float, 2) + M_float[:, j] ./= (s[j] + eps(eltype(M_float))) + end + return M_float +end + +""" + median_normalize(y) -> Vector + +Normalizes spectrum intensities by dividing by the median intensity. +""" +function median_normalize(y::AbstractVector{<:Real}) + m = median(y) + return m <= 0 ? collect(float.(y)) : collect(float.(y)) ./ m +end + +""" + rms_normalize(y) -> Vector + +Normalizes spectrum intensities to the Root Mean Square (RMS). +""" +function rms_normalize(y::AbstractVector{<:Real}) + s = sqrt(sum(abs2, y) / length(y)) + return s <= 0 ? collect(float.(y)) : collect(float.(y)) ./ s +end + +""" + apply_normalization_core(y::AbstractVector{<:Real}; method::Symbol=:tic) -> Vector + +Applies a per-spectrum normalization algorithm to the intensity data. + +# Arguments +- `y`: The intensity data. +- `method`: The normalization method (:tic, :median, :rms, or :none). +""" +function apply_normalization_core(y::AbstractVector{<:Real}; method::Symbol=:tic)::Vector + if method === :tic + return tic_normalize(y) + elseif method === :median + return median_normalize(y) + elseif method === :rms + return rms_normalize(y) + elseif method === :none + return collect(float.(y)) + else + @warn "Unsupported normalization method: $method. Returning original intensity." + return collect(float.(y)) + end +end + +# ============================================================================= +# 4) Peak Detection +# ============================================================================= + +""" + detect_peaks_profile_core(mz, y; ...) -> Vector{NamedTuple} + +Enhanced peak detection for profile-mode spectra with advanced filtering and quality metrics. + +Returns a vector of NamedTuples, each representing a detected peak with: +- `mz`: m/z value of the peak +- `intensity`: Intensity of the peak +- `fwhm`: Full Width at Half Maximum (Δm) +- `shape_r2`: Pseudo R^2 for peak shape (simplified) +- `snr`: Signal-to-Noise Ratio +- `prominence`: Peak prominence +""" +function detect_peaks_profile_core(mz::AbstractVector{<:Real}, y::AbstractVector{<:Real}; + half_window::Int=10, + snr_threshold::Float64=2.0, + min_peak_prominence::Float64=0.1, + merge_peaks_tolerance::Float64=0.002, + # New parameters for quality filtering (used for calculation, not filtering here) + min_peak_width_ppm::Float64=0.0, # Not used for filtering in this function + max_peak_width_ppm::Float64=Inf, # Not used for filtering in this function + min_peak_shape_r2::Float64=0.0 # Not used for filtering in this function + ) + n = length(y) + n < 3 && return NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[] + + # Fast, non-allocating noise estimation + mean_y = sum(y) / n + noise_level = (sum(abs.(y .- mean_y)) / n) * 1.5 + eps(Float64) + + ys = smooth_spectrum_core(y; method=:savitzky_golay, window=max(5, 2*half_window+1), order=2) + + candidate_peak_indices = Int[] + sizehint!(candidate_peak_indices, div(n, 10)) # Pre-allocate memory capacity + + @inbounds for i in 2:n-1 + left = max(1, i - half_window) + right = min(n, i + half_window) + + # Avoid @view allocation in tight loop by manually computing minimums and maximums + min_left = ys[left] + for j in left:i; min_left = min(min_left, ys[j]); end + + min_right = ys[i] + for j in i:right; min_right = min(min_right, ys[j]); end + + prominence = ys[i] - max(min_left, min_right) + + max_local = ys[left] + for j in left:right; max_local = max(max_local, ys[j]); end + + if ys[i] >= max_local && + (ys[i] > snr_threshold * noise_level) && + (prominence > min_peak_prominence * ys[i]) + push!(candidate_peak_indices, i) + end + end + + # Merge close peaks + if !isempty(candidate_peak_indices) && merge_peaks_tolerance > 0 + merged_indices = [candidate_peak_indices[1]] + for i in 2:length(candidate_peak_indices) + if (mz[candidate_peak_indices[i]] - mz[last(merged_indices)]) > merge_peaks_tolerance + push!(merged_indices, candidate_peak_indices[i]) + elseif y[candidate_peak_indices[i]] > y[last(merged_indices)] + merged_indices[end] = candidate_peak_indices[i] # Replace with more intense peak + end + end + candidate_peak_indices = merged_indices + end + + detected_peaks = NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[] + for p_idx in candidate_peak_indices + peak_mz = float(mz[p_idx]) + peak_int = float(y[p_idx]) + + fwhm_delta_m = calculate_robust_fwhm(mz, y, p_idx) + fwhm_ppm = if isnan(fwhm_delta_m) || fwhm_delta_m <= 0 + 0.0 + else + 1e6 * fwhm_delta_m / peak_mz + end + shape_r2 = _fit_gaussian_and_r2(mz, y, p_idx, half_window) + + peak_snr = peak_int / noise_level # Recalculate SNR based on final peak_int + + left = max(1, p_idx - half_window) + right = min(n, p_idx + half_window) + + min_left = ys[left] + for j in left:p_idx; min_left = min(min_left, ys[j]); end + + min_right = ys[p_idx] + for j in p_idx:right; min_right = min(min_right, ys[j]); end + + prominence = ys[p_idx] - max(min_left, min_right) + + push!(detected_peaks, (mz=peak_mz, intensity=peak_int, fwhm=fwhm_ppm, shape_r2=shape_r2, snr=peak_snr, prominence=prominence)) + end + + return detected_peaks +end + +""" + detect_peaks_wavelet_core(mz, intensity; ...) -> Vector{NamedTuple} + +Detects peaks using Continuous Wavelet Transform (CWT). CWT is effective at +identifying peaks at different scales (widths), making it robust for complex spectra. + +# Arguments +- `mz::AbstractVector`: The m/z values of the spectrum. +- `intensity::AbstractVector`: The intensity values of the spectrum. +- `scales`: A range of scales to use for the CWT. Corresponds to the widths of + the features to be detected. +- `snr_threshold`: The minimum Signal-to-Noise Ratio for a CWT-detected local maximum + in the original spectrum to be considered a peak. +- `half_window`: Used for calculating peak quality metrics like FWHM and shape R^2. + +# Returns +A vector of `NamedTuple`s, each representing a detected peak with: +- `mz`: m/z value of the peak. +- `intensity`: Intensity of the peak from the original spectrum. +- `fwhm`: Full Width at Half Maximum (in ppm). +- `shape_r2`: Goodness-of-fit to a Gaussian shape. +- `snr`: Signal-to-Noise Ratio. +- `prominence`: Peak prominence (estimated as peak intensity for this method). +""" +function detect_peaks_wavelet_core(mz::AbstractVector, intensity::AbstractVector; scales=1:10, snr_threshold=3.0, half_window=10)::Vector{NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}} + n = length(intensity) + n < 10 && return NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[] + + # Compute CWT + cwt_res = ContinuousWavelets.cwt(intensity, ContinuousWavelets.morl) # Morlet is good for peaks + + noise_level = mad(intensity, normalize=true) + eps(Float64) + + candidate_indices = Set{Int}() # Use a Set to store unique peak indices + + # Find local maxima in the CWT coefficients (magnitude) + # This assumes `localmaxima` is available (e.g., from ImageFiltering, often a dependency of ContinuousWavelets). + abs_cwt_res = abs.(cwt_res) + # Iterate over all (m/z index, scale index) pairs that are local maxima in the CWT matrix + for (m_idx, scale_idx) in Tuple.(localmaxima(abs_cwt_res)) + # Ensure m_idx is not at the very edges of the intensity array to avoid index out of bounds + if m_idx > 1 && m_idx < n + # Check if this CWT maximum corresponds to a local maximum in the original intensity + # AND if the original intensity is above the SNR threshold + if intensity[m_idx] > intensity[m_idx-1] && intensity[m_idx] > intensity[m_idx+1] && intensity[m_idx] > snr_threshold * noise_level + push!(candidate_indices, m_idx) + end + end + end + peak_indices = collect(candidate_indices) + sort!(peak_indices) # Ensure order + + detected_peaks = NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[] + for p_idx in peak_indices + peak_mz = float(mz[p_idx]) + peak_int = float(intensity[p_idx]) + peak_snr = peak_int / noise_level + + fwhm_delta_m = calculate_robust_fwhm(mz, intensity, p_idx) + fwhm_ppm = if isnan(fwhm_delta_m) || fwhm_delta_m <= 0 + 0.0 + else + 1e6 * fwhm_delta_m / peak_mz + end + shape_r2 = _fit_gaussian_and_r2(mz, intensity, p_idx, half_window) + + push!(detected_peaks, (mz=peak_mz, intensity=peak_int, fwhm=fwhm_ppm, shape_r2=shape_r2, snr=peak_snr, prominence=peak_int)) + end + + return detected_peaks +end + +""" + detect_peaks_centroid_core(mz, y; ...) -> Vector{NamedTuple} + +Filters peaks in centroid-mode data based on intensity threshold. + +Returns a vector of NamedTuples, each representing a detected peak with: +- `mz`: m/z value of the peak +- `intensity`: Intensity of the peak +""" +function detect_peaks_centroid_core(mz::AbstractVector{<:Real}, y::AbstractVector{<:Real}; snr_threshold::Float64=0.0) + noise_level = mad(y, normalize=true) + eps(Float64) + detected_peaks = NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[] + + for i in eachindex(mz) + snr = noise_level > 0 ? y[i] / noise_level : y[i] > 0 ? Inf : 0.0 + if snr >= snr_threshold + # For centroid data, FWHM and shape are not applicable. Return placeholders. + push!(detected_peaks, (mz=float(mz[i]), intensity=float(y[i]), fwhm=0.0, shape_r2=1.0, snr=snr, prominence=y[i])) + end + end + return detected_peaks +end + +# ============================================================================= +# 5) Peak Alignment & Calibration +# ============================================================================= + +""" + align_peaks_lowess_core(ref_mz, tgt_mz; ...) + +Enhanced peak alignment with PPM tolerance and other constraints. +""" +function align_peaks_lowess_core(ref_mz::Vector{<:Real}, tgt_mz::Vector{<:Real}; + method::Symbol=:linear, # :linear, :lowess, or :ransac + span::Float64=0.75, # Span for LOWESS + tolerance::Float64=0.002, + tolerance_unit::Symbol=:mz, + max_shift_ppm::Float64=50.0, + min_matched_peaks::Int=5) + pairs = Tuple{Float64,Float64}[] + i = 1; j = 1 + while i <= length(tgt_mz) && j <= length(ref_mz) + # Dynamic tolerance for PPM + tol = (tolerance_unit == :ppm) ? (ref_mz[j] * tolerance / 1e6) : tolerance + dt = tgt_mz[i] - ref_mz[j] + + if abs(dt) <= tol + # Max shift check to avoid spurious matches + if abs(dt) * 1e6 / ref_mz[j] <= max_shift_ppm + push!(pairs, (float(tgt_mz[i]), float(ref_mz[j]))) + end + i += 1; j += 1 + elseif dt < 0 + i += 1 + else + j += 1 + end + end + + if length(pairs) < min_matched_peaks + #@warn "Too few matching peaks ($(length(pairs)) < $min_matched_peaks). Returning identity function." + return x -> float.(x) + end + + t = [p[1] for p in pairs] # Target m/z (x-axis) + r = [p[2] for p in pairs] # Reference m/z (y-axis) + + if method == :linear + itp = linear_interpolation(t, r, extrapolation_bc=Line()) + return itp + elseif method == :lowess + try + model = loess(t, r; span=span) + # Predict over the original target m/z values (t) + predicted_r = Loess.predict(model, t) + # Create a linear interpolation from original t and Loess-predicted r, + # allowing linear extrapolation. + itp = linear_interpolation(t, predicted_r, extrapolation_bc=Line()) + return itp + catch e + @warn "LOWESS fitting failed: $e. Falling back to linear interpolation." + itp = linear_interpolation(t, r, extrapolation_bc=Line()) + return itp + end + elseif method == :ransac + # RANSAC implementation for linear model + num_iterations = 100 + best_model_inliers_count = -1 + best_inliers_t = Float64[] + best_inliers_r = Float64[] + + n_pairs = length(pairs) + if n_pairs < 2 # Need at least 2 points to fit a line + @warn "Not enough matched peaks ($n_pairs) for RANSAC. Falling back to linear interpolation." + itp = linear_interpolation(t, r, extrapolation_bc=Line()) + return itp + end + + for iter in 1:num_iterations + # 1. Randomly select 2 points + sample_indices = StatsBase.sample(1:n_pairs, 2, replace=false) + p1_x, p1_y = pairs[sample_indices[1]] + p2_x, p2_y = pairs[sample_indices[2]] + + # Avoid vertical line for simplicity in this basic implementation + if isapprox(p1_x, p2_x, atol=1e-9) + continue + end + + # 2. Fit a line y = mx + b + m = (p2_y - p1_y) / (p2_x - p1_x) + b = p1_y - m * p1_x + + current_inliers_t = Float64[] + current_inliers_r = Float64[] + current_inliers_count = 0 + + # 3. Find inliers + for (px, py) in pairs + predicted_y = m * px + b + residual = abs(py - predicted_y) + + # Determine inlier threshold based on tolerance_unit + current_inlier_threshold = (tolerance_unit == :ppm) ? (px * tolerance / 1e6) : tolerance + + if residual <= current_inlier_threshold + current_inliers_count += 1 + push!(current_inliers_t, px) + push!(current_inliers_r, py) + end + end + + # 4. Evaluate model + if current_inliers_count > best_model_inliers_count + best_model_inliers_count = current_inliers_count + best_inliers_t = current_inliers_t + best_inliers_r = current_inliers_r + end + end + + if best_model_inliers_count >= 2 # At least 2 inliers to form a line + return linear_interpolation(best_inliers_t, best_inliers_r, extrapolation_bc=Line()) + else + @warn "RANSAC failed to find a robust model (found $(best_model_inliers_count) inliers). Falling back to linear interpolation." + itp = linear_interpolation(t, r, extrapolation_bc=Line()) + return itp + end + else + @warn "Unsupported alignment method: $method. Falling back to linear interpolation." + itp = linear_interpolation(t, r, extrapolation_bc=Line()) + return itp + end +end + +""" + find_calibration_peaks_core(mz, intensity, reference_masses; ...) + +Finds peaks that match a list of reference masses. +""" +function find_calibration_peaks_core(mz::AbstractVector, intensity::AbstractVector, reference_masses::AbstractVector; ppm_tolerance=20.0) + matched_peaks = Dict{Float64, Float64}() + + # detect_peaks_profile_core returns Vector{NamedTuple}, so we need to extract mz values + detected_peaks_list = detect_peaks_profile_core(mz, intensity) + + # Extract only the m/z values into a new vector for easier processing + detected_mz_values = [p.mz for p in detected_peaks_list] + + for ref_mass in reference_masses + tol = ref_mass * ppm_tolerance / 1e6 + # Find candidates within the detected m/z values + candidates = findall(m -> abs(m - ref_mass) <= tol, detected_mz_values) + if !isempty(candidates) + # Find the closest detected peak to the reference mass among candidates + closest_peak_idx = argmin(abs.(detected_mz_values[candidates] .- ref_mass)) + matched_peaks[ref_mass] = detected_mz_values[candidates[closest_peak_idx]] + end + end + return matched_peaks +end + +""" + calibrate_spectra_core(spectra, internal_standards; ...) + +Calibrates spectra using internal standards. +""" +function calibrate_spectra_core(spectra::Vector, internal_standards::Vector; ppm_tolerance=20.0) + calibrated_spectra = similar(spectra) + for (i, spec) in enumerate(spectra) + mz, intensity = spec[1], spec[2] + + matched_peaks = find_calibration_peaks_core(mz, intensity, internal_standards; ppm_tolerance=ppm_tolerance) + if length(matched_peaks) < 2 + @warn "Spectrum $i: Not enough calibration peaks found. Skipping." + calibrated_spectra[i] = spec + continue + end + measured = sort(collect(values(matched_peaks))) + theoretical = sort(collect(keys(matched_peaks))) + itp = linear_interpolation(measured, theoretical, extrapolation_bc=Line()) + + new_mz = itp(mz) + + if length(spec) == 3 + calibrated_spectra[i] = (new_mz, intensity, spec[3]) + else + calibrated_spectra[i] = (new_mz, intensity) + end + end + return calibrated_spectra +end + +# ============================================================================= +# 6) Peak Binning & Feature Matrix Generation +# ============================================================================= + +""" + bin_peaks_core(all_pk_mz::Vector{Vector{Float64}}, + all_pk_int::Vector{Vector{Float64}}, + params::PeakBinning) -> Tuple{FeatureMatrix, Vector{Tuple{Float64,Float64}}} + +Enhanced peak binning with adaptive and PPM-based parameters, or uniform binning. + +# Arguments +- `all_pk_mz`: A vector of m/z vectors for all spectra. +- `all_pk_int`: A vector of intensity vectors for all spectra. +- `params`: A `PeakBinning` struct. + +# Returns +- `Tuple{FeatureMatrix, Vector{Tuple{Float64,Float64}}}`: A tuple containing the generated FeatureMatrix and the bin definitions. + +# Thread Safety +The use of `Threads.@threads` in the `:adaptive` and `:uniform` methods is safe. +- In the `:adaptive` method, the loop is over the bins (`j` index). Each thread writes only to its assigned column `X[:, j]`, so there are no write conflicts between threads. +- In the `:uniform` method, the loop is over the spectra (`s_idx`). Writes to `X[s_idx, bin_idx]` could theoretically conflict if different peaks from the same spectrum (`s_idx`) are processed by different threads. However, the loop is over `s_idx`, meaning each thread handles a distinct spectrum, making writes to `X[s_idx, :]` exclusive to that thread and thus safe. +""" +function bin_peaks_core(spectra::Vector{MutableSpectrum}, + params::PeakBinning) + ns = length(spectra) # Number of spectra + ns == 0 && return FeatureMatrix(zeros(0,0), Tuple{Float64,Float64}[], Int[]), Tuple{Float64,Float64}[] + + if params.method == :uniform + println("Performing uniform binning with $(params.num_uniform_bins) bins.") + # Determine global m/z range from all peaks + min_mz = Inf + max_mz = -Inf + for s in spectra + if !isempty(s.peaks) + # Extract m/z values from peaks NamedTuple + pk_mz_vec = [p.mz for p in s.peaks] + min_mz = min(min_mz, minimum(pk_mz_vec)) + max_mz = max(max_mz, maximum(pk_mz_vec)) + end + end + + if !isfinite(min_mz) || !isfinite(max_mz) || min_mz == max_mz + @warn "Could not determine valid m/z range for uniform binning. Returning empty FeatureMatrix." + return FeatureMatrix(zeros(0,0), Tuple{Float64,Float64}[], Int[]), Tuple{Float64,Float64}[] + end + + # Create uniform bins + mz_edges = collect(range(min_mz, stop=max_mz, length=params.num_uniform_bins + 1)) + bin_definitions = Vector{Tuple{Float64,Float64}}(undef, params.num_uniform_bins) + for i in 1:params.num_uniform_bins + bin_definitions[i] = (mz_edges[i], mz_edges[i+1]) + end + + X = zeros(Float64, ns, params.num_uniform_bins) + + Threads.@threads for s_idx in 1:ns + s = spectra[s_idx] # Get the current MutableSpectrum + for p in s.peaks # Iterate over peaks directly + m = p.mz + i = p.intensity + # Find which bin this peak belongs to + bin_idx = searchsortedlast(mz_edges, m) + if bin_idx > 0 && bin_idx <= params.num_uniform_bins + X[s_idx, bin_idx] = max(X[s_idx, bin_idx], i) # Take max intensity in bin + end + end + end + + if params.frequency_threshold !== nothing && params.frequency_threshold > 0 + present_count = vec(sum(X .> 0, dims=1)) + min_count = ceil(Int, params.frequency_threshold * ns) + keep_mask = findall(present_count .>= min_count) + X = X[:, keep_mask] + bin_definitions = bin_definitions[keep_mask] + end + + return FeatureMatrix(X, bin_definitions, collect(1:ns)), bin_definitions + + elseif params.method == :adaptive + println("Performing adaptive binning with tolerance $(params.tolerance) $(params.tolerance_unit).") + # Collect all peaks with their intensities and original spectrum ID directly from MutableSpectrum objects + all_peaks = Vector{Tuple{Float64, Float64, Int}}() + sizehint!(all_peaks, sum(length(s.peaks) for s in spectra)) # Pre-allocate memory + + for s in spectra + for p in s.peaks + push!(all_peaks, (p.mz, p.intensity, s.id)) + end + end + sort!(all_peaks, by=p->p[1]) + + isempty(all_peaks) && return FeatureMatrix(zeros(0,0), Tuple{Float64,Float64}[], Int[]), Tuple{Float64,Float64}[] + + # Create bins using indices into all_peaks to avoid copying large vectors + bins_indices = Vector{UnitRange{Int}}() # Stores UnitRange (start_idx:end_idx) for each bin + if isempty(all_peaks) + # Handle empty all_peaks case if it was not caught earlier + return FeatureMatrix(zeros(0,0), Tuple{Float64,Float64}[], Int[]), Tuple{Float64,Float64}[] + end + + current_bin_start_idx = 1 + for i in 2:length(all_peaks) + p_prev = all_peaks[i-1] + p_current = all_peaks[i] + + # Approximate bin center for tolerance calculation. Using current_bin_start_idx or p_current.mz is sufficient. + # A more precise bin_center would require iterating over current_bin_peaks, which we are trying to avoid for memory. + # For tolerance calculation, a single mz value (e.g., p_current.mz or all_peaks[current_bin_start_idx].mz) is often sufficient + # because the m/z range within a small bin is typically very narrow. + approx_bin_mz = p_prev[1] # Use the m/z of the previous peak in the bin as a proxy for bin center + tol = (params.tolerance_unit == :ppm) ? (approx_bin_mz * params.tolerance / 1e6) : params.tolerance + + if (p_current[1] - p_prev[1]) <= tol + # Peak is within tolerance, continue current bin + else + # Peak is outside tolerance, close current bin and start new one + current_bin_end_idx = i - 1 + # Apply min_peak_per_bin filter when closing the bin + if params.min_peak_per_bin === nothing || (current_bin_end_idx - current_bin_start_idx + 1) >= params.min_peak_per_bin + push!(bins_indices, current_bin_start_idx:current_bin_end_idx) + end + current_bin_start_idx = i + end + end + # Add the last bin + current_bin_end_idx = length(all_peaks) + if params.min_peak_per_bin === nothing || (current_bin_end_idx - current_bin_start_idx + 1) >= params.min_peak_per_bin + push!(bins_indices, current_bin_start_idx:current_bin_end_idx) + end + + # Filter bins by max width + if params.max_bin_width_ppm !== nothing + filter!(range_idx -> begin + bin_peaks_view = @view all_peaks[range_idx] + min_mz_bin = first(bin_peaks_view)[1] + max_mz_bin = last(bin_peaks_view)[1] + bin_center_approx = (min_mz_bin + max_mz_bin) / 2 + (max_mz_bin - min_mz_bin) * 1e6 / bin_center_approx <= params.max_bin_width_ppm + end, bins_indices) + end + + # Create feature matrix + X = zeros(Float64, ns, length(bins_indices)) + final_bins_boundaries = Vector{Tuple{Float64,Float64}}(undef, length(bins_indices)) + + Threads.@threads for j in 1:length(bins_indices) + range_idx = bins_indices[j] + bin_peaks_view = @view all_peaks[range_idx] # Create a view into all_peaks for the current bin + + # Calculate bin center + local bin_center + if params.intensity_weighted_centers && sum(p[2] for p in bin_peaks_view) > 0 + weights = [p[2] for p in bin_peaks_view] + bin_center = sum(p[1] * p[2] for p in bin_peaks_view) / sum(weights) + else + bin_center = mean(p[1] for p in bin_peaks_view) + end + + final_bins_boundaries[j] = (first(bin_peaks_view)[1], last(bin_peaks_view)[1]) + + for p in bin_peaks_view + s_idx = p[3] + # This is thread-safe because each thread writes to a unique column j + X[s_idx, j] = max(X[s_idx, j], p[2]) + end + end + + # Filter by frequency + if params.frequency_threshold !== nothing && params.frequency_threshold > 0 + present_count = vec(sum(X .> 0, dims=1)) + min_count = ceil(Int, params.frequency_threshold * ns) + keep_mask = findall(present_count .>= min_count) + X = X[:, keep_mask] + final_bins_boundaries = final_bins_boundaries[keep_mask] + end + + return FeatureMatrix(X, final_bins_boundaries, collect(1:ns)), final_bins_boundaries + else + @warn "Unsupported binning method: $(params.method). Returning empty FeatureMatrix." + return FeatureMatrix(zeros(0,0), Tuple{Float64,Float64}[], Int[]), Tuple{Float64,Float64}[] + end +end diff --git a/src/PreprocessingPipeline.jl b/src/PreprocessingPipeline.jl new file mode 100644 index 0000000..c990156 --- /dev/null +++ b/src/PreprocessingPipeline.jl @@ -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 \ No newline at end of file diff --git a/src/ResourcePool.jl b/src/ResourcePool.jl new file mode 100644 index 0000000..aaa0ed8 --- /dev/null +++ b/src/ResourcePool.jl @@ -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 diff --git a/src/StreamingKernels.jl b/src/StreamingKernels.jl new file mode 100644 index 0000000..8f4b1a0 --- /dev/null +++ b/src/StreamingKernels.jl @@ -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 diff --git a/src/StreamingPipeline.jl b/src/StreamingPipeline.jl new file mode 100644 index 0000000..ee97ac4 --- /dev/null +++ b/src/StreamingPipeline.jl @@ -0,0 +1,402 @@ +# 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 --- + n_threads = Base.Threads.nthreads() + 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 diff --git a/src/imzML.jl b/src/imzML.jl new file mode 100644 index 0000000..a144893 --- /dev/null +++ b/src/imzML.jl @@ -0,0 +1,1613 @@ +using Images, Statistics, CairoMakie, DataFrames, Printf, ColorSchemes, StatsBase, Mmap + +""" +This file provides a library for parsing `.imzML` and `.ibd` files in pure Julia. + +Core Functions: +- `load_imzml_lazy`: The main function that orchestrates the parsing. +- Helper functions for reading XML metadata and binary spectral data. +""" + + +# ============================================================================ +# +# +# imzML Parser Implementation +# +# ============================================================================ + +""" + parse_imzml_header(stream::IO) + +Parses the header of an imzML file. + +# Arguments + +- `stream::IO`: The stream to parse. + +# Returns + +- `instrument_meta::InstrumentMetadata`: The instrument metadata. +- `param_groups::Dict{String, SpecDim}`: The parameter groups. +- `img_dims::Vector{Int32}`: The image dimensions. +""" +function parse_imzml_header(stream::IO) + # Initialize all return values and temporary variables + instrument_meta = InstrumentMetadata() + param_groups = Dict{String, SpecDim}() + img_dims = zeros(Int32, 3) + vendor_preprocessing_steps = String[] # Initialize vendor_preprocessing_steps + + # Temp vars for parsing + 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}() + + try + seekstart(stream) + + in_scan_settings = false + dim_axes_found = 0 + found_spectrum_count = false + + # This loop performs a single pass to get most metadata + while !eof(stream) + line = readline(stream) + + # State-machine like logic to enter/exit sections + if occursin("", line) + in_scan_settings = false + end + + # --- Parse Scan Settings for Image Dimensions --- + if in_scan_settings && occursin("", line) + break + end + + id_match = match(r"", line) + return join(lines, "\n") + end + end + end + + # If we reach EOF without finding for a started block, + # or if no was found at all, return empty. + if isempty(lines) + seek(stream, start_pos) # Reset stream position if no block was found + return "" + else + # Should not happen if XML is well-formed, but just in case + @warn "Reached EOF while parsing spectrum block without finding tag. Returning partial block." + return join(lines, "\n") + end +end + +""" + parse_coordinates(spectrum_block::String) + +Helper function to parse coordinates from a spectrum block. + +# Arguments + +- `spectrum_block::String`: The spectrum block to parse. + +# Returns + +- `x::Int32`: The x-coordinate. +- `y::Int32`: The y-coordinate. +""" +function parse_coordinates(spectrum_block::String) + x = Int32(0) + y = Int32(0) + + x_match = match(r"IMS:1000050[^>]*value=\"(\d+)\"", spectrum_block) + y_match = match(r"IMS:1000051[^>]*value=\"(\d+)\"", spectrum_block) + + x = x_match !== nothing ? parse(Int32, x_match.captures[1]) : x + y = y_match !== nothing ? parse(Int32, y_match.captures[1]) : y + + return x, y +end + +""" + parse_spectrum_mode(spectrum_block::String, global_mode::SpectrumMode) + +Helper function to parse spectrum mode from a spectrum block. + +# Arguments + +- `spectrum_block::String`: The spectrum block to parse. +- `global_mode::SpectrumMode`: The global mode. + +# Returns + +- `mode::SpectrumMode`: The spectrum mode. +""" +function parse_spectrum_mode(spectrum_block::String, global_mode::SpectrumMode) + if occursin("MS:1000127", spectrum_block) + return CENTROID + elseif occursin("MS:1000128", spectrum_block) + return PROFILE + else + return global_mode + end +end + +""" + parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::String, + default_mz_format::DataType, default_intensity_format::DataType, + mz_is_compressed::Bool, int_is_compressed::Bool) + +Helper function to parse binary data arrays from a spectrum block. + +# Arguments + +- `spectrum_block::String`: The spectrum block to parse. +- `spectrum_start_line::String`: The start line of the spectrum. +- `default_mz_format::DataType`: The default data type for mz arrays. +- `default_intensity_format::DataType`: The default data type for intensity arrays. +- `mz_is_compressed::Bool`: Whether mz arrays are compressed. +- `int_is_compressed::Bool`: Whether intensity arrays are compressed. + +# Returns + +- `array_data::Vector{Tuple{Bool, Int32, Int64, Int64}}`: The array data. +""" +function parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::String, + default_mz_format::DataType, default_intensity_format::DataType, + mz_is_compressed::Bool, int_is_compressed::Bool) + + array_data_type = @NamedTuple{is_mz::Bool, array_length::Int32, encoded_length::Int64, offset::Int64} + current_array_data = array_data_type[] + + for bda_match in eachmatch(r"(.*?)"sm, spectrum_block) + bda_content = bda_match.match # This will be the full block + + is_mz = occursin("MS:1000514", bda_content) || occursin("mzArray", bda_content) + + array_len_cv_match = match(r"IMS:1000103.*?value=\"(\d+)\"", bda_content) + array_length = Int32(0) + if array_len_cv_match !== nothing + array_length = parse(Int32, array_len_cv_match.captures[1]) + end + + # Fallback for defaultArrayLength from the spectrum_start_line + if array_length == 0 + default_match = match(r"defaultArrayLength=\"(\d+)\"", spectrum_start_line) + if default_match !== nothing + array_length = parse(Int32, default_match.captures[1]) + end + end + + encoded_len_cv_match = match(r"IMS:1000104.*?value=\"(\d+)\"", bda_content) + encoded_length = Int64(0) + if encoded_len_cv_match !== nothing + encoded_length = parse(Int64, encoded_len_cv_match.captures[1]) + else + encoded_len_attr_match = match(r"encodedLength=\"(\d+)\"", bda_content) + if encoded_len_attr_match !== nothing + encoded_length = parse(Int64, encoded_len_attr_match.captures[1]) + end + end + + offset_match = match(r"IMS:1000102.*?value=\"(\d+)\"", bda_content) + offset = Int64(0) + if offset_match !== nothing + offset = parse(Int64, offset_match.captures[1]) + end + + if array_length > 0 && offset > 0 + push!(current_array_data, (is_mz=is_mz, array_length=array_length, + encoded_length=encoded_length, offset=offset)) + end + end + return current_array_data +end + +""" + parse_imzml_spectrum_block(stream::IO, hIbd::Union{IO, ThreadSafeFileHandle}, param_groups::Dict{String, SpecDim}, + width::Int32, height::Int32, num_spectra::Int32, + default_mz_format::DataType, default_intensity_format::DataType, + mz_is_compressed::Bool, int_is_compressed::Bool, global_mode::SpectrumMode) + + Unified function to parse spectrum metadata + +# Arguments + +- `stream::IO`: The stream to parse. +- `hIbd::IO`: The IBD file handle. +- `param_groups::Dict{String, SpecDim}`: The parameter groups. +- `width::Int32`: The width of the image. +- `height::Int32`: The height of the image. +- `num_spectra::Int32`: The number of spectra. +- `default_mz_format::DataType`: The default data type for mz arrays. +- `default_intensity_format::DataType`: The default data type for intensity arrays. +- `mz_is_compressed::Bool`: Whether mz arrays are compressed. +- `int_is_compressed::Bool`: Whether intensity arrays are compressed. +- `global_mode::SpectrumMode`: The global mode. + +# Returns + +- `spectra_metadata::Vector{SpectrumMetadata}`: The spectrum metadata. +""" +function parse_imzml_spectrum_block(stream::IO, hIbd::IO, param_groups::Dict{String, SpecDim}, + width::Int32, height::Int32, num_spectra::Int32, + default_mz_format::DataType, default_intensity_format::DataType, + mz_is_compressed::Bool, int_is_compressed::Bool, global_mode::SpectrumMode) + + spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra) + + # Store the initial position of the stream, in case read_spectrum_block fails to find a spectrum. + # This helps reset the stream for subsequent debugging if needed, though typically it should find a spectrum. + initial_stream_pos = position(stream) + + for k in 1:num_spectra + spectrum_block_content = read_spectrum_block(stream) + if isempty(spectrum_block_content) + @warn "Expected spectrum block $k but found none or reached EOF prematurely. Stopping parsing." + # Fill remaining spectra_metadata with placeholder or error. + for j in k:num_spectra + mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, Int64(0), 0, :mz, 0.0, 0.0) + int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, Int64(0), 0, :intensity, 0.0, 0.0) + spectra_metadata[j] = SpectrumMetadata(Int32(0), Int32(0), "", :sample, global_mode, mz_asset, int_asset) + end + break + end + + x, y = parse_coordinates(spectrum_block_content) + spectrum_mode = parse_spectrum_mode(spectrum_block_content, global_mode) + + # The spectrum_start_line is needed for defaultArrayLength fallback in parse_binary_data_arrays + # We need to extract it from spectrum_block_content or pass the first line of the spectrum_block_content + # Let's assume the first line of spectrum_block_content is the spectrum_start_line for this purpose + spectrum_start_line_from_block = String(split(spectrum_block_content, '\n')[1]) + + current_array_data = parse_binary_data_arrays(spectrum_block_content, spectrum_start_line_from_block, + default_mz_format, default_intensity_format, + mz_is_compressed, int_is_compressed) + + # Separate m/z and intensity arrays + mz_data = filter(d -> d.is_mz, current_array_data) + int_data = filter(d -> !d.is_mz, current_array_data) + + if length(mz_data) != 1 || length(int_data) != 1 + println("DEBUG: Spectrum $k is empty or invalid - creating placeholder metadata") + mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, Int64(0), 0, :mz, 0.0, 0.0) + int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, Int64(0), 0, :intensity, 0.0, 0.0) + else + mz_info = mz_data[1] + int_info = int_data[1] + + if k == 1 # Only print debug for the first spectrum + println("DEBUG First spectrum parsed (unified):") + println(" Coordinates: x=$x, y=$y") + println(" Mode: $spectrum_mode") + println(" m/z array: array_length=$(mz_info.array_length), encoded_length=$(mz_info.encoded_length), offset=$(mz_info.offset)") + println(" intensity array: array_length=$(int_info.array_length), encoded_length=$(int_info.encoded_length), offset=$(int_info.offset)") + end + + mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, mz_info.offset, + mz_is_compressed ? mz_info.encoded_length : mz_info.array_length, :mz, 0.0, 0.0) + int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, int_info.offset, + int_is_compressed ? int_info.encoded_length : int_info.array_length, :intensity, 0.0, 0.0) + end + + spectra_metadata[k] = SpectrumMetadata(x, y, "", :sample, spectrum_mode, mz_asset, int_asset) + end + + return spectra_metadata +end + +""" + load_imzml_lazy(file_path::String; cache_size::Int=100) + +The main entry point for loading an imzML file. +It works by locating the .ibd file and parsing the .imzML file +Lazily loads the data and then creating a MSIData object with the +parsed information acquired by the helper functions. + +# Arguments + +- `file_path::String`: The path to the imzML file. +- `cache_size::Int`: The size of the cache. + +# Returns + +- `msi_data::MSIData`: The MSI data. +""" +function load_imzml_lazy(file_path::String; cache_size::Int=100, use_mmap::Bool=true) + println("DEBUG: Checking for .imzML file at $file_path") + if !isfile(file_path) + throw(FileFormatError("Provided path is not a file: $(file_path)")) + end + + ibd_path = replace(file_path, r"\.(imzML|mzML)"i => ".ibd") + println("DEBUG: Checking for .ibd file at $ibd_path") + if !isfile(ibd_path) + throw(FileFormatError("Corresponding .ibd file not found for: $(file_path)")) + end + + println("DEBUG: Opening file streams for .imzML and .ibd") + stream = open(file_path, "r") + + # --- Handle Pool Optimization --- + # We open multiple handles to the same .ibd file to avoid lock contention in parallel code. + num_handles = Threads.nthreads() + ibd_handles = [open(ibd_path, "r") for _ in 1:num_handles] + + # --- Mmap Optimization with RAM Safety --- + mmap_data = nothing + if use_mmap + try + file_size = filesize(ibd_path) + + @debug "Memory mapping .ibd file..." + # We use the first handle for mmapping + mmap_data = Mmap.mmap(ibd_handles[1], Vector{UInt8}, file_size) + # Use POSIX shim for sequential access optimization + posix_madvise(mmap_data, MADV_SEQUENTIAL) + @debug ".ibd file mmapped successfully." + catch e + @warn "Memory mapping failed, falling back to standard I/O: $e" + end + end + + try + @debug "Parsing imzML header..." + (instrument_meta, param_groups, imgDim) = parse_imzml_header(stream) + + width, height, num_spectra = imgDim + @debug "Image dimensions: $(width)x$(height), $num_spectra spectra." + + # ... (format extraction logic stays the same) ... + # [Simplified for brevity in replacement chunk, but keeping the logic] + mz_group = nothing + int_group = nothing + for group in values(param_groups) + if group.Axis == 1; mz_group = group; elseif group.Axis == 2; int_group = group; end + end + + default_mz_format = (mz_group !== nothing) ? mz_group.Format : Float64 + default_intensity_format = (int_group !== nothing) ? int_group.Format : Float64 + mz_is_compressed = (mz_group !== nothing) ? mz_group.Packed : false + int_is_compressed = (int_group !== nothing) ? int_group.Packed : false + global_mode = (mz_group !== nothing && mz_group.Mode != UNKNOWN) ? mz_group.Mode : UNKNOWN + + # Use the first handle for metadata parsing (sequential) + # --- Metadata Caching Strategy (Sprint 1) --- + cache_path = file_path * ".cache" + use_cache = isfile(cache_path) && (mtime(cache_path) > mtime(file_path)) + + local spectra_metadata + if use_cache + @debug "Found valid metadata cache at $cache_path. Loading..." + try + spectra_metadata = load_metadata_cache(cache_path, default_mz_format, default_intensity_format) + @debug "Metadata loaded from cache in O(1) time." + catch e + @warn "Failed to load cache: $e. Falling back to full XML parsing." + use_cache = false + end + end + + # Check for compression status once + any_comp = mz_is_compressed || int_is_compressed + + if !use_cache + @debug "Parsing spectrum block from XML (this may take time for large files)..." + spectra_metadata = parse_imzml_spectrum_block(stream, ibd_handles[1], param_groups, width, height, num_spectra, + default_mz_format, default_intensity_format, + mz_is_compressed, int_is_compressed, global_mode) + + @debug "Metadata parsing complete. Saving cache for next time..." + # We create a temporary MSIData just for save_metadata_cache + tmp_source = ImzMLSource(ibd_handles, default_mz_format, default_intensity_format, mmap_data, any_comp) + tmp_msi = MSIData(tmp_source, spectra_metadata, instrument_meta, (width, height), nothing, cache_size) + save_metadata_cache(tmp_msi, cache_path) + end + + # Build coordinate map ... + coordinate_map = zeros(Int, width, height) + for (idx, meta) in enumerate(spectra_metadata) + if 1 <= meta.x <= width && 1 <= meta.y <= height + coordinate_map[meta.x, meta.y] = idx + end + end + + source = ImzMLSource(ibd_handles, default_mz_format, default_intensity_format, mmap_data, any_comp) + @debug "Creating MSIData object." + msi_data = MSIData(source, spectra_metadata, instrument_meta, (width, height), coordinate_map, cache_size) + + # NOTE: Do NOT set analytics_ready here even though the cache provides fast metadata loading. + # The cache only stores binary offsets (SpectrumMetadataBinary). It does NOT populate + # msi_data.spectrum_stats_df (TIC, BPI, BasePeakMZ, MinMZ, MaxMZ), which requires a + # streaming pass via precompute_analytics(). Setting the flag prematurely causes + # get_mz_slice to skip that pass, leaving stats_df=nothing and all min/max bounds at 0.0, + # resulting in zero pixels populated in every image slice. + @debug "Metadata loaded from cache — analytics scan deferred until first use." + + close(stream) + return msi_data + + catch e + close(stream) + # Check if handles exist before closing + if @isdefined(ibd_handles) + for h in ibd_handles + isopen(h) && close(h) + end + end + rethrow(e) + end +end + + +# ============================================================================= +# +# Image Slice Extraction +# +# ============================================================================= + +""" + find_mass(mz_array, intensity_array, target_mass, tolerance) + +Finds the intensity of the most intense peak within a mass tolerance window. +This optimized version uses binary search for efficiency. + +# Arguments + +- `mz_array::AbstractVector{<:Real}`: The m/z array. +- `intensity_array::AbstractVector{<:Real}`: The intensity array. +- `target_mass::Real`: The target mass. +- `tolerance::Real`: The tolerance. + +# Returns +- The intensity (`Float64`) of the peak if found, otherwise `0.0`. +""" +@inline function find_mass(mz_array::AbstractVector{<:Real}, intensity_array::AbstractVector{<:Real}, + target_mass::Real, tolerance::Real) + # Fast-path rejection: if the array is empty or the target is out of range + if isempty(mz_array) || target_mass + tolerance < first(mz_array) || target_mass - tolerance > last(mz_array) + return 0.0 + end + + lower_bound = target_mass - tolerance + upper_bound = target_mass + tolerance + + # Use binary search to find the start and end of the m/z window + start_idx = searchsortedfirst(mz_array, lower_bound) + end_idx = searchsortedlast(mz_array, upper_bound) + + # If the window is empty, return 0.0 + if start_idx > end_idx + return 0.0 + end + + # Find the maximum intensity within the identified window, optimized with @inbounds and @simd + max_intensity = intensity_array[start_idx] + @inbounds @simd for i in (start_idx + 1):end_idx + max_intensity = max(max_intensity, intensity_array[i]) + end + + return max_intensity +end + +""" + get_mz_slice(data::MSIData, mass::Real, tolerance::Real) + +Extracts an image slice for a given m/z value without plotting. +This is a performant function that iterates through spectra once. + +# Arguments + +- `data::MSIData`: The MSIData object. +- `mass::Real`: The target mass. +- `tolerance::Real`: The tolerance. +- `mask_path::Union{String, Nothing}`: The path to the mask. + +# Returns +- A `Matrix{Float64}` representing the intensity slice. +""" +function get_mz_slice(data::MSIData, mass::Real, tolerance::Real; mask_path::Union{String, Nothing}=nothing) + width, height = data.image_dims + slice_matrix = zeros(Float64, height, width) + + local masked_indices::Union{Set{Int}, Nothing} = nothing + if mask_path !== nothing + mask_matrix = load_and_prepare_mask(mask_path, (width, height)) + masked_indices = get_masked_spectrum_indices(data, mask_matrix) + println("Applying mask from: $(mask_path), found $(length(masked_indices)) spectra in ROI.") + end + + # INTELLIGENT LOADING: Ensure analytics are computed for filtering. + if !is_set(data.analytics_ready) + println("Per-spectrum metadata not found. Running one-time analytics computation...") + precompute_analytics(data) + end + + target_min = mass - tolerance + target_max = mass + tolerance + + # PERFORMANCE: Access raw vectors from metadata to avoid DataFrame dependency + # If stats_df exists, use it; otherwise, use the pre-computed bounds in SpectrumAsset + stats_df = get_spectrum_stats(data) + + n_total = length(data.spectra_metadata) + # Instantiate thread-local buffer locally since global pools are deprecated + candidate_indices = Vector{Int}(undef, n_total) + + # We'll use local views of min/max if stats_df is missing to represent zero-allocation fallback + # But for extreme performance, we avoid list comprehensions [m... for m in ...] as they allocate. + local min_mzs::Vector{Float64} + local max_mzs::Vector{Float64} + + if stats_df !== nothing + min_mzs = stats_df.MinMZ + max_mzs = stats_df.MaxMZ + else + # Fallback path: extract to local buffers or use metadata directly in loop + # For now, let's assume stats_df is usually populated by precompute_analytics. + # If not, we'll access it directly inside the filter loop. + end + candidate_count = 0 + indices_to_check = masked_indices === nothing ? (1:n_total) : masked_indices + discretization_factor = 100.0 + bloom_filters = get_bloom_filters(data) + + for i in indices_to_check + # Range check first (cheapest) + # Access metadata directly if stats_df is missing to ensure zero-allocation + @inbounds meta = data.spectra_metadata[i] + s_min, s_max = (stats_df !== nothing) ? (min_mzs[i], max_mzs[i]) : (meta.mz_asset.min_val, meta.mz_asset.max_val) + + if target_max < s_min || target_min > s_max + continue + end + + # Bloom filter rejection (very fast) + if bloom_filters !== nothing + bf = bloom_filters[i] + if !is_empty(bf) + min_mass_int = round(Int, (mass - tolerance) * discretization_factor) + max_mass_int = round(Int, (mass + tolerance) * discretization_factor) + + found = false + @inbounds for mass_int in min_mass_int:max_mass_int + if mass_int in bf + found = true + break + end + end + !found && continue + end + end + + candidate_count += 1 + @inbounds candidate_indices[candidate_count] = i + end + + # Use a view of the pre-allocated vector to avoid collect() allocations + valid_candidates = view(candidate_indices, 1:candidate_count) + + # 2. Iterate using the optimized, low-allocation iterator + # Use Atomic for thread-safe increment and avoid Ref-boxing + results_count = Base.Threads.Atomic{Int}(0) + + # Use let block to ensure closure captures are optimized (avoid boxing) + let slice_matrix=slice_matrix, results_count=results_count, width=width, height=height, + spectra_metadata=data.spectra_metadata, mass=mass, tolerance=tolerance + + _iterate_spectra_fast(data, valid_candidates) do idx, mz_array, intensity_array + @inbounds meta = spectra_metadata[idx] + intensity = find_mass(mz_array, intensity_array, mass, tolerance) + if intensity > 0.0 + if 1 <= meta.x <= width && 1 <= meta.y <= height + @inbounds slice_matrix[meta.y, meta.x] = intensity + Base.Threads.atomic_add!(results_count, 1) + end + end + end + end + + #println("Populated $(results_count[]) pixels with intensity data") + replace!(slice_matrix, NaN => 0.0) + return slice_matrix +end + + +""" + get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, tolerance::Real) + +Extracts multiple image slices for a given list of m/z values in a single pass. +This is a highly performant function that iterates through the full dataset only once. + +# Arguments + +- `data::MSIData`: The MSIData object. +- `masses::AbstractVector{<:Real}`: The target masses. +- `tolerance::Real`: The tolerance. +- `mask_path::Union{String, Nothing}`: The path to the mask. + +# Returns +- A `Dict{Real, Matrix{Float64}}` mapping each mass to its intensity slice matrix. +""" +function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, tolerance::Real; mask_path::Union{String, Nothing}=nothing) + width, height = data.image_dims + + # Sort masses to improve cache locality and allow binary search + sorted_masses = sort(masses) + n_masses = length(sorted_masses) + + # 1. Initialize a dictionary to hold the output slice matrices (using Float32 for 50% RAM savings) + slice_dict = Dict{Real, Matrix{Float32}}() + for mass in sorted_masses + slice_dict[mass] = zeros(Float32, height, width) + end + + local masked_indices::Union{Set{Int}, Nothing} = nothing + if mask_path !== nothing + mask_matrix = load_and_prepare_mask(mask_path, (width, height)) + masked_indices = get_masked_spectrum_indices(data, mask_matrix) + println("Applying mask from: $(mask_path), found $(length(masked_indices)) spectra in ROI.") + end + + # 2. Ensure analytics are computed for filtering. + if !is_set(data.analytics_ready) + println("Per-spectrum metadata not found. Running one-time analytics computation...") + precompute_analytics(data) + end + + println("Filtering candidate spectra for $n_masses m/z values...") + stats_df = get_spectrum_stats(data) + bloom_filters = get_bloom_filters(data) + + # Use a BitSet for faster index tracking + candidate_indices = BitSet() + indices_to_check = masked_indices === nothing ? (1:length(data.spectra_metadata)) : masked_indices + + # 3. Optimized filtering: Iterate through spectra ONCE and check against all masses + # This changes complexity from O(M*N) to O(N * log M) or O(N + M) depending on range overlap + discretization_factor = 100.0 + for i in indices_to_check + spec_min = stats_df.MinMZ[i] + spec_max = stats_df.MaxMZ[i] + + # Binary search to find masses that might overlap with this spectrum's range + # target_min = mass - tolerance => mass = target_min + tolerance + # We need mass such that mass + tolerance >= spec_min => mass >= spec_min - tolerance + # and mass - tolerance <= spec_max => mass <= spec_max + tolerance + + m_start_idx = searchsortedfirst(sorted_masses, spec_min - tolerance) + m_end_idx = searchsortedlast(sorted_masses, spec_max + tolerance) + + if m_start_idx <= m_end_idx + # Range overlap found, now check Bloom filter if available + if bloom_filters !== nothing && !is_empty(bloom_filters[i]) + found_any = false + @inbounds for m_idx in m_start_idx:m_end_idx + mass = sorted_masses[m_idx] + min_mass_int = round(Int, (mass - tolerance) * discretization_factor) + max_mass_int = round(Int, (mass + tolerance) * discretization_factor) + + for mass_int in min_mass_int:max_mass_int + if mass_int in bloom_filters[i] + found_any = true + break + end + end + found_any && break + end + if found_any + push!(candidate_indices, i) + end + else + push!(candidate_indices, i) + end + end + end + + println("Found $(length(candidate_indices)) total candidate spectra.") + + # 4. Iterate through the data a single time using the optimized iterator. + # We collect candidate_indices to pass to parallel iterator + _iterate_spectra_fast(data, collect(candidate_indices)) do idx, mz_array, intensity_array + meta = data.spectra_metadata[idx] + if isempty(mz_array) + return + end + + # Spectrum-level boundaries + spec_first = first(mz_array) + spec_last = last(mz_array) + + # Find which of our target masses fall within this specific spectrum's actual range + m_start_idx = searchsortedfirst(sorted_masses, spec_first - tolerance) + m_end_idx = searchsortedlast(sorted_masses, spec_last + tolerance) + + @inbounds for m_idx in m_start_idx:m_end_idx + mass = sorted_masses[m_idx] + intensity = find_mass(mz_array, intensity_array, mass, tolerance) + if intensity > 0.0 + if 1 <= meta.x <= width && 1 <= meta.y <= height + # Note: Concurrent writes to different matrices/coordinates are safe. + # Dictionary access is safe because it's read-only after initialization. + slice_dict[mass][meta.y, meta.x] = Float32(intensity) + end + end + end + end + + # 5. Clean up - replaces NaNs with 0.0 directly in Float32 matrices + for mass in sorted_masses + replace!(slice_dict[mass], NaN32 => 0.0f0) + end + + println("Finished generating $n_masses slices in a single pass.") + return slice_dict +end + + +""" + plot_slice(msi_data::MSIData, mass::Float64, tolerance::Float64, output_dir::String; stage_name="slice", bins=256) + +Generates and saves a plot of a single image slice for a given m/z value. +This function closely imitates the logic of the original `GetSlice` but uses +the modern `MSIData` access patterns and robust peak finding. + +# Arguments + +- `msi_data::MSIData`: The MSIData object. +- `mass::Real`: The target mass. +- `tolerance::Real`: The tolerance. +- `output_dir::String`: The output directory. +- `stage_name::String`: The name of the stage. +- `bins::Int`: The number of bins. +- `mask_path::Union{String, Nothing}`: The path to the mask. + +# Returns +- `fig::Figure`: A figure with the data plotted with colors applied. +""" +function plot_slice(msi_data::MSIData, mass::Real, tolerance::Real, output_dir::String; + stage_name="slice_mz_$(mass)", bins=256, mask_path::Union{String, Nothing}=nothing) + + # 1. Generate the slice, applying the mask if provided. + println("Generating slice for m/z $mass...") + slice_matrix = get_mz_slice(msi_data, mass, tolerance, mask_path=mask_path) + println("Slice generation complete.") + + # 2. Plot the resulting slice matrix using CairoMakie + println("Plotting slice...") + + fig = Figure(size = (600, 500)) + ax = CairoMakie.Axis(fig[1, 1], + aspect=DataAspect(), + title=@sprintf("Slice for m/z: %.2f", mass), + yreversed=true + ) + hidedecorations!(ax) + + # Use mass-specific bounds for colorrange, ensuring a valid range + min_val, max_val = extrema(slice_matrix) + if min_val == max_val + max_val = min_val + 1.0 # Ensure the color range has a non-zero width + end + hm = heatmap!(ax, slice_matrix, + colormap=cgrad(ColorSchemes.viridis, bins), + colorrange=(min_val, max_val) + ) + + Colorbar(fig[1, 2], hm, label="Intensity") + colgap!(fig.layout, 5) + + # 3. Save the plot + mkpath(output_dir) + filename = "$(stage_name).png" + save_path = joinpath(output_dir, filename) + save(save_path, fig) + @info "Saved slice plot to $save_path" + + return fig +end + +# ============================================================================ +# +# +# Image Processing and Normalization +# +# ============================================================================ + +""" + get_outlier_thres(img, prob=0.98) + +Calculates dynamic intensity range bounds for an image based on a cumulative +probability histogram. This function replicates an R algorithm to find an +intensity threshold that corresponds to a given cumulative probability, which +is used to exclude outliers before normalization. + +# Arguments +- `img`: The input image matrix. +- `prob`: The cumulative probability threshold (default: 0.98) for outlier detection. + +# Returns +- A tuple `(low, high)` representing the calculated lower and upper intensity bounds. +""" +function get_outlier_thres(img::AbstractVector{<:Real}, prob::Real=0.98) + # DO NOT filter zeros. Use all pixel values like R does. + int_values = img + low = minimum(int_values) + upp = maximum(int_values) + + # Create histogram bins + if upp - low + 1 >= 100 + bins = 100 + brk = range(low, stop=upp + (upp - low)/(bins - 1), length=bins + 1) + else + brk = collect(floor(low):(ceil(upp) + 1)) + end + + # Compute histogram with RIGHT-CLOSED = FALSE to mimic R's right=FALSE + # This makes intervals [a, b) instead of the default [a, b] + h = fit(Histogram, int_values, brk, closed=:left) # Key change: closed=:left + + # Check if histogram is valid + if isempty(h.weights) || sum(h.weights) == 0 + return (low, upp) + end + + # Replicate R's algorithm exactly + cum_counts = cumsum(h.weights) / sum(h.weights) + # Calculate the difference from the target probability + top = prob .- cum_counts + delta = abs.(top) + # Find the index where the difference is minimized + min_delta_index = findfirst(x -> x == minimum(delta), delta) + + # R adds 1 to this index: index <- 1 + which(...)[1] + target_bin_index = min_delta_index + 1 + # Get the upper edge of the target bin + target_bin_upper_edge = h.edges[1][target_bin_index] + + # Find the maximum data value that is strictly less than this edge + # This mimics: max( intMap[ intMap < h$breaks[index] ] ) + values_below_edge = filter(x -> x < target_bin_upper_edge, int_values) + actual_threshold = isempty(values_below_edge) ? low : maximum(values_below_edge) + + return (low, actual_threshold) +end + +function get_outlier_thres(img::AbstractMatrix{<:Real}, prob::Real=0.98) + return get_outlier_thres(vec(img), prob) +end + +""" + set_pixel_depth(img, bounds, depth) + +Quantizes the intensity values of an image into a specified number of bins +(`depth`) within a given intensity range (`bounds`). Pixels outside the bounds +are clipped. + +# Arguments +- `img`: The input image matrix. +- `bounds`: A tuple `(min, max)` specifying the intensity range for quantization. +- `depth`: The number of quantization levels (bins). + +# Returns +- A `Matrix{UInt8}` with pixel values quantized to the specified depth. +""" +function set_pixel_depth(img::AbstractMatrix{<:Real}, bounds::Tuple{<:Real, <:Real}, depth::Integer) + min_val, max_val = bounds + bins = depth - 1 + + if min_val >= max_val + return zeros(UInt8, size(img)) + end + + # Create intensity bins - FIXED: use binary search instead of linear scan + range_vals = range(min_val, stop=max_val, length=depth)[2:depth] + + # Pre-allocate result for better performance + result = similar(img, UInt8) + + # Use binary search for much faster bin assignment + @inbounds for i in eachindex(img) + val = img[i] + if val <= min_val + result[i] = 0 + elseif val >= max_val + result[i] = bins + else + # Binary search is much faster than linear scan + bin_idx = searchsortedfirst(range_vals, val) + result[i] = bin_idx + end + end + + return result +end + +""" + TrIQ(pixMap, depth, prob=0.98) + +Applies TrIQ (Treshold Intensity Quantization) normalization to an image. +This function first computes dynamic intensity range bounds by identifying outliers +based on a cumulative probability, then sets the pixel depth (quantizes intensities) +within these bounds. + +# Arguments +- `pixMap`: The input image matrix (e.g., a slice from `GetMzSliceJl`). +- `depth`: The number of grey levels (bins) to quantize the intensities into. +- `prob`: The target cumulative probability (e.g., 0.98) used to determine outlier thresholds. + +# Returns +- A new image matrix with intensities quantized to the specified depth within the TrIQ bounds. +""" +function TrIQ(pixMap::AbstractMatrix{<:Real}, depth::Integer, prob::Real=0.98; mask_matrix::Union{BitMatrix, Nothing}=nothing) + local values_for_thres + if mask_matrix !== nothing + values_for_thres = pixMap[mask_matrix] + filter!(x -> x != 0, values_for_thres) + else + values_for_thres = pixMap + end + + if isempty(values_for_thres) || all(iszero, values_for_thres) + bounds = (0.0, 0.0) + quantized = zeros(UInt8, size(pixMap)) + else + bounds = get_outlier_thres(values_for_thres, prob) + quantized = set_pixel_depth(pixMap, bounds, depth) + end + + return quantized, bounds # Return both! +end + +""" + norm_slices_hist(slices, bins; prob=0.98) + +Normalizes a set of image slices based on a shared histogram range. + +# Arguments + +- `slices`: The image slices. +- `bins`: The number of bins. +- `prob`: The target cumulative probability. + +# Returns +- `norm_img`: The normalized image slices. +- `mass_bounds`: The bounds for each mass. +""" +function norm_slices_hist(slices, bins; prob=0.98) + n_files, n_masses = size(slices) + norm_img = similar(slices) + mass_bounds = [] # This will store bounds for EACH mass + + # Calculate bounds for each mass across all files + for mass_idx in 1:n_masses + # Get all slices for this specific mass across all files + mass_slices = [slices[i, mass_idx] for i in 1:n_files] + all_vals = reduce(vcat, [vec(s) for s in mass_slices]) + + # Calculate global bounds for this specific mass + mass_global_bounds = get_outlier_thres(all_vals, prob) + push!(mass_bounds, mass_global_bounds) + + # Normalize each file's slice for this mass using its specific bounds + for file_idx in 1:n_files + norm_img[file_idx, mass_idx] = set_pixel_depth(slices[file_idx, mass_idx], mass_global_bounds, bins) + end + end + + return (norm_img=norm_img, bounds=mass_bounds) # bounds is now a vector, one per mass +end + +""" + quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256) + +Linearly scales the intensity values in a slice to a specified number of levels. +The output is an array of `UInt8` values. +This is a modernized version of the original `IntQuantCl`. by Nacho + +# Arguments + +- `slice`: The image slice. +- `levels`: The number of levels. +- `mask_matrix`: The mask matrix. + +# Returns +- `quantized`: The quantized image slice. +- `bounds`: The bounds for each mass. +""" +function quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256; mask_matrix::Union{BitMatrix, Nothing}=nothing) + local max_val + if mask_matrix !== nothing + masked_slice = slice[mask_matrix] + # Filter out zeros that might have been introduced by masking, if any + filter!(x -> x != 0, masked_slice) + max_val = isempty(masked_slice) ? 0.0 : maximum(masked_slice) + else + max_val = maximum(slice) + end + + if max_val <= 0 + bounds = (0.0, 0.0) + quantized = zeros(UInt8, size(slice)) + else + bounds = (0.0, max_val) + quantized = similar(slice, UInt8) + scale = (levels - 1) / max_val + @inbounds for i in eachindex(slice) + quantized[i] = round(UInt8, clamp(slice[i] * scale, 0, levels - 1)) + end + end + + return quantized, bounds # Return both! +end + +""" + median_filter(img) + +Applies a 3x3 median filter to the input image. This is a simple noise +reduction technique that replaces each pixel's value with the median value of +its 3x3 neighborhood. + +# Arguments +- `img`: The input image matrix. + +# Returns +- A new matrix containing the filtered image. +""" +function median_filter(img) + # 3x3 median filter implementation + return mapwindow(median, img, (3, 3)) +end + + + +""" + downsample_spectrum(mz, intensity, n_points=2000) + +Reduces the number of points in a spectrum for faster plotting, while preserving peaks. +It divides the m/z range into `n_points` bins and keeps only the most intense point from each bin. + +# Arguments + +- `mz`: The m/z values. +- `intensity`: The intensity values. +- `n_points`: The number of points. + +# Returns +- `mz`: The downsampled m/z values. +- `intensity`: The downsampled intensity values. +""" +function downsample_spectrum(mz::AbstractVector, intensity::AbstractVector, n_points::Integer=2000) + if isempty(mz) || length(mz) <= n_points + return mz, intensity + end + + mz_min, mz_max = extrema(mz) + bin_width = (mz_max - mz_min) / n_points + + # We use a vector of tuples to store the max intensity and its corresponding mz for each bin + # (max_intensity, mz_value) + bins = fill((0.0, 0.0), n_points) + + for i in eachindex(mz) + # Determine the bin for the current point + # Bin indices are 1-based + bin_index = min(n_points, floor(Int, (mz[i] - mz_min) / bin_width) + 1) + + # If the current point's intensity is higher than what's in the bin, replace it + if intensity[i] > bins[bin_index][1] + bins[bin_index] = (intensity[i], mz[i]) + end + end + + # Filter out empty bins and separate the mz and intensity values + final_mz = [b[2] for b in bins if b[1] > 0.0] + final_intensity = [b[1] for b in bins if b[1] > 0.0] + + return final_mz, final_intensity +end + +# ============================================================================ +# +# +# Analysis and Visualization +# +# ============================================================================ + +""" + plot_slices(slices, names, masses, output_dir; stage_name, bins=256, dpi=150, global_bounds=nothing) + +Generates and saves a grid of image slice plots. Each row corresponds to a +file and each column to a mass, creating a comprehensive overview. + +# Arguments +- `slices`: A 2D array of image slice matrices (`n_files` x `n_masses`). +- `names`: A vector of file names, used for titling rows. +- `masses`: A vector of m/z values, used for titling columns. +- `output_dir`: The directory where the output plots will be saved. + +# Keyword Arguments +- `stage_name`: A string used to name the output files (e.g., "raw", "normalized"). +- `bins`: The number of color levels in the heatmap palette. +- `dpi`: The resolution for the saved image files. +- `global_bounds`: A vector of `(min, max)` tuples, one for each mass, to ensure a consistent + color scale across all files for a given mass. If `nothing`, bounds are calculated automatically. + +# Returns +- The generated `Figure` object from Makie. +""" +function plot_slices(slices, names, masses, output_dir; stage_name, bins=256, dpi=150, global_bounds=nothing) + n_files, n_masses = size(slices) + + mkpath(output_dir) + + # If global_bounds is provided, it should now be a VECTOR of bounds (one per mass) + # If not provided, calculate per-mass bounds + if global_bounds === nothing + global_bounds = [] + for mass_idx in 1:n_masses + mass_slices = [slices[i, mass_idx] for i in 1:n_files] + all_vals = reduce(vcat, [vec(s) for s in mass_slices]) + filter!(isfinite, all_vals) + mass_bounds = isempty(all_vals) ? (0.0, 1.0) : extrema(all_vals) + push!(global_bounds, mass_bounds) + end + end + + # With Makie, we define a Figure and a layout. + fig = Figure(size = (400 * n_masses, 330 * n_files)) # Adjusted size calculation + + # Add a title for the entire figure. + Label(fig[0, 1:(2*n_masses)], "Image Slices - $(stage_name)", fontsize=24, font=:bold, tellwidth=false, padding=(0,0,10,0)) + + for file_idx in 1:n_files + for mass_idx in 1:n_masses + img = slices[file_idx, mass_idx] + mass = masses[mass_idx] + name = names[file_idx] + mass_global_bounds = global_bounds[mass_idx] # Get bounds for THIS specific mass + + # --- Calculate tick properties for THIS mass --- + min_val, max_val = mass_global_bounds + levels = range(min_val, stop=max_val, length=bins + 1) + level_range = levels[end] - levels[1] + + if level_range == 0 + levels = range(min_val - 0.1, stop=max_val + 0.1, length=bins + 1) + level_range = 0.2 + end + + exponent = level_range > 0 ? floor(log10(level_range)) / 3 : 0 + scale = 10^(3 * exponent) + scaled_levels = levels ./ scale + + format_num = level_range > 0 ? floor(log10(level_range)) % 3 : 0 + labels = if format_num == 0 + [@sprintf("%3.2f", lvl) for lvl in scaled_levels] + elseif format_num == 1 + [@sprintf("%3.2f", lvl) for lvl in scaled_levels] + else + [@sprintf("%3.2f", lvl) for lvl in scaled_levels] + end + + divisors = 2:7 + remainders = (bins - 1) .% divisors + best_divisor = divisors[findlast(x -> x == minimum(remainders), remainders)] + tick_indices = round.(Int, range(1, stop=bins + 1, length=best_divisor + 1)) + + if !(1 in tick_indices) + pushfirst!(tick_indices, 1) + end + if !((bins + 1) in tick_indices) + push!(tick_indices, bins + 1) + end + unique!(sort!(tick_indices)) + + tick_positions = levels[tick_indices] + tick_labels = labels[tick_indices] + # --- End of mass-specific tick calculation --- + + # Create an Axis for the heatmap + ax = CairoMakie.Axis(fig[file_idx, 2*mass_idx-1], + aspect=DataAspect(), + title=@sprintf("%s\nm/z: %.2f", basename(name), mass), + titlesize=14 + ) + hidedecorations!(ax) + + # Use mass-specific bounds for colorrange + hm = heatmap!(ax, transpose(img), + colormap=cgrad(ColorSchemes.viridis, bins), + colorrange=mass_global_bounds # ← This is mass-specific + ) + + # Add a colorbar with mass-specific scale + cb = Colorbar(fig[file_idx, 2*mass_idx], hm, + label=(scale == 1 ? "" : "×10^$(round(Int, 3 * exponent))"), + labelpadding=2, + labelsize=12, + ticks=(tick_positions, tick_labels), + ticklabelsize=10 + ) + colsize!(fig.layout, 2*mass_idx, 30) + end + end + + colgap!(fig.layout, 5) + rowgap!(fig.layout, 10) + + # Save in multiple formats. + formats = ["png", "pdf"] + + for fmt in formats + filename = "$(stage_name)_overview.$(fmt)" + save_path = joinpath(output_dir, filename) + save(save_path, fig, px_per_unit = dpi / 96.0) + @info "Saved $(fmt) overview plot to $save_path" + end + return fig +end + +""" + save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32}) + +Saves an 8-bit indexed image as a BMP file. +This is a modernized version of `SaveBitmapCl`. + +# Arguments + +- `name`: The name of the file. +- `pixMap`: The pixel map. +- `colorTable`: The color table. + +# Returns +- `nothing` +""" +function save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32}) + # Get image dimensions + height, width = size(pixMap) + + # Normalize pixel values to stretch contrast, as in the original SaveBitmapCl + minVal, maxVal = extrema(pixMap) + if maxVal > minVal + pixMap = round.(UInt8, 255 * (pixMap .- minVal) ./ (maxVal - minVal)) + end + + # Compute row padding (each row must be a multiple of 4 bytes) + padding = (4 - (width % 4)) % 4 + + # BMP color table must have 256 entries for 8-bit images + fullColorTable = Vector{UInt32}(undef, 256) + if length(colorTable) <= 256 + fullColorTable[1:length(colorTable)] .= colorTable + fullColorTable[length(colorTable)+1:end] .= 0 + else + fullColorTable .= colorTable[1:256] + end + + # Compute file dimensions + offset = 14 + 40 + (256 * 4) # 14(file) + 40(info) + 1024(palette) = 1078 + imgBytes = height * (width + padding) + fileSize = offset + imgBytes + + open(name, "w") do stream + # === File Header (14 bytes) === + write(stream, UInt16(0x4D42)) # "BM" + write(stream, UInt32(fileSize)) + write(stream, UInt16(0)) # Reserved + write(stream, UInt16(0)) # Reserved + write(stream, UInt32(offset)) + + # === Info Header (40 bytes) === + write(stream, UInt32(40)) # Info header size + write(stream, Int32(width)) + write(stream, Int32(height)) # Positive for bottom-up storage + write(stream, UInt16(1)) # Number of color planes + write(stream, UInt16(8)) # Bits per pixel + write(stream, UInt32(0)) # Compression (BI_RGB) + write(stream, UInt32(imgBytes)) + write(stream, Int32(2835)) # Pels per meter X (~72 DPI) + write(stream, Int32(2835)) # Pels per meter Y (~72 DPI) + write(stream, UInt32(256)) # Colors in color table + write(stream, UInt32(0)) # Important colors (0 = all) + + # === Color Table === + write(stream, fullColorTable) + + # === Image Pixels (written bottom-up) === + row_buffer = Vector{UInt8}(undef, width + padding) + row_buffer[width+1:end] .= 0 # pre-fill padding bytes + + for i in height:-1:1 + row_data = @view pixMap[i, :] + row_buffer[1:width] = row_data + write(stream, row_buffer) + end + end +end + +""" + generate_palette(colorscheme, n_colors=256) + +Generates a BMP-compatible UInt32 color palette from a ColorScheme. + +# Arguments + +- `colorscheme`: The colorscheme. +- `n_colors`: The number of colors. + +# Returns +- `palette`: The color palette. +""" +function generate_palette(colorscheme, n_colors=256) + palette = Vector{UInt32}(undef, n_colors) + colors = get(colorscheme, range(0, 1, length=n_colors)) + for i in 1:n_colors + c = colors[i] + r = round(UInt8, c.r * 255) + g = round(UInt8, c.g * 255) + b = round(UInt8, c.b * 255) + # BMP color table format is 0x00RRGGBB, written little-endian becomes BB GG RR 00 + palette[i] = (UInt32(r) << 16) | (UInt32(g) << 8) | UInt32(b) + end + return palette +end + +# Viridis color palette (256 colors) - defined as constant +const ViridisPalette = generate_palette(ColorSchemes.viridis) + +""" + generate_colorbar_image(slice_data::AbstractMatrix, color_levels::Int, output_path::String, + bounds::Tuple{Float64, Float64}; + use_triq::Bool=false, triq_prob::Float64=0.98, + mask_path::Union{String, Nothing}=nothing) + +Generates a colorbar image for a given slice of data. + +# Arguments + +- `slice_data`: The slice data. +- `color_levels`: The number of color levels. +- `output_path`: The output path. +- `bounds`: The bounds for the colorbar. +- `use_triq`: Whether to use triq. +- `triq_prob`: The probability of using triq. +- `mask_path`: The path to the mask. + +# Returns +- `fig::Figure`: A figure with the colorbar. +""" +function generate_colorbar_image(slice_data::AbstractMatrix, color_levels::Int, output_path::String, + bounds::Tuple{Real, Real}; + use_triq::Bool=false, triq_prob::Float64=0.98, + mask_path::Union{String, Nothing}=nothing) + # Use the provided bounds instead of recalculating + min_val, max_val = bounds + + # If bounds are invalid, calculate fallback + if min_val == max_val == 0.0 + local data_for_bounds + if mask_path !== nothing + height, width = size(slice_data) + mask_matrix = load_and_prepare_mask(mask_path, (width, height)) + data_for_bounds = slice_data[mask_matrix] + filter!(x -> x > 0, data_for_bounds) + else + data_for_bounds = vec(slice_data) + end + min_val, max_val = isempty(data_for_bounds) ? (0.0, 1.0) : extrema(data_for_bounds) + end + + # 2. Replicate the tick calculation logic from plot_slices + bins = color_levels + levels = range(min_val, stop=max_val, length=bins + 1) + level_range = levels[end] - levels[1] + + if level_range == 0 + levels = range(min_val - 0.1, stop=max_val + 0.1, length=bins + 1) + level_range = 0.2 + end + + exponent = level_range > 0 ? floor(log10(level_range)) / 3 : 0 + scale = 10^(3 * exponent) + scaled_levels = levels ./ scale + + format_num = level_range > 0 ? floor(log10(level_range)) % 3 : 0 + labels = if format_num == 0 + [ @sprintf("%3.2f", lvl) for lvl in scaled_levels] + elseif format_num == 1 + [ @sprintf("%3.2f", lvl) for lvl in scaled_levels] + else + [ @sprintf("%3.2f", lvl) for lvl in scaled_levels] + end + + divisors = 2:7 + remainders = (bins - 1) .% divisors + best_divisor = divisors[findlast(x -> x == minimum(remainders), remainders)] + tick_indices = round.(Int, range(1, stop=bins + 1, length=best_divisor + 1)) + + if !(1 in tick_indices) + pushfirst!(tick_indices, 1) + end + if !((bins + 1) in tick_indices) + push!(tick_indices, bins + 1) + end + unique!(sort!(tick_indices)) + + tick_positions = levels[tick_indices] + tick_labels = labels[tick_indices] + + # 3. Create and save the colorbar image + fig = Figure(size=(150, 250)) + Colorbar(fig[1, 1], + colormap=cgrad(:viridis, bins, categorical=true), + # limits=(min_val, max_val), + limits=(levels[1], levels[end]), + label=(scale == 1 ? "Intensity" : "Intensity ×10^$(round(Int, 3 * exponent))"), + ticks=(tick_positions, tick_labels), + labelsize=20, + ticklabelsize=16 + ) + save(output_path, fig) +end diff --git a/src/mzML.jl b/src/mzML.jl new file mode 100644 index 0000000..d3afd94 --- /dev/null +++ b/src/mzML.jl @@ -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("", line) || occursin("", line) + break + end + header_block *= line * "\n" + end + + header_io = IOBuffer(header_block) + while !eof(header_io) + line = readline(header_io) + + if occursin("` 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 `` 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"", line) + break + end + if occursin("") + 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, "") + #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 `` 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 `` 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("", line) + break + end + end + spectrum_xml = String(take!(spectrum_buffer)) + seek(stream, spectrum_start_pos) # Reset for other parsing + + id_match = match(r"` 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 `` block. + +# Returns +- A `Vector{Int64}` containing the byte offsets for all spectra. +""" +function parse_offset_list(stream::IO) + offsets = Int64[] + offset_regex = r"]*>(\d+)" + + # 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("", line) || occursin("", 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"(\d+)", footer) + if index_offset_match === nothing + throw(FileFormatError("Could not find . 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 = Threads.nthreads() + 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 ''.") + if find_tag(primary_handle, r" 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