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
+62 -37
View File
@@ -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")
+69 -49
View File
@@ -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()
+33 -44
View File
@@ -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