fixed docker Julia issues, tested reproductability across all scripts through the docker

This commit is contained in:
Pixelguy14
2026-06-03 13:38:45 -06:00
parent 3143e29843
commit 242fc6a445
13 changed files with 410 additions and 183 deletions
+3 -1
View File
@@ -1,4 +1,6 @@
MSI_julia-python_mapping.md
data/Leaf.imzML data/Leaf.imzML
data/Leaf.ibd data/Leaf.ibd
data/Leaf.imzML.cache
JuliaMSI/ JuliaMSI/
environment/Manifest.toml
datos_para_ai/*
+7 -9
View File
@@ -5,7 +5,6 @@ FROM nvidia/cuda:12.4.1-runtime-ubuntu22.04
ENV DEBIAN_FRONTEND=noninteractive ENV DEBIAN_FRONTEND=noninteractive
# 1. Install System Dependencies # 1. Install System Dependencies
# Includes Julia requirements, Python, and Headless Display libs for GLMakie
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
wget \ wget \
curl \ curl \
@@ -18,7 +17,6 @@ RUN apt-get update && apt-get install -y \
libpng-dev \ libpng-dev \
libjpeg-dev \ libjpeg-dev \
libfreetype6-dev \ libfreetype6-dev \
# Display dependencies for GLMakie/GLFW (fixes "X11: The DISPLAY environment variable is missing")
xvfb \ xvfb \
libgl1-mesa-glx \ libgl1-mesa-glx \
libgl1-mesa-dri \ libgl1-mesa-dri \
@@ -36,36 +34,36 @@ RUN curl -fsSL https://julialang-s3.julialang.org/bin/linux/x64/1.11/julia-1.11.
WORKDIR /app WORKDIR /app
# 4. Integrate JuliaMSI Framework # 4. Integrate JuliaMSI Framework
# We use the local JuliaMSI folder
COPY JuliaMSI /opt/JuliaMSI COPY JuliaMSI /opt/JuliaMSI
WORKDIR /opt/JuliaMSI WORKDIR /opt/JuliaMSI
# Set DISPLAY for xvfb
ENV DISPLAY=:99 ENV DISPLAY=:99
# Instantiate and precompile. We skip sysimage creation due to RAM constraints. # Instantiate framework package
RUN xvfb-run -s "-screen 0 1024x768x24" julia --project=. -e 'using Pkg; Pkg.instantiate(); Pkg.precompile()' RUN xvfb-run -s "-screen 0 1024x768x24" julia --project=. -e 'using Pkg; Pkg.instantiate(); Pkg.precompile()'
# 5. Setup Project Root and Environments # 5. Setup Project Root and Environments
WORKDIR /app WORKDIR /app
COPY environment/ /app/environment/ COPY environment/ /app/environment/
# Isolate Python dependencies so they stay cached if Julia fails # Isolate Python dependencies for cleaner caching layers
RUN pip3 install --no-cache-dir -r environment/requirements.txt RUN pip3 install --no-cache-dir -r environment/requirements.txt
# Force Julia 1.11.3 to resolve the 1.11.7 manifest to its own stdlibs first, then instantiate # Force Julia 1.11.3 to resolve environments natively using your fixed UUID entries
RUN julia --project=environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()' RUN julia --project=environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
# Register JuliaMSI explicitly into the runtime environment project
RUN julia --project=environment -e 'using Pkg; Pkg.develop(path="/opt/JuliaMSI")'
# 6. Copy Application Files # 6. Copy Application Files
COPY . /app COPY . /app
# 7. Final Configuration # 7. Final Configuration
ENV JULIA_LOAD_PATH="/opt/JuliaMSI:${JULIA_LOAD_PATH}" ENV JULIA_LOAD_PATH="/opt/JuliaMSI:/opt/JuliaMSI/src:${JULIA_LOAD_PATH}"
ENV PYTHONPATH="/app/scripts_python:${PYTHONPATH}" ENV PYTHONPATH="/app/scripts_python:${PYTHONPATH}"
ENV DISPLAY=:99 ENV DISPLAY=:99
LABEL maintainer="MSI Hybrid Workflow Team" LABEL maintainer="MSI Hybrid Workflow Team"
LABEL description="CUDA + Julia 1.11.3 + JuliaMSI Framework" LABEL description="CUDA + Julia 1.11.3 + JuliaMSI Framework"
# Default to interactive bash
CMD ["/bin/bash"] CMD ["/bin/bash"]
+28 -20
View File
@@ -34,7 +34,7 @@ docker run -it --rm -v $(pwd):/app msi-hybrid-workflow
### Running the Container (GPU/CUDA Mode) ### Running the Container (GPU/CUDA Mode)
```bash ```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow
``` ```
## Usage Workflow ## Usage Workflow
@@ -42,15 +42,21 @@ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow
### 1. Preprocessing (Julia) ### 1. Preprocessing (Julia)
Leverage Julia's performance and the **JuliaMSI** framework. Leverage Julia's performance and the **JuliaMSI** framework.
**Run the MSI Bridge (Normalization & PNG Export):** **Run this clean runtime instantiation command one time to sync everything down to your local directory:**
```bash ```bash
docker run -it --rm -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm -v $(pwd):/app msi-hybrid-workflow \
julia --threads auto --project=/app/environment scripts_julia/julia_msi_bridge.jl julia --project=/app/environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
```
**Run the MSI Bridge (Normalization & PNG Export):**
```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
julia --threads auto --project=/app/environment /app/scripts_julia/julia_msi_bridge.jl
``` ```
**Optional: Plot Cluster Spectra:** **Optional: Plot Cluster Spectra:**
```bash ```bash
docker run -it --rm -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
julia --threads auto --project=/app/environment scripts_julia/graph_cluster_spectra.jl julia --threads auto --project=/app/environment scripts_julia/graph_cluster_spectra.jl
``` ```
@@ -59,7 +65,12 @@ Train the SimCLR encoder to extract morphological features using CUDA.
**Run CNN Training (SimCLR):** **Run CNN Training (SimCLR):**
```bash ```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm \
--shm-size=2gb \
--gpus all \
-v $(pwd):/app \
-v msi_torch_cache:/root/.cache/torch \
msi-hybrid-workflow \
python3 scripts_python/CNN_proof_1.py python3 scripts_python/CNN_proof_1.py
``` ```
*Note: The script automatically detects CUDA and logs per-epoch RAM usage.* *Note: The script automatically detects CUDA and logs per-epoch RAM usage.*
@@ -67,6 +78,12 @@ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
### 3. Clustering & Validation ### 3. Clustering & Validation
Determine optimal clusters and perform quantitative validation. Determine optimal clusters and perform quantitative validation.
**Generate Clusters:**
```bash
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
python3 scripts_python/cluster_msi_direct.py
```
**Evaluate Clustering:** **Evaluate Clustering:**
```bash ```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
@@ -75,7 +92,7 @@ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
**Quantitative Validation:** **Quantitative Validation:**
```bash ```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
python3 scripts_python/quantitative_validation.py python3 scripts_python/quantitative_validation.py
``` ```
@@ -84,28 +101,19 @@ Generate the final galleries and t-SNE maps.
**Generate t-SNE Maps:** **Generate t-SNE Maps:**
```bash ```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
python3 scripts_python/graficar_tsne_msi.py python3 scripts_python/graficar_tsne_msi.py
``` ```
**Create Cluster Galleries:** **Create Cluster Galleries:**
```bash ```bash
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \ docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
python3 scripts_python/visualize_clusters.py python3 scripts_python/visualize_clusters.py
``` ```
## Benchmarking & Hardware Realism ## Citation & Acknowledgments
The pipeline is optimized for efficiency on consumer-grade hardware. This implementation is based on the methodology proposed by:
- **Julia Stage**: Uses `BenchmarkTools.jl` to profile binary parsing. > Hu, H., Bindu, J. P., & Laskin, J. (2022). Self-supervised clustering of mass spectrometry imaging data using contrastive learning. *Chemical Science*, 13(1), 90-98. DOI: [10.1039/d1sc04077d](https://doi.org/10.1039/d1sc04077d)
- **Python Stage**: Uses `psutil` and `CUDA` monitoring to track hardware overhead.
- **Determinism**: All stochastic steps are locked with `seed=42`.
## Julia-Python Bridge Details
The "two-language problem" is solved by an intermediate file-system bridge. Julia performs binary MSI parsing and **Threshold Intensity Quantization (TrIQ)**. The resulting data is saved as high-contrast 224x224 grayscale PNG images, allowing the Python PyTorch pipeline to consume it efficiently.
## Citation
If you use this workflow or the JuliaMSI framework, please cite:
> Sierra-Álvarez, J. J., et al. (2025). JuliaMSI: A high-performance graphical platform for mass spectrometry imaging data analysis. *Analytica Chimica Acta*, 1377, 344613. DOI: [10.1016/j.aca.2025.344613](https://doi.org/10.1016/j.aca.2025.344613)
## License ## License
This project is licensed under the **MIT License**. This project is licensed under the **MIT License**.
+10
View File
@@ -61,3 +61,13 @@ We implemented **Additive Gaussian Noise ($\sigma=0.01$)**. This is critical for
### 4.4 Dimensionality Reduction ### 4.4 Dimensionality Reduction
PCA was used to reduce the 1280-dim (EfficientNet) or 128-dim (Projector) features to **50 components** before k-means. This heuristic stabilizes clustering by removing noise and redundant dimensions. PCA was used to reduce the 1280-dim (EfficientNet) or 128-dim (Projector) features to **50 components** before k-means. This heuristic stabilizes clustering by removing noise and redundant dimensions.
* *Citation:* Jolliffe (2002). * *Citation:* Jolliffe (2002).
## Benchmarking & Hardware Realism
The pipeline is optimized for efficiency on consumer-grade hardware.
- **Julia Stage**: Uses `BenchmarkTools.jl` to profile binary parsing.
- **Python Stage**: Uses `psutil` and `CUDA` monitoring to track hardware overhead.
- **Determinism**: All stochastic steps are locked with `seed=42`.
## Julia-Python Bridge Details
The "two-language problem" is solved by an intermediate file-system bridge. Julia performs binary MSI parsing and **Threshold Intensity Quantization (TrIQ)**. The resulting data is saved as high-contrast 224x224 grayscale PNG images, allowing the Python PyTorch pipeline to consume it efficiently.
+42
View File
@@ -1,7 +1,49 @@
[deps] [deps]
Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
CodecBase = "6c391c72-fb7b-5838-ba82-7cfb1bcfecbf"
ColorSchemes = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
Colors = "5ae59095-9a9b-59fe-a467-6f913c188581"
ContinuousWavelets = "96eb917e-2868-4417-9cb6-27e7ff17528f"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
GLMakie = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a"
Genie = "c43c736e-a2d1-11e8-161f-af95117fbd1e"
GenieFramework = "a59fdf5c-6bf0-4f5d-949c-a137c9e2f353"
HistogramThresholding = "2c695a8d-9458-5d45-9878-1b8a99cf7853"
ImageBinarization = "cbc4b850-ae4b-5111-9e64-df94c024a13d"
ImageComponentAnalysis = "d9b9e9a0-1569-11e9-2cb5-bbca914b0e89"
ImageContrastAdjustment = "f332f351-ec65-5f6a-b3d1-319c6670881a"
ImageCore = "a09fc81d-aa75-5fe9-8630-4744c3626534"
ImageFiltering = "6a3955dd-da59-5b1f-98d4-e7296123deb5"
ImageMorphology = "787d08f9-d448-5407-9aad-5290dd7ab264"
ImageSegmentation = "80713f31-8817-5129-9cf8-209ff8fb23e1"
Images = "916415d5-f1e6-5110-898d-aaa5f9f070e0" Images = "916415d5-f1e6-5110-898d-aaa5f9f070e0"
Interpolations = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" Interpolations = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
JLD2 = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
Libz = "2ec943e9-cfe8-584d-b93d-64dcb6d567b7"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Loess = "4345ca2d-374a-55d4-8d30-97f9976e7612"
Mmap = "a63ad114-7e13-5084-954f-fe012c677804"
NativeFileDialog = "e1fe445b-aa65-4df4-81c1-2041507f0fd4"
NaturalSort = "c020b1a1-e9b0-503a-9c33-f039bfc54a85"
PackageCompiler = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d"
Parameters = "d96e819e-fc66-5662-9728-84c9c7592b0a"
PlotlyBase = "a03496cd-edff-5a9b-9e67-9cda94a718b5"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca"
SavitzkyGolay = "c4bf5708-b6a6-4fbe-bcd0-6850ed671584"
Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
Setfield = "efcf1570-3423-57d1-acb7-fd33fddbac46"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
StipplePlotly = "ec984513-233d-481d-95b0-a3b58b97af2b"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+61 -36
View File
@@ -1,70 +1,95 @@
using MSI_src using Pkg
using CSV, DataFrames Pkg.activate("/app/environment")
# Handle dynamic environment fallback
if !haskey(Pkg.project().dependencies, "Plots")
Pkg.add("Plots")
end
ENV["GKSwstype"] = "100" # Headless rendering for Docker container
using Plots using Plots
# Load framework core dependencies smoothly
juliamsi_path = "/app/JuliaMSI"
push!(LOAD_PATH, joinpath(juliamsi_path, "src"))
include(joinpath(juliamsi_path, "src", "MSI_src.jl"))
using .MSI_src
using CSV, DataFrames
using Statistics using Statistics
using Plots.Measures using Plots.Measures
# 1. Data loading # 1. PATH CONFIGURATIONS
data_path = "Leaf.imzML" data_path = "/app/data/Leaf.imzML"
mask_path = "region_of_interest.png" mask_path = "/app/data/region_of_interest.png"
clusters_path = "msi_clusters_results.csv" clusters_path = "/app/msi_clusters_results.csv"
println("Loading data...") println("Loading data arrays...")
data = OpenMSIData(data_path) data = OpenMSIData(data_path)
clusters_df = CSV.read(clusters_path, DataFrame) clusters_df = CSV.read(clusters_path, DataFrame)
# 2. Get Average Spectrum (Single reference) # 2. RUN FRAMEWORK ANALYTICS TO DISCOVER PHYSICAL BOUNDARIES
println("Syncing Dataset Precomputed Boundaries...")
MSI_src.precompute_analytics(data)
# Extract binned spectrum arrays
mzs_avg, ints_avg = MSI_src.get_average_spectrum(data, mask_path=mask_path) mzs_avg, ints_avg = MSI_src.get_average_spectrum(data, mask_path=mask_path)
# 3. Configure base plot (Thin, clean gray line) # --- DYNAMIC AXIS SAFEGUARD ---
# Query the atomic fields populated by precompute_analytics
# fallback to standard values if the fields return uninitialized values
min_vis_mz = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
max_vis_mz = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 700.0
println(" Detected Dynamic Min m/z Limit: ", round(min_vis_mz, digits=2))
println(" Detected Dynamic Max m/z Limit: ", round(max_vis_mz, digits=2))
# 3. Configure Base Plot Layer with Dynamic X-limits
p = plot(mzs_avg, ints_avg, p = plot(mzs_avg, ints_avg,
linecolor = :darkgray, linecolor = :lightgray, # Light base so cluster sticks pop out visually
linewidth = 0.8, linewidth = 0.7,
label = "Average Spectrum (Reference)", label = "Average Spectrum (Reference)",
xlabel = "m/z", xlabel = "m/z",
ylabel = "Relative Intensity", ylabel = "Relative Intensity",
title = "Cluster Mapping on Isotopic Pattern", title = "Cluster Mapping on Isotopic Pattern",
size = (1200, 600), size = (1200, 600),
legend = :outerright, legend = :outerright,
grid = false, # Clean article style grid = false,
framestyle = :box, # Full frame framestyle = :box,
xlims = (min_vis_mz, max_vis_mz), # Dynamically locks view strictly to valid mass range
left_margin = 15mm, left_margin = 15mm,
bottom_margin = 15mm bottom_margin = 15mm
) )
# 4. Distinctive color palette # 4. Use the exact qualitative 10-color palette seen in your image
cluster_colors = palette(:tab10) cluster_colors = palette(:tab10)
# 5. Color specific peaks (Sticks) # 5. Map Cluster Vectors to Binned Positions
println("Highlighting chemical clusters...") println("Mapping chemical clusters onto binned coordinates...")
for cluster_id in sort(unique(clusters_df.cluster)) for cluster_id in sort(unique(clusters_df.cluster))
sub_df = filter(row -> row.cluster == cluster_id, clusters_df) sub_df = filter(row -> row.cluster == cluster_id, clusters_df)
label_ready = false label_ready = false
for target_mz in sub_df.mz for target_mz in sub_df.mz
# Find the index of the real peak in the average spectrum # Find the closest matching bin channel index in the 2000-bin array
idx = argmin(abs.(mzs_avg .- target_mz)) idx = argmin(abs.(mzs_avg .- target_mz))
# Tolerance to center the color on the real peak m = mzs_avg[idx]
if abs(mzs_avg[idx] - target_mz) < 0.1 i = ints_avg[idx]
m = mzs_avg[idx]
i = ints_avg[idx]
# Draw the cluster "stick" over the base spectrum # Draw the vertical peak highlighter over the base spectrum
plot!(p, [m, m], [0, i], plot!(p, [m, m], [0, i],
linecolor = cluster_colors[cluster_id + 1], linecolor = cluster_colors[cluster_id + 1],
linewidth = 1.2, linewidth = 1.2,
alpha = 1.0, # Fully opaque to stand out alpha = 0.9,
label = label_ready ? "" : "Cluster $cluster_id" label = label_ready ? "" : "Cluster $cluster_id"
) )
label_ready = true label_ready = true
end
end end
end end
# 6. Save with high resolution # 6. Save assets to shared folder mount
savefig("espectro_msi_paper_style.png") savefig("/app/espectro_msi_paper_style.png")
println("Final plot saved as 'espectro_msi_paper_style.png'") println("Saved publication-ready plot: /app/espectro_msi_paper_style.png")
savefig("espectro_msi_clusters_julia.png") savefig("/app/espectro_msi_clusters_julia.png")
println("Plot saved as 'espectro_msi_clusters_julia.png'") println("Saved backup copy: /app/espectro_msi_clusters_julia.png")
+68 -48
View File
@@ -1,15 +1,14 @@
# BRIDGE SCRIPT: Connects JuliaMSI framework to the CNN Preprocessing pipeline. # BRIDGE SCRIPT: Connects JuliaMSI framework to the CNN Preprocessing pipeline.
# This script is designed to run within the Docker container. # VERSION (V3): Relying directly on precomputed analytics and multiple mz slices for max throughtput
# Includes Benchmarking and Memory Profiling.
using Pkg using Pkg
juliamsi_path = "/opt/JuliaMSI" juliamsi_path = "/app/JuliaMSI"
push!(LOAD_PATH, juliamsi_path) push!(LOAD_PATH, joinpath(juliamsi_path, "src"))
# Load JuliaMSI core files directly as per documentation # Load JuliaMSI core
include(joinpath(juliamsi_path, "src", "julia_mzML_imzML.jl")) include(joinpath(juliamsi_path, "src", "MSI_src.jl"))
include(joinpath(juliamsi_path, "src", "mask.jl"))
using .MSI_src
using Statistics, Images, Interpolations, BenchmarkTools using Statistics, Images, Interpolations, BenchmarkTools
# CONFIGURATION # CONFIGURATION
@@ -17,59 +16,80 @@ data_path = "/app/data/Leaf.imzML"
mask_path = "/app/data/region_of_interest.png" mask_path = "/app/data/region_of_interest.png"
output_folder = "/app/datos_para_ai" output_folder = "/app/datos_para_ai"
img_size = (224, 224) img_size = (224, 224)
tolerance = 0.05
mkpath(output_folder) mkpath(output_folder)
println("--- JULIA PREPROCESSING BENCHMARK ---") println("--- JULIA BATCH ENGINE ---")
println("Dataset: ", basename(data_path))
if isfile(data_path)
println("File Size: ", round(filesize(data_path) / 1024^2, digits=2), " MB")
end
function run_preprocessing() function run_production_pipeline()
# 1. LOAD DATA # 1. LOAD DATA
println("Step 1: Ingesting MSI Data...") println("Step 1: Ingesting Data...")
# OpenMSIData: Core ingestion function from the JuliaMSI framework.
# Citation: Sierra-Álvarez et al. (2025).
data = OpenMSIData(data_path) data = OpenMSIData(data_path)
# 2. EXTRACT AVERAGE SPECTRUM (Inside Mask/ROI) # 2. RUN FRAMEWORK ANALYTICS
println("Step 2: Calculating ROI Average Spectrum...") println("Step 2: Checking Dataset Precomputed Boundaries...")
mzs, avg_ints = get_average_spectrum(data, mask_path=mask_path) # This matches the framework's internal logic to safely discover the true boundaries.
# It populates global_min_mz and global_max_mz by reading the binary headers properly.
MSI_src.precompute_analytics(data)
# 3. EXTRACT AVERAGE SPECTRUM
println("Step 3: Calculating ROI Average Spectrum...")
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path)
println(" True Dataset Min m/z: ", round(minimum(mzs), digits=2))
println(" True Dataset Max m/z: ", round(maximum(mzs), digits=2))
# 4. PEAK PICKING USING TRUE SPECTRA LIMITS
# Identify relevant ion channels above a 2% intensity base peak threshold
threshold = maximum(avg_ints) * 0.02 threshold = maximum(avg_ints) * 0.02
peak_indices = findall(x -> x > threshold, avg_ints) peak_indices = findall(x -> x > threshold, avg_ints)
println("Found $(length(peak_indices)) significant ions.") min_vis_mz = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
max_vis_mz = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 1000.0
# 3. TRiq NORMALIZATION & RESIZING # Isolate targets that fall strictly within the standard CNN metabolic training window
println("Step 3: Exporting Normalized Ion Maps...") target_masses = Float64[]
for idx in peak_indices for idx in peak_indices
mz_val = mzs[idx] mz_val = mzs[idx]
if mz_val < 50.0 || mz_val > 700.0 continue end if mz_val >= min_vis_mz && mz_val <= max_vis_mz
push!(target_masses, mz_val)
# Extract slice: Using a ±0.05 Da window. end
# This tolerance is standard for low-resolution Ion Trap instruments (LCQ Fleet)
# to ensure the entire peak centroid and its isotopic distribution are captured.
raw_slice = get_mz_slice(data, mz_val, 0.05, mask_path=mask_path)
# TrIQ Normalization (Threshold Intensity Quantization)
# Optimized for resolving low-abundance features in the presence of hotspots.
# Citation: Rosas-Román et al. (2024).
vals = filter(x -> x > 0 && isfinite(x), raw_slice)
if isempty(vals) continue end
q = quantile(vals, 0.98)
q = q == 0 ? maximum(vals) : q
enhanced = clamp.(raw_slice ./ q, 0.0, 1.0)
# Resize for CNN
img_resized = imresize(enhanced, img_size)
# Save to intermediate folder
filename = "ion_$(round(mz_val, digits=2)).png"
save(joinpath(output_folder, filename), Gray.(img_resized))
end end
total_ions = length(target_masses)
println("Found $total_ions ions within training range ($(min_vis_mz) to $(max_vis_mz) m/z) above threshold.")
if total_ions == 0
println("Warning: No peaks met the criteria. Check your threshold or mask alignment.")
return
end
# 5. MULTI-CHANNEL BATCH EXTRACTION (Single pass over binary data)
println("Step 4: Multi-channel Batch Extraction (Optimized I/O)...")
slice_dict = MSI_src.get_multiple_mz_slices(data, target_masses, tolerance, mask_path=mask_path)
# 6. THREADED PROCESSING & EXPORT
println("Step 5: Threaded TrIQ Normalization & Resizing (Using $(Threads.nthreads()) threads)...")
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
exported_count = Threads.Atomic{Int}(0)
Threads.@threads for mz_val in target_masses
slice = get(slice_dict, mz_val, nothing)
if slice === nothing || all(iszero, slice) continue end
# Use Framework-Native TrIQ (Standard: 256 bins, 0.98 probability cutoff)
slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix)
# Resize cleanly to standard CNN dimensions
img_resized = imresize(slice_quant, img_size)
# Normalize 0-255 scaling back to 0.0-1.0 float mapping for Gray storage conversion
filename = "ion_$(round(mz_val, digits=2)).png"
save(joinpath(output_folder, filename), Gray.(img_resized ./ 255.0))
Threads.atomic_add!(exported_count, 1)
end
println("\nSuccess: $(exported_count[]) target image maps exported to $output_folder.")
end end
# Execution with Benchmarking @time run_production_pipeline()
@time run_preprocessing()
println("--- BENCHMARK COMPLETE ---")
+33 -44
View File
@@ -1,53 +1,42 @@
# This script is part of the hybrid Julia-Python workflow for MSI analysis. using MSI_src
# It uses JuliaMSI for high-performance data ingestion and TrIQ normalization.
# 1. SETUP ENVIRONMENT
# We add the JuliaMSI directory to the load path
using Pkg
juliamsi_path = joinpath(@__DIR__, "..", "JuliaMSI")
if isdir(juliamsi_path)
push!(LOAD_PATH, juliamsi_path)
end
using Statistics, Images, Interpolations using Statistics, Images, Interpolations
# 2. CONFIGURATION # 1. Configuration
data_path = joinpath(@__DIR__, "..", "data", "Leaf.imzML") data_path = "Leaf.imzML"
mask_path = joinpath(@__DIR__, "..", "data", "region_of_interest.png") mask_path = "region_of_interest.png"
output_folder = joinpath(@__DIR__, "..", "datos_para_ai") output_folder = "datos_para_ai"
img_size = (224, 224) img_size = (224, 224) # Standard size for CNN
mkpath(output_folder) mkpath(output_folder)
# 3. DATA LOADING (Using JuliaMSI core logic) # 2. Data loading
# Note: In a headless Docker environment, we would use: data = OpenMSIData(data_path)
# julia -J /app/JuliaMSI/sys_msi_headless.so scripts_julia/prepare_data_simclr.jl
try
# JuliaMSI core loading (based on documentation analysis)
# We include the core logic directly if the module isn't exported as a package
include(joinpath(juliamsi_path, "src", "julia_mzML_imzML.jl"))
include(joinpath(juliamsi_path, "src", "mask.jl"))
catch e
println("Warning: Could not find JuliaMSI core files. Falling back to local MSI_src if available.")
# Fallback to user's existing MSI_src if present in LOAD_PATH
end
# Placeholder for OpenMSIData if not loaded via include # 3. Get important peaks (you can use your previous logic)
if !@isdefined(OpenMSIData) mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path)
# Fallback to basic imzML loading logic if framework is missing threshold = maximum(avg_ints) * 0.02
println("Using basic loading logic...") peak_indices = findall(x -> x > threshold, avg_ints)
end
# 4. PROCESSING LOGIC println("Exporting $(length(peak_indices)) ions...")
# (The user's original logic using OpenMSIData and TrIQ)
# This assumes OpenMSIData returns a structure compatible with the framework
function process_msi()
println("Loading data: $data_path")
# data = OpenMSIData(data_path)
# ... (Actual implementation would call JuliaMSI functions) for idx in peak_indices
println("Preprocessing step would run here using JuliaMSI backend.") mz_val = mzs[idx]
end if mz_val < 50.0 || mz_val > 700.0 continue end
if abspath(PROGRAM_FILE) == @__FILE__ # A. Extract slice (raw, no plots)
process_msi() raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=mask_path)
# B. TrIQ Normalization (as in your script)
vals = filter(x -> x > 0 && isfinite(x), raw_slice)
if isempty(vals) continue end
q = quantile(vals, 0.98)
q = q == 0 ? maximum(vals) : q
enhanced = clamp.(raw_slice ./ q, 0.0, 1.0)
# C. Rescale to 224x224 (Crucial for CNN)
# We use imresize from Images.jl
img_resized = imresize(enhanced, img_size)
# D. Save as raw PNG (Grayscale, no axes)
filename = "ion_$(round(mz_val, digits=2)).png"
save(joinpath(output_folder, filename), Gray.(img_resized))
end end
+33 -17
View File
@@ -28,7 +28,7 @@ set_seed(42)
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai") IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth") MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
BATCH_SIZE = 32 BATCH_SIZE = 8 # Reduced from 16 to prevent OOM on low-memory GPUs
# Epochs: 50 is sufficient for convergence on normalized ion maps. # Epochs: 50 is sufficient for convergence on normalized ion maps.
# Further training leads to minor overfitting to background noise. # Further training leads to minor overfitting to background noise.
EPOCHS = 50 EPOCHS = 50
@@ -38,6 +38,11 @@ LEARNING_RATE = 0.0003
TEMPERATURE = 0.5 TEMPERATURE = 0.5
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Optimization for fragmented CUDA memory
if DEVICE.type == 'cuda':
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
torch.cuda.empty_cache()
# 2. AUMENTACIONES ESPECÍFICAS DE MSI (Basado en Hu et al. 2022) # 2. AUMENTACIONES ESPECÍFICAS DE MSI (Basado en Hu et al. 2022)
class MSIAugmentations: class MSIAugmentations:
def __init__(self, size=224): def __init__(self, size=224):
@@ -125,23 +130,34 @@ if __name__ == "__main__":
start_time = time.time() start_time = time.time()
for epoch in range(EPOCHS): try:
epoch_start = time.time() for epoch in range(EPOCHS):
total_loss = 0 epoch_start = time.time()
for (img1, img2), names in loader: total_loss = 0
img1, img2 = img1.to(DEVICE), img2.to(DEVICE) for (img1, img2), names in loader:
optimizer.zero_grad() img1, img2 = img1.to(DEVICE), img2.to(DEVICE)
_, z1 = model(img1) optimizer.zero_grad()
_, z2 = model(img2) _, z1 = model(img1)
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE) _, z2 = model(img2)
loss.backward() loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE)
optimizer.step() loss.backward()
total_loss += loss.item() optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / len(loader) avg_loss = total_loss / len(loader)
epoch_end = time.time() epoch_end = time.time()
curr_mem = process.memory_info().rss / 1024 / 1024 # MB curr_mem = process.memory_info().rss / 1024 / 1024 # MB
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}, Time: {epoch_end-epoch_start:.2f}s, RAM: {curr_mem:.2f} MB") print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}, Time: {epoch_end-epoch_start:.2f}s, RAM: {curr_mem:.2f} MB")
except RuntimeError as e:
if "shared memory" in str(e).lower() or "shm" in str(e).lower() or "no space left on device" in str(e).lower():
print("\n" + "!"*60)
print("[ERROR] Shared memory (shm) exhaustion detected.")
print("This is a common issue when running PyTorch in Docker containers.")
print("\nFIX:")
print("Add '--shm-size=2gb' (or more) to your 'docker run' command.")
print("Example: docker run -it --rm --shm-size=2gb --gpus all ...")
print("!"*60 + "\n")
raise e
total_time = time.time() - start_time total_time = time.time() - start_time
peak_mem = process.memory_info().rss / 1024 / 1024 # MB peak_mem = process.memory_info().rss / 1024 / 1024 # MB
+116
View File
@@ -0,0 +1,116 @@
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
from PIL import Image
import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE
import pandas as pd
import matplotlib.pyplot as plt
# 1. CONFIGURACIÓN
IMG_DIR = "datos_para_ai"
OUTPUT_DIR = "pruebas_clusters"
N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
os.makedirs(OUTPUT_DIR, exist_ok=True)
# 2. CARGAR MODELO PRE-ENTRENADO (Directo de PyTorch)
def get_pretrained_extractor():
# Usamos los pesos por defecto de ImageNet
model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
model.classifier = nn.Identity() # Quitamos la capa de clasificación
model.to(DEVICE)
model.eval()
return model
# 3. DATASET CON NORMALIZACIÓN ESTÁNDAR
class MSIDatasetDirect(Dataset):
def __init__(self, img_dir):
self.img_dir = img_dir
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
# Normalización obligatoria para modelos pre-entrenados
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def __len__(self):
return len(self.img_names)
def __getitem__(self, idx):
img_path = os.path.join(self.img_dir, self.img_names[idx])
image = Image.open(img_path).convert("RGB")
return self.transform(image), self.img_names[idx]
if __name__ == "__main__":
print(f"Extrayendo características con red pre-entrenada en {DEVICE}...")
model = get_pretrained_extractor()
dataset = MSIDatasetDirect(IMG_DIR)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
features = []
ion_names = []
with torch.no_grad():
for img, name in loader:
img = img.to(DEVICE)
feat = model(img)
# Aplanar el vector de características (1280 dimensiones para EffNet-B0)
features.append(feat.cpu().numpy().flatten())
ion_names.append(name[0])
features = np.array(features)
print(f"Características extraídas: {features.shape}")
# 4. REDUCCIÓN DE DIMENSIONALIDAD (PCA)
# Esto ayuda a que el clustering no se pierda en dimensiones irrelevantes
print("Reduciendo ruido con PCA...")
features_scaled = StandardScaler().fit_transform(features)
pca = PCA(n_components=0.95) # Mantenemos el 95% de la varianza
features_pca = pca.fit_transform(features_scaled)
print(f"Dimensiones tras PCA: {features_pca.shape[1]}")
# 5. CLUSTERING K-MEANS
print(f"Agrupando en {N_CLUSTERS} clusters...")
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
labels = km.fit_predict(features_pca)
# 6. VISUALIZACIÓN (t-SNE)
print("Generando visualización t-SNE para verificar consistencia...")
tsne = TSNE(n_components=2, random_state=42)
features_tsne = tsne.fit_transform(features_pca)
plt.figure(figsize=(10, 8))
scatter = plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=labels, cmap='tab10', alpha=0.7)
plt.colorbar(scatter, ticks=range(N_CLUSTERS), label='Cluster ID')
plt.title(f"Visualización de Clusters (K={N_CLUSTERS}) - Directo")
plt.xlabel("t-SNE 1")
plt.ylabel("t-SNE 2")
plt.grid(True, linestyle='--', alpha=0.5)
plt.savefig(os.path.join(OUTPUT_DIR, "msi_clusters_direct_plot.png"))
print(f"Gráfico de consistencia guardado en '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
# 7. GUARDAR Y REPORTAR
df = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
df['mz'] = df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_results.csv"), index=False)
# Crear un resumen de cuántos iones hay por cluster
print("\nResumen de Clusters (Consistente con el CSV y el Gráfico):")
counts = df['cluster'].value_counts().sort_index()
print(counts)
# Guardar también el resumen para evitar confusiones con otros archivos
summary_df = counts.reset_index()
summary_df.columns = ['Cluster_ID', 'Ion_Count']
summary_df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_summary.csv"), index=False)
print(f"\nResultados guardados en '{OUTPUT_DIR}/msi_clusters_direct_results.csv' y '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
print(f"Usa '{OUTPUT_DIR}/msi_clusters_direct_plot.png' para validar visualmente los puntos.")
+2 -2
View File
@@ -147,11 +147,11 @@ def isotope_validation(X_features, mzs):
isotope_dist = [] isotope_dist = []
random_dist = [] random_dist = []
# Find isotopic pairs (M+H and M+H+1, diff ~ 1.0033) # Find isotopic pairs (Adjusted to allow for binned channel drift)
for i in range(len(mzs)): for i in range(len(mzs)):
for j in range(i + 1, len(mzs)): for j in range(i + 1, len(mzs)):
diff = abs(mzs[i] - mzs[j]) diff = abs(mzs[i] - mzs[j])
if 1.00 < diff < 1.01: # Heuristic for C13 isotope if 0.95 <= diff <= 1.05: # Accommodates binned spacing variations
dist = np.linalg.norm(X_norm[i] - X_norm[j]) dist = np.linalg.norm(X_norm[i] - X_norm[j])
isotope_dist.append(dist) isotope_dist.append(dist)
+1
View File
@@ -9,6 +9,7 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CSV_OPTIONS = [ CSV_OPTIONS = [
os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"), os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"),
os.path.join(BASE_DIR, "..", "msi_clusters_direct_results.csv"), os.path.join(BASE_DIR, "..", "msi_clusters_direct_results.csv"),
os.path.join(BASE_DIR, "..", "pruebas_clusters", "msi_clusters_direct_results.csv"),
os.path.join(BASE_DIR, "..", "msi_tsne_results.csv") os.path.join(BASE_DIR, "..", "msi_tsne_results.csv")
] ]