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" # Second positional arg (optional) overrides the dataset directory, e.g. # `julia plot_mass_spectra.jl Datura_leaf /path/to/ai_data/Datura_leaf`. data_dir = length(ARGS) >= 2 ? ARGS[2] : joinpath(project_root, "ai_data", 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)) # `nothing` means "no mask" (see julia_msi_bridge.jl); "" would be treated as a path. mask_path = isempty(alt) ? nothing : 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 !== nothing && 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")