diff --git a/.gitignore b/.gitignore index 9427ac9..e90991c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ -MSI_julia-python_mapping.md data/Leaf.imzML data/Leaf.ibd -JuliaMSI/ \ No newline at end of file +data/Leaf.imzML.cache +JuliaMSI/ +environment/Manifest.toml +datos_para_ai/* \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index cbf76c7..44700e6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,6 @@ FROM nvidia/cuda:12.4.1-runtime-ubuntu22.04 ENV DEBIAN_FRONTEND=noninteractive # 1. Install System Dependencies -# Includes Julia requirements, Python, and Headless Display libs for GLMakie RUN apt-get update && apt-get install -y \ wget \ curl \ @@ -18,7 +17,6 @@ RUN apt-get update && apt-get install -y \ libpng-dev \ libjpeg-dev \ libfreetype6-dev \ - # Display dependencies for GLMakie/GLFW (fixes "X11: The DISPLAY environment variable is missing") xvfb \ libgl1-mesa-glx \ 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 # 4. Integrate JuliaMSI Framework -# We use the local JuliaMSI folder COPY JuliaMSI /opt/JuliaMSI WORKDIR /opt/JuliaMSI -# Set DISPLAY for xvfb 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()' # 5. Setup Project Root and Environments WORKDIR /app 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 -# 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()' +# Register JuliaMSI explicitly into the runtime environment project +RUN julia --project=environment -e 'using Pkg; Pkg.develop(path="/opt/JuliaMSI")' + # 6. Copy Application Files COPY . /app # 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 DISPLAY=:99 LABEL maintainer="MSI Hybrid Workflow Team" LABEL description="CUDA + Julia 1.11.3 + JuliaMSI Framework" -# Default to interactive bash -CMD ["/bin/bash"] +CMD ["/bin/bash"] \ No newline at end of file diff --git a/README.md b/README.md index 1e9c7da..295e3fd 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ docker run -it --rm -v $(pwd):/app msi-hybrid-workflow ### Running the Container (GPU/CUDA Mode) ```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 @@ -42,15 +42,21 @@ docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow ### 1. Preprocessing (Julia) 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 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:** ```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 ``` @@ -59,7 +65,12 @@ Train the SimCLR encoder to extract morphological features using CUDA. **Run CNN Training (SimCLR):** ```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 ``` *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 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:** ```bash 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:** ```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 ``` @@ -84,28 +101,19 @@ Generate the final galleries and t-SNE maps. **Generate t-SNE Maps:** ```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 ``` **Create Cluster Galleries:** ```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 ``` -## 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. - -## 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) +## Citation & Acknowledgments +This implementation is based on the methodology proposed by: +> 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) ## License This project is licensed under the **MIT License**. diff --git a/documentation.md b/documentation.md index 3c22f5f..6b5acc9 100644 --- a/documentation.md +++ b/documentation.md @@ -61,3 +61,13 @@ We implemented **Additive Gaussian Noise ($\sigma=0.01$)**. This is critical for ### 4.4 Dimensionality Reduction PCA was used to reduce the 1280-dim (EfficientNet) or 128-dim (Projector) features to **50 components** before k-means. This heuristic stabilizes clustering by removing noise and redundant dimensions. * *Citation:* Jolliffe (2002). + + +## Benchmarking & Hardware Realism +The pipeline is optimized for efficiency on consumer-grade hardware. +- **Julia Stage**: Uses `BenchmarkTools.jl` to profile binary parsing. +- **Python Stage**: Uses `psutil` and `CUDA` monitoring to track hardware overhead. +- **Determinism**: All stochastic steps are locked with `seed=42`. + +## Julia-Python Bridge Details +The "two-language problem" is solved by an intermediate file-system bridge. Julia performs binary MSI parsing and **Threshold Intensity Quantization (TrIQ)**. The resulting data is saved as high-contrast 224x224 grayscale PNG images, allowing the Python PyTorch pipeline to consume it efficiently. diff --git a/environment/Project.toml b/environment/Project.toml index 2d77c74..ecae987 100644 --- a/environment/Project.toml +++ b/environment/Project.toml @@ -1,7 +1,49 @@ [deps] +Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697" +Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" 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" +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" 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" -Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" \ No newline at end of file +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" +StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" +StipplePlotly = "ec984513-233d-481d-95b0-a3b58b97af2b" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" +UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" diff --git a/figures/isotope_validation_plot.png b/figures/isotope_validation_plot.png new file mode 100644 index 0000000..5af45ce Binary files /dev/null and b/figures/isotope_validation_plot.png differ diff --git a/scripts_julia/graph_cluster_spectra.jl b/scripts_julia/graph_cluster_spectra.jl index 6e9d7a7..a79766b 100644 --- a/scripts_julia/graph_cluster_spectra.jl +++ b/scripts_julia/graph_cluster_spectra.jl @@ -1,70 +1,95 @@ -using MSI_src -using CSV, DataFrames +using Pkg +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 + +# 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 Plots.Measures -# 1. Data loading -data_path = "Leaf.imzML" -mask_path = "region_of_interest.png" -clusters_path = "msi_clusters_results.csv" +# 1. PATH CONFIGURATIONS +data_path = "/app/data/Leaf.imzML" +mask_path = "/app/data/region_of_interest.png" +clusters_path = "/app/msi_clusters_results.csv" -println("Loading data...") +println("Loading data arrays...") data = OpenMSIData(data_path) 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) -# 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, - linecolor = :darkgray, - linewidth = 0.8, + linecolor = :lightgray, # Light base so cluster sticks pop out visually + linewidth = 0.7, label = "Average Spectrum (Reference)", xlabel = "m/z", ylabel = "Relative Intensity", title = "Cluster Mapping on Isotopic Pattern", size = (1200, 600), legend = :outerright, - grid = false, # Clean article style - framestyle = :box, # Full frame + grid = false, + framestyle = :box, + xlims = (min_vis_mz, max_vis_mz), # Dynamically locks view strictly to valid mass range left_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) -# 5. Color specific peaks (Sticks) -println("Highlighting chemical clusters...") +# 5. Map Cluster Vectors to Binned Positions +println("Mapping chemical clusters onto binned coordinates...") for cluster_id in sort(unique(clusters_df.cluster)) sub_df = filter(row -> row.cluster == cluster_id, clusters_df) - label_ready = false 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)) - # Tolerance to center the color on the real peak - if abs(mzs_avg[idx] - target_mz) < 0.1 - m = mzs_avg[idx] - i = ints_avg[idx] - - # Draw the cluster "stick" over the base spectrum - plot!(p, [m, m], [0, i], - linecolor = cluster_colors[cluster_id + 1], - linewidth = 1.2, - alpha = 1.0, # Fully opaque to stand out - label = label_ready ? "" : "Cluster $cluster_id" - ) - label_ready = true - end + m = mzs_avg[idx] + i = ints_avg[idx] + + # Draw the vertical peak highlighter over the base spectrum + plot!(p, [m, m], [0, i], + linecolor = cluster_colors[cluster_id + 1], + linewidth = 1.2, + alpha = 0.9, + label = label_ready ? "" : "Cluster $cluster_id" + ) + label_ready = true end end -# 6. Save with high resolution -savefig("espectro_msi_paper_style.png") -println("Final plot saved as 'espectro_msi_paper_style.png'") -savefig("espectro_msi_clusters_julia.png") -println("Plot saved as 'espectro_msi_clusters_julia.png'") +# 6. Save assets to shared folder mount +savefig("/app/espectro_msi_paper_style.png") +println("Saved publication-ready plot: /app/espectro_msi_paper_style.png") +savefig("/app/espectro_msi_clusters_julia.png") +println("Saved backup copy: /app/espectro_msi_clusters_julia.png") \ No newline at end of file diff --git a/scripts_julia/julia_msi_bridge.jl b/scripts_julia/julia_msi_bridge.jl index 08db54d..0600e42 100644 --- a/scripts_julia/julia_msi_bridge.jl +++ b/scripts_julia/julia_msi_bridge.jl @@ -1,15 +1,14 @@ # BRIDGE SCRIPT: Connects JuliaMSI framework to the CNN Preprocessing pipeline. -# This script is designed to run within the Docker container. -# Includes Benchmarking and Memory Profiling. +# VERSION (V3): Relying directly on precomputed analytics and multiple mz slices for max throughtput using Pkg -juliamsi_path = "/opt/JuliaMSI" -push!(LOAD_PATH, juliamsi_path) +juliamsi_path = "/app/JuliaMSI" +push!(LOAD_PATH, joinpath(juliamsi_path, "src")) -# Load JuliaMSI core files directly as per documentation -include(joinpath(juliamsi_path, "src", "julia_mzML_imzML.jl")) -include(joinpath(juliamsi_path, "src", "mask.jl")) +# Load JuliaMSI core +include(joinpath(juliamsi_path, "src", "MSI_src.jl")) +using .MSI_src using Statistics, Images, Interpolations, BenchmarkTools # CONFIGURATION @@ -17,59 +16,80 @@ data_path = "/app/data/Leaf.imzML" mask_path = "/app/data/region_of_interest.png" output_folder = "/app/datos_para_ai" img_size = (224, 224) +tolerance = 0.05 mkpath(output_folder) -println("--- JULIA PREPROCESSING BENCHMARK ---") -println("Dataset: ", basename(data_path)) -if isfile(data_path) - println("File Size: ", round(filesize(data_path) / 1024^2, digits=2), " MB") -end +println("--- JULIA BATCH ENGINE ---") -function run_preprocessing() +function run_production_pipeline() # 1. LOAD DATA - println("Step 1: Ingesting MSI Data...") - # OpenMSIData: Core ingestion function from the JuliaMSI framework. - # Citation: Sierra-Álvarez et al. (2025). + println("Step 1: Ingesting Data...") data = OpenMSIData(data_path) + + # 2. RUN FRAMEWORK ANALYTICS + println("Step 2: Checking Dataset Precomputed Boundaries...") + # 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)) - # 2. EXTRACT AVERAGE SPECTRUM (Inside Mask/ROI) - println("Step 2: Calculating ROI Average Spectrum...") - mzs, avg_ints = get_average_spectrum(data, mask_path=mask_path) + # 4. PEAK PICKING USING TRUE SPECTRA LIMITS + # Identify relevant ion channels above a 2% intensity base peak threshold threshold = maximum(avg_ints) * 0.02 peak_indices = findall(x -> x > threshold, avg_ints) - println("Found $(length(peak_indices)) significant ions.") - - # 3. TRiq NORMALIZATION & RESIZING - println("Step 3: Exporting Normalized Ion Maps...") + 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 + + # Isolate targets that fall strictly within the standard CNN metabolic training window + target_masses = Float64[] for idx in peak_indices mz_val = mzs[idx] - if mz_val < 50.0 || mz_val > 700.0 continue end - - # Extract slice: Using a ±0.05 Da window. - # 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)) + if mz_val >= min_vis_mz && mz_val <= max_vis_mz + push!(target_masses, mz_val) + 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 -# Execution with Benchmarking -@time run_preprocessing() - -println("--- BENCHMARK COMPLETE ---") +@time run_production_pipeline() diff --git a/scripts_julia/prepare_data_simclr.jl b/scripts_julia/prepare_data_simclr.jl index b7dc1af..68f9151 100644 --- a/scripts_julia/prepare_data_simclr.jl +++ b/scripts_julia/prepare_data_simclr.jl @@ -1,53 +1,42 @@ -# This script is part of the hybrid Julia-Python workflow for MSI analysis. -# 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 MSI_src using Statistics, Images, Interpolations -# 2. CONFIGURATION -data_path = joinpath(@__DIR__, "..", "data", "Leaf.imzML") -mask_path = joinpath(@__DIR__, "..", "data", "region_of_interest.png") -output_folder = joinpath(@__DIR__, "..", "datos_para_ai") -img_size = (224, 224) +# 1. Configuration +data_path = "Leaf.imzML" +mask_path = "region_of_interest.png" +output_folder = "datos_para_ai" +img_size = (224, 224) # Standard size for CNN mkpath(output_folder) -# 3. DATA LOADING (Using JuliaMSI core logic) -# Note: In a headless Docker environment, we would use: -# 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 +# 2. Data loading +data = OpenMSIData(data_path) -# Placeholder for OpenMSIData if not loaded via include -if !@isdefined(OpenMSIData) - # Fallback to basic imzML loading logic if framework is missing - println("Using basic loading logic...") -end +# 3. Get important peaks (you can use your previous logic) +mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path) +threshold = maximum(avg_ints) * 0.02 +peak_indices = findall(x -> x > threshold, avg_ints) -# 4. PROCESSING LOGIC -# (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) +println("Exporting $(length(peak_indices)) ions...") + +for idx in peak_indices + mz_val = mzs[idx] + if mz_val < 50.0 || mz_val > 700.0 continue end + + # A. Extract slice (raw, no plots) + raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=mask_path) - # ... (Actual implementation would call JuliaMSI functions) - println("Preprocessing step would run here using JuliaMSI backend.") -end + # 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) -if abspath(PROGRAM_FILE) == @__FILE__ - process_msi() + # 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 diff --git a/scripts_python/CNN_proof_1.py b/scripts_python/CNN_proof_1.py index 28ee757..c1528ff 100644 --- a/scripts_python/CNN_proof_1.py +++ b/scripts_python/CNN_proof_1.py @@ -28,7 +28,7 @@ set_seed(42) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai") 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. # Further training leads to minor overfitting to background noise. EPOCHS = 50 @@ -38,6 +38,11 @@ LEARNING_RATE = 0.0003 TEMPERATURE = 0.5 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) class MSIAugmentations: def __init__(self, size=224): @@ -125,23 +130,34 @@ if __name__ == "__main__": start_time = time.time() - for epoch in range(EPOCHS): - epoch_start = time.time() - total_loss = 0 - for (img1, img2), names in loader: - img1, img2 = img1.to(DEVICE), img2.to(DEVICE) - optimizer.zero_grad() - _, z1 = model(img1) - _, z2 = model(img2) - loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE) - loss.backward() - optimizer.step() - total_loss += loss.item() - - avg_loss = total_loss / len(loader) - epoch_end = time.time() - 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") + try: + for epoch in range(EPOCHS): + epoch_start = time.time() + total_loss = 0 + for (img1, img2), names in loader: + img1, img2 = img1.to(DEVICE), img2.to(DEVICE) + optimizer.zero_grad() + _, z1 = model(img1) + _, z2 = model(img2) + loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE) + loss.backward() + optimizer.step() + total_loss += loss.item() + + avg_loss = total_loss / len(loader) + epoch_end = time.time() + 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") + 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 peak_mem = process.memory_info().rss / 1024 / 1024 # MB diff --git a/scripts_python/cluster_msi_direct.py b/scripts_python/cluster_msi_direct.py new file mode 100644 index 0000000..93528ef --- /dev/null +++ b/scripts_python/cluster_msi_direct.py @@ -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.") diff --git a/scripts_python/quantitative_validation.py b/scripts_python/quantitative_validation.py index 6c2d6be..227b938 100644 --- a/scripts_python/quantitative_validation.py +++ b/scripts_python/quantitative_validation.py @@ -147,11 +147,11 @@ def isotope_validation(X_features, mzs): isotope_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 j in range(i + 1, len(mzs)): 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]) isotope_dist.append(dist) diff --git a/scripts_python/visualize_clusters.py b/scripts_python/visualize_clusters.py index 1270a0d..f142777 100644 --- a/scripts_python/visualize_clusters.py +++ b/scripts_python/visualize_clusters.py @@ -9,6 +9,7 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__)) CSV_OPTIONS = [ os.path.join(BASE_DIR, "..", "msi_clusters_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") ]