Subir archivos a "scripts_julia"

This commit is contained in:
2026-08-18 07:59:23 +02:00
parent 7e5dd427b7
commit eb95969da2
3 changed files with 452 additions and 108 deletions
+22 -39
View File
@@ -1,52 +1,39 @@
using Pkg using Pkg
Pkg.activate("/app/environment") script_dir = @__DIR__
project_root = joinpath(script_dir, "..", "..")
Pkg.activate(joinpath(project_root, "environment"))
# Handle dynamic environment fallback ENV["GKSwstype"] = "100"
if !haskey(Pkg.project().dependencies, "Plots")
Pkg.add("Plots")
end
ENV["GKSwstype"] = "100" # Headless rendering for Docker container
using Plots using Plots
push!(LOAD_PATH, joinpath(project_root, "src"))
# Load framework core dependencies smoothly include(joinpath(project_root, "src", "MSI_src.jl"))
juliamsi_path = "/app/JuliaMSI"
push!(LOAD_PATH, joinpath(juliamsi_path, "src"))
include(joinpath(juliamsi_path, "src", "MSI_src.jl"))
using .MSI_src using .MSI_src
using CSV, DataFrames using CSV, DataFrames
using Statistics using Statistics
using Plots.Measures using Plots.Measures
# 1. PATH CONFIGURATIONS data_path = joinpath(project_root, "data", "Leaf.imzML")
data_path = "/app/data/Leaf.imzML" mask_path = joinpath(project_root, "data", "region_of_interest.png")
mask_path = "/app/data/region_of_interest.png" clusters_path = joinpath(project_root, "outputs", "msi_clusters_results.csv")
clusters_path = "/app/msi_clusters_results.csv"
println("Loading data arrays...") 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. RUN FRAMEWORK ANALYTICS TO DISCOVER PHYSICAL BOUNDARIES
println("Syncing Dataset Precomputed Boundaries...") println("Syncing Dataset Precomputed Boundaries...")
MSI_src.precompute_analytics(data) 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)
# --- 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 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 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 Min m/z Limit: ", round(min_vis_mz, digits=2))
println(" Detected Dynamic Max m/z Limit: ", round(max_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 = :lightgray,
linecolor = :lightgray, # Light base so cluster sticks pop out visually
linewidth = 0.7, linewidth = 0.7,
label = "Average Spectrum (Reference)", label = "Average Spectrum (Reference)",
xlabel = "m/z", xlabel = "m/z",
@@ -54,30 +41,26 @@ p = plot(mzs_avg, ints_avg,
title = "Cluster Mapping on Isotopic Pattern", title = "Cluster Mapping on Isotopic Pattern",
size = (1200, 600), size = (1200, 600),
legend = :outerright, legend = :outerright,
grid = false, grid = false,
framestyle = :box, framestyle = :box,
xlims = (min_vis_mz, max_vis_mz), # Dynamically locks view strictly to valid mass range xlims = (min_vis_mz, max_vis_mz),
left_margin = 15mm, left_margin = 15mm,
bottom_margin = 15mm bottom_margin = 15mm
) )
# 4. Use the exact qualitative 10-color palette seen in your image
cluster_colors = palette(:tab10) cluster_colors = palette(:tab10)
# 5. Map Cluster Vectors to Binned Positions
println("Mapping chemical clusters onto binned coordinates...") 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 closest matching bin channel index in the 2000-bin array
idx = argmin(abs.(mzs_avg .- target_mz)) idx = argmin(abs.(mzs_avg .- target_mz))
m = mzs_avg[idx] m = mzs_avg[idx]
i = ints_avg[idx] i = ints_avg[idx]
# 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,
@@ -88,8 +71,8 @@ for cluster_id in sort(unique(clusters_df.cluster))
end end
end end
# 6. Save assets to shared folder mount output_dir = joinpath(project_root, "outputs")
savefig("/app/espectro_msi_paper_style.png") savefig(joinpath(output_dir, "msi_spectra_plot.png"))
println("Saved publication-ready plot: /app/espectro_msi_paper_style.png") println("Saved publication-ready plot: outputs/msi_spectra_plot.png")
savefig("/app/espectro_msi_clusters_julia.png") savefig(joinpath(output_dir, "msi_spectra_clusters.png"))
println("Saved backup copy: /app/espectro_msi_clusters_julia.png") println("Saved backup copy: outputs/msi_spectra_clusters.png")
+231 -69
View File
@@ -1,71 +1,183 @@
# BRIDGE SCRIPT: Connects JuliaMSI framework to the CNN Preprocessing pipeline.
# VERSION (V3): Relying directly on precomputed analytics and multiple mz slices for max throughtput
using Pkg using Pkg
juliamsi_path = "/app/JuliaMSI" script_dir = @__DIR__
push!(LOAD_PATH, joinpath(juliamsi_path, "src")) project_root = joinpath(script_dir, "..", "..")
# Load JuliaMSI core Pkg.activate(joinpath(project_root, "environment"))
include(joinpath(juliamsi_path, "src", "MSI_src.jl"))
push!(LOAD_PATH, joinpath(project_root, "src"))
include(joinpath(project_root, "src", "MSI_src.jl"))
using .MSI_src using .MSI_src
using Statistics, Images, Interpolations, BenchmarkTools using Statistics, Images, Interpolations, BenchmarkTools
import julia_mzML_imzML
# CONFIGURATION data_dir = length(ARGS) >= 1 ? ARGS[1] : joinpath(project_root, "data")
data_path = "/app/data/Leaf.imzML" dataset_name = length(ARGS) >= 2 ? ARGS[2] : splitdir(data_dir)[2]
mask_path = "/app/data/region_of_interest.png"
output_folder = "/app/datos_para_ai" # Find first .imzML file
img_size = (256, 256) imzml_files = filter(f -> endswith(lowercase(f), ".imzml"), readdir(data_dir))
if isempty(imzml_files)
error("No .imzML file found in $data_dir")
end
data_path = joinpath(data_dir, imzml_files[1])
# Find ROI mask
mask_path = joinpath(data_dir, "region_of_interest.png")
if !isfile(mask_path)
alt_masks = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir))
mask_path = isempty(alt_masks) ? "" : joinpath(data_dir, alt_masks[1])
end
output_folder = joinpath(project_root, "outputs", "ion_images", dataset_name)
viridis_folder = joinpath(project_root, "outputs", "ion_images_viridis", dataset_name)
tolerance = 0.05 tolerance = 0.05
mkpath(output_folder) mkpath(output_folder)
mkpath(viridis_folder)
println("--- JULIA BATCH ENGINE: $dataset_name ---")
println("Data: $data_path")
println("Mask: $(isempty(mask_path) ? "none" : mask_path)")
println("Output (grayscale): $output_folder")
println("Output (viridis): $viridis_folder")
println("--- JULIA BATCH ENGINE ---") println("--- JULIA BATCH ENGINE ---")
# Apply Julia's native ViridisPalette (256-entry, 0xRRGGBB) to a 0..255 intensity map.
function apply_viridis(intensity_matrix::AbstractMatrix{Float32})
palette = julia_mzML_imzML.ViridisPalette
h, w = size(intensity_matrix)
rgb = Matrix{RGB{N0f8}}(undef, h, w)
@inbounds for j in 1:w, i in 1:h
v = intensity_matrix[i, j]
v = isfinite(v) ? v : 0.0f0
idx = clamp(round(Int, v) + 1, 1, 256)
c = palette[idx]
r = Float64((c >> 16) & 0xFF) / 255.0
g = Float64((c >> 8) & 0xFF) / 255.0
b = Float64(c & 0xFF) / 255.0
rgb[i, j] = RGB{N0f8}(r, g, b)
end
return rgb
end
function run_production_pipeline() function run_production_pipeline()
# 1. LOAD DATA
println("Step 1: Ingesting Data...") println("Step 1: Ingesting Data...")
data = OpenMSIData(data_path) data = OpenMSIData(data_path)
orig_height = data.image_dims[2] orig_height = data.image_dims[2]
orig_width = data.image_dims[1] orig_width = data.image_dims[1]
if orig_height < 256 || orig_width < 256 target_size = (256, 256)
if orig_height <= 256 && orig_width <= 256
final_img_size = (orig_height, orig_width) final_img_size = (orig_height, orig_width)
println(" [Notice] Original image is smaller than 256x256. Keeping original size: ", final_img_size) println(" [Notice] Original image is smaller than or equal to 256x256. Keeping original size: ", final_img_size)
else else
final_img_size = (256, 256) scale = min(256 / orig_height, 256 / orig_width)
println(" [Notice] Resizing down to target size: ", final_img_size) final_img_size = (max(1, round(Int, orig_height * scale)), max(1, round(Int, orig_width * scale)))
println(" [Notice] Resizing from ($orig_height, $orig_width) to $final_img_size")
end end
# 2. RUN FRAMEWORK ANALYTICS
println("Step 2: Checking Dataset Precomputed Boundaries...") 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) MSI_src.precompute_analytics(data)
# 3. EXTRACT AVERAGE SPECTRUM println("Step 3: Calculating Average Spectrum...")
println("Step 3: Calculating ROI Average Spectrum...") # MSI_BIN_AVG (Da) bin width: for high-resolution ToF datasets the per-pixel m/z
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path) # values are essentially unique doubles, so an exact-key average spectrum never
# accumulates signal across pixels and starves peak picking (e.g. Mouse_Liver got
# only 23 ions). Binning onto a fixed grid (as in the 3-way benchmark) fixes that.
bin_avg = get(ENV, "MSI_BIN_AVG", "")
if !isempty(bin_avg)
bin_step = parse(Float64, bin_avg)
lo = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
hi = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 1000.0
nb = max(1, Int(floor((hi - lo) / bin_step)) + 1)
mz_axis_bin = collect(lo .+ (0:nb-1) .* bin_step)
avg_int_bin = zeros(nb)
npx_bin = size(data.imzml_data, 2)
for i in 1:npx_bin
pm = data.imzml_data[3, i]
pi = data.imzml_data[4, i]
idx = floor.(Int, (pm .- lo) ./ bin_step) .+ 1
for j in eachindex(pm)
k = idx[j]
if k >= 1 && k <= nb
avg_int_bin[k] += pi[j]
end
end
end
mzs = mz_axis_bin
avg_ints = avg_int_bin
println(" Binned average spectrum: $bin_step Da grid over $(round(lo,digits=2))-$(round(hi,digits=2)) m/z ($nb channels)")
else
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path)
end
println(" True Dataset Min m/z: ", round(minimum(mzs), digits=2)) println(" True Dataset Min m/z: ", round(minimum(mzs), digits=2))
println(" True Dataset Max m/z: ", round(maximum(mzs), digits=2)) println(" True Dataset Max m/z: ", round(maximum(mzs), digits=2))
# 4. PEAK PICKING USING TRUE SPECTRA LIMITS println("Step 4: Peak Picking...")
# 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)
min_vis_mz = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0 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 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 # Configurable peak-picking policy (via env vars so older datasets stay at 2%).
target_masses = Float64[] # MSI_PEAK_FRAC - threshold as fraction of base-peak max (default 0.02)
# MSI_PEAK_MIN_MZ_GAP - minimum m/z separation between distinct ions; 0 disables
# (e.g. 0.25 for high-dynamic-range ToF spectra)
peak_frac = get(ENV, "MSI_PEAK_FRAC", "0.02")
peak_frac = parse(Float64, peak_frac)
peak_gap = get(ENV, "MSI_PEAK_MIN_MZ_GAP", "0.0")
peak_gap = parse(Float64, peak_gap)
println(" Peak policy: threshold = $peak_frac of base max, min m/z separation = $peak_gap")
threshold = maximum(avg_ints) * peak_frac
peak_indices = findall(x -> x > threshold, avg_ints)
println(" Raw candidates above threshold: ", length(peak_indices))
in_range = Int[]
for idx in peak_indices for idx in peak_indices
mz_val = mzs[idx] mz_val = mzs[idx]
if mz_val >= min_vis_mz && mz_val <= max_vis_mz if mz_val >= min_vis_mz && mz_val <= max_vis_mz
push!(target_masses, mz_val) push!(in_range, idx)
end end
end end
if peak_gap > 0.0 && !isempty(in_range)
# Select local maxima first, then greedily take highest-intensity peaks
# that are at least `peak_gap` m/z apart (collapse adjacent samples of the
# same wide peak into a single ion). Used for dense/high-dynamic-range data.
in_range_set = Set(in_range)
local_max = Int[]
for i in in_range
above_lo = i == 1 || avg_ints[i] >= avg_ints[i - 1] || !(i - 1 in in_range_set)
above_hi = i == length(avg_ints) || avg_ints[i] >= avg_ints[i + 1] || !(i + 1 in in_range_set)
if above_lo && above_hi
push!(local_max, i)
end
end
if isempty(local_max)
local_max = copy(in_range)
end
order = sortperm(local_max, by = i -> avg_ints[i], rev = true)
selected = Int[]
for i in order
mz_i = mzs[local_max[i]]
keep = true
for j in selected
if abs(mz_i - mzs[j]) < peak_gap
keep = false
break
end
end
if keep
push!(selected, local_max[i])
end
end
in_range = selected
end
target_masses = sort([mzs[i] for i in in_range])
n_collapsed = length(peak_indices) - length(target_masses)
println(" Kept $(length(target_masses)) peaks after threshold/range/separation filtering ($n_collapsed collapsed).")
total_ions = length(target_masses) total_ions = length(target_masses)
println("Found $total_ions ions within training range ($(min_vis_mz) to $(max_vis_mz) m/z) above threshold.") println("Found $total_ions ions within training range ($(min_vis_mz) to $(max_vis_mz) m/z) above threshold.")
if total_ions == 0 if total_ions == 0
@@ -73,47 +185,97 @@ function run_production_pipeline()
return return
end end
# 5. MULTI-CHANNEL BATCH EXTRACTION (Single pass over binary data) println("Step 5+6: Batched Ion Extraction, TrIQ Normalization & 256x256 Zero-Padding...")
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 & Safe 256x256 Zero-Padding...")
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2])) mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
exported_count = Threads.Atomic{Int}(0) exported_count = Threads.Atomic{Int}(0)
# Fixed target dimensions for the CNN
target_size = (256, 256) target_size = (256, 256)
Threads.@threads for mz_val in target_masses # Memory-bounded batching: only `batch_size` full-resolution slices are resident
slice = get(slice_dict, mz_val, nothing) # in RAM at once, instead of materializing every ion image simultaneously. This
if slice === nothing || all(iszero, slice) continue end # keeps peak memory flat and independent of the total number of detected peaks
# (the cause of OOM kills on large datasets such as Mouse_Stomach).
batch_size = parse(Int, get(ENV, "MSI_ION_BATCH", "32"))
total_batches = cld(length(target_masses), batch_size)
# 1. Framework-Native TrIQ (0.0 to 255.0 Scaling) for (bi, start_idx) in enumerate(1:batch_size:length(target_masses))
slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix) end_idx = min(start_idx + batch_size - 1, length(target_masses))
batch = target_masses[start_idx:end_idx]
# 2. Allocate an empty 256x256 background matrix
padded_matrix = zeros(Float32, target_size) slices = Dict{Float64, Matrix{Float64}}()
for mz_val in batch
# 3. Compute structural centering offsets based on true resolution (161x106) slices[mz_val] = MSI_src.get_mz_slice(data, mz_val, tolerance; mask_path=mask_path)
h_orig, w_orig = size(slice_quant, 1), size(slice_quant, 2) end
offset_y = div(target_size[1] - h_orig, 2) + 1
offset_x = div(target_size[2] - w_orig, 2) + 1 Threads.@threads for mz_val in batch
slice = get(slices, mz_val, nothing)
# 4. Map the pristine, raw pixels directly into the center if slice === nothing continue end
padded_matrix[offset_y:offset_y+h_orig-1, offset_x:offset_x+w_orig-1] .= slice_quant # Blank/off-tissue pixels are stored as NaN in the imzML; TrIQ's
# GetOutlierThres(min(slice)) would then hit floor(Int, NaN) and abort.
# 5. Convert safely to 0.0 - 1.0 float mapping for Gray image export # Replace non-finite intensities with 0 before quantization.
normalized_gray = padded_matrix ./ 255.0 if !all(isfinite, slice)
slice = ifelse.(isfinite.(slice), slice, 0.0)
# 6. Save the unblurred, structurally perfect map end
filename = "ion_$(round(mz_val, digits=2)).png" if all(iszero, slice) continue end
save(joinpath(output_folder, filename), Gray.(normalized_gray))
try
Threads.atomic_add!(exported_count, 1) slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix)
slice_quant = permutedims(slice_quant)
h_orig, w_orig = size(slice_quant, 1), size(slice_quant, 2)
padded_matrix = if h_orig > 256 || w_orig > 256
scale = min(256 / h_orig, 256 / w_orig)
new_h = round(Int, h_orig * scale)
new_w = round(Int, w_orig * scale)
resized = imresize(slice_quant, (new_h, new_w))
m = zeros(Float32, target_size)
oh = div(256 - new_h, 2) + 1
ow = div(256 - new_w, 2) + 1
m[oh:oh+new_h-1, ow:ow+new_w-1] .= resized
m
else
m = zeros(Float32, target_size)
offset_y = div(256 - h_orig, 2) + 1
offset_x = div(256 - w_orig, 2) + 1
m[offset_y:offset_y+h_orig-1, offset_x:offset_x+w_orig-1] .= slice_quant
m
end
if !all(isfinite, padded_matrix)
padded_matrix = ifelse.(isfinite.(padded_matrix), padded_matrix, 0.0f0)
end
normalized_gray = padded_matrix ./ 255.0
filename = "ion_$(round(mz_val, digits=5)).png"
save(joinpath(output_folder, filename), Gray.(normalized_gray))
save(joinpath(viridis_folder, filename), apply_viridis(padded_matrix))
Threads.atomic_add!(exported_count, 1)
catch err
# A single ion whose intensity distribution degenerates (e.g. every
# nonzero pixel identical -> TrIQ bounds collapse) must not abort the
# whole extraction; log and skip it.
lo = minimum(slice); hi = maximum(slice)
println(" [skip] ion m/z $mz_val: $(sprint(showerror, err)) (slice min=$lo max=$hi nz=$(count(!iszero, slice)))")
dbg = get(ENV, "MSI_DUMP_FAILS", "")
if !isempty(dbg) && ispath(dbg)
fn = joinpath(dbg, "fail_$(round(mz_val, digits=3)).bin")
open(fn, "w") do f
write(f, size(slice, 1)); write(f, size(slice, 2)); write(f, slice)
end
end
end
end
empty!(slices)
GC.gc(false)
println(" batch $bi/$total_batches done (ions $start_idx..$end_idx of $(length(target_masses)); exported $(exported_count[]) so far)")
end end
println("\nSuccess: $(exported_count[]) target image maps exported to $output_folder.") println("\nSuccess: $(exported_count[]) target image maps exported to $output_folder.")
println("Success: $(exported_count[]) viridis maps exported to $viridis_folder.")
end end
@time run_production_pipeline() @time run_production_pipeline()
+199
View File
@@ -0,0 +1,199 @@
using Pkg
script_dir = @__DIR__
project_root = joinpath(script_dir, "..", "..")
Pkg.activate(joinpath(project_root, "environment"))
ENV["GKSwstype"] = "100"
using Plots
push!(LOAD_PATH, joinpath(project_root, "src"))
include(joinpath(project_root, "src", "MSI_src.jl"))
using .MSI_src
using CSV, DataFrames, Statistics
using Plots.Measures
dataset_name = length(ARGS) >= 1 ? ARGS[1] : "leaf"
data_dir = joinpath(project_root, "datasets", 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")
mkpath(figures_dir)
imzml_files = filter(f -> endswith(lowercase(f), ".imzml"), readdir(data_dir))
isempty(imzml_files) && error("No .imzML in $data_dir")
data_path = joinpath(data_dir, imzml_files[1])
mask_path = joinpath(data_dir, "region_of_interest.png")
if !isfile(mask_path)
alt = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir))
mask_path = isempty(alt) ? "" : joinpath(data_dir, alt[1])
end
println("Loading data: $data_path")
data = OpenMSIData(data_path)
MSI_src.precompute_analytics(data)
println("Computing average spectrum...")
# High-resolution ToF datasets (Mouse_Liver, Mouse_Stomach) store per-pixel m/z on
# non-uniform, pixel-specific grids, so an exact-key average spectrum never
# accumulates signal across pixels (139M+ unique channels, flat noise floor with a
# few dominant outliers). Match Stage 1's binning policy (MSI_BIN_AVG, set by
# run_full_pipeline.sh) so the plot reflects the real peaks.
bin_avg = get(ENV, "MSI_BIN_AVG", "")
if !isempty(bin_avg)
bin_step = parse(Float64, bin_avg)
lo = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
hi = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 1000.0
nb = max(1, Int(floor((hi - lo) / bin_step)) + 1)
mzs_avg = collect(lo .+ (0:nb-1) .* bin_step)
ints_avg = zeros(nb)
# Apply the ROI mask (if present) so off-tissue pixels are excluded, matching
# the masked get_average_spectrum path and the Stage 1 extraction policy.
mask_mat = nothing
if mask_path != "" && isfile(mask_path)
mask_mat = MSI_src.load_and_prepare_mask(mask_path, data.image_dims)
end
for i in 1:size(data.imzml_data, 2)
x = data.imzml_data[1, i]
y = data.imzml_data[2, i]
if mask_mat !== nothing && (y > size(mask_mat, 1) || x > size(mask_mat, 2) || mask_mat[y, x] == 0)
continue
end
pm = data.imzml_data[3, i]
pi = data.imzml_data[4, i]
idx = floor.(Int, (pm .- lo) ./ bin_step) .+ 1
for j in eachindex(pm)
k = idx[j]
if k >= 1 && k <= nb
ints_avg[k] += pi[j]
end
end
end
println(" Binned average spectrum: $bin_step Da grid over $(round(lo,digits=2))-$(round(hi,digits=2)) m/z ($nb channels)")
else
mzs_avg, ints_avg = MSI_src.get_average_spectrum(data, mask_path=mask_path)
end
function closest_index(xs::Vector{Float64}, target::Float64)
n = length(xs)
i = searchsortedfirst(xs, target)
i == 1 && return 1
i > n && return n
return (target - xs[i-1]) <= (xs[i] - target) ? i - 1 : i
end
function decimate_max(x::Vector{Float64}, y::Vector{Float64}, budget::Int)
n = length(x)
step = max(1, cld(n, budget))
step == 1 && return x, y
n_out = cld(n, step)
xo = Vector{Float64}(undef, n_out)
yo = Vector{Float64}(undef, n_out)
@inbounds for i in 0:(n_out-1)
lo = i * step + 1
hi = min(lo + step - 1, n)
m = argmax(view(y, lo:hi))
xo[i+1] = x[lo + m - 1]
yo[i+1] = y[lo + m - 1]
end
return xo, yo
end
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
mz_range = (min_vis_mz, max_vis_mz)
within = mzs_avg .>= min_vis_mz .&& mzs_avg .<= max_vis_mz
mzs_plot = mzs_avg[within]
ints_plot = ints_avg[within]
dmzs, dints = decimate_max(mzs_plot, ints_plot, 200_000)
p3 = plot(dmzs, dints,
linecolor = :black, linewidth = 1.0, label = "",
xlabel = "m/z", ylabel = "Relative Intensity",
title = "Full Average Spectrum ($dataset_name)",
size = (1400, 400), grid = false, framestyle = :box,
xlims = (min_vis_mz, max_vis_mz),
bottom_margin = 10mm, left_margin = 10mm
)
savefig(joinpath(figures_dir, "mean_spectrum_full.png"))
println(" Saved: mean_spectrum_full.png")
if isfile(cluster_csv)
clusters_df = CSV.read(cluster_csv, DataFrame)
cluster_colors = palette(:tab10)
p_annot = plot(dmzs, dints,
linecolor = :lightgray, linewidth = 0.7,
label = "Average Spectrum",
xlabel = "m/z", ylabel = "Relative Intensity",
title = "Cluster-Annotated Spectrum ($dataset_name)",
size = (1400, 600), legend = :outerright,
grid = false, framestyle = :box,
xlims = (min_vis_mz, max_vis_mz),
left_margin = 15mm, bottom_margin = 15mm
)
for cluster_id in sort(unique(clusters_df.cluster))
sub_df = filter(row -> row.cluster == cluster_id, clusters_df)
first_label = true
xs = Float64[]
ys = Float64[]
for target_mz in sub_df.mz
idx = closest_index(mzs_plot, target_mz)
m, i = mzs_plot[idx], ints_plot[idx]
push!(xs, m, m, NaN)
push!(ys, 0.0, i, NaN)
end
plot!(p_annot, xs, ys,
linecolor = cluster_colors[mod1(cluster_id + 1, 10)],
linewidth = 1.2, alpha = 0.9,
label = first_label ? "Cluster $cluster_id" : ""
)
first_label = false
end
savefig(joinpath(figures_dir, "spectrum_cluster_annotated.png"))
println(" Saved: spectrum_cluster_annotated.png")
for cluster_id in sort(unique(clusters_df.cluster))
sub_df = filter(row -> row.cluster == cluster_id, clusters_df)
mz_set = Set(sub_df.mz)
cluster_mask = [m in mz_set for m in mzs_plot]
cluster_ints = copy(ints_plot)
cluster_ints[.!cluster_mask] .= 0.0
dcmzs, dcints = decimate_max(mzs_plot, cluster_ints, 200_000)
p_cluster = plot(dmzs, dints,
linecolor = :lightgray, linewidth = 0.5, label = "",
xlabel = "m/z", ylabel = "Intensity",
title = "Cluster $cluster_id (n=$(nrow(sub_df)))",
size = (1400, 400), grid = false, framestyle = :box,
xlims = (min_vis_mz, max_vis_mz),
left_margin = 10mm, bottom_margin = 10mm,
legend = false
)
plot!(p_cluster, dcmzs, dcints,
linecolor = cluster_colors[mod1(cluster_id + 1, 10)],
linewidth = 1.5, label = ""
)
xs = Float64[]
ys = Float64[]
for target_mz in sub_df.mz
idx = closest_index(mzs_plot, target_mz)
mi, ii = mzs_plot[idx], ints_plot[idx]
push!(xs, mi, mi, NaN)
push!(ys, 0.0, ii, NaN)
end
plot!(p_cluster, xs, ys,
linecolor = cluster_colors[mod1(cluster_id + 1, 10)],
linewidth = 1.0, alpha = 0.6, label = ""
)
savefig(joinpath(figures_dir, "spectrum_cluster_$(cluster_id).pdf"))
println(" Saved: spectrum_cluster_$(cluster_id).pdf")
end
else
println(" No cluster CSV found at $cluster_csv — skipping per-cluster plots")
end
println("Done: $dataset_name spectrum plots → $figures_dir")