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 using Statistics using Plots.Measures data_path = joinpath(project_root, "data", "Leaf.imzML") mask_path = joinpath(project_root, "data", "region_of_interest.png") clusters_path = joinpath(project_root, "outputs", "msi_clusters_results.csv") println("Loading data arrays...") data = OpenMSIData(data_path) clusters_df = CSV.read(clusters_path, DataFrame) println("Syncing Dataset Precomputed Boundaries...") MSI_src.precompute_analytics(data) mzs_avg, ints_avg = MSI_src.get_average_spectrum(data, mask_path=mask_path) 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)) p = plot(mzs_avg, ints_avg, linecolor = :lightgray, 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, framestyle = :box, xlims = (min_vis_mz, max_vis_mz), left_margin = 15mm, bottom_margin = 15mm ) cluster_colors = palette(:tab10) 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 idx = argmin(abs.(mzs_avg .- target_mz)) m = mzs_avg[idx] i = ints_avg[idx] 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 output_dir = joinpath(project_root, "outputs") savefig(joinpath(output_dir, "msi_spectra_plot.png")) println("Saved publication-ready plot: outputs/msi_spectra_plot.png") savefig(joinpath(output_dir, "msi_spectra_clusters.png")) println("Saved backup copy: outputs/msi_spectra_clusters.png")