import os import sys import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import Image PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from msi_preprocess_python import parse_imzml, compute_average_spectrum, load_mask, configure, find_mask_path dataset_name = sys.argv[1] if len(sys.argv) > 1 else "Datura_leaf" data_dir = os.path.join(PROJECT_ROOT, "datasets", dataset_name) output_dir = os.path.join(PROJECT_ROOT, "outputs", dataset_name) figures_dir = os.path.join(output_dir, "figures") cluster_csv = os.path.join(output_dir, "msi_clusters_results.csv") os.makedirs(figures_dir, exist_ok=True) imzml_path, ibd_path, _, _ = configure(data_dir, dataset_name) print(f"Parsing imzML: {imzml_path}") spectra_info, max_x, max_y, mz_format, int_format = parse_imzml(imzml_path) mask = load_mask(find_mask_path(data_dir), (max_x, max_y)) print(f" Dims: {max_x}x{max_y}, Spectra: {len(spectra_info)}") print("Computing average spectrum...") mzs_avg, ints_avg = compute_average_spectrum(spectra_info, ibd_path, mz_format, int_format, mask=mask) min_vis_mz = float(mzs_avg[0]) if mzs_avg[0] > 0 else 50.0 max_vis_mz = float(mzs_avg[-1]) if mzs_avg[-1] > 0 else 1000.0 cluster_colors = plt.cm.tab10(np.linspace(0, 1, 10)) # ---- 1. mean_spectrum_full.png ---- plt.figure(figsize=(14, 4)) plt.plot(mzs_avg, ints_avg, color='black', linewidth=1.0) plt.xlabel("m/z") plt.ylabel("Relative Intensity") plt.title(f"Full Average Spectrum ({dataset_name})") plt.xlim(min_vis_mz, max_vis_mz) plt.grid(False) plt.box(True) plt.tight_layout() plt.savefig(os.path.join(figures_dir, "mean_spectrum_full.png"), dpi=200) plt.close() print(" Saved: mean_spectrum_full.png") # ---- Cluster annotations ---- if os.path.isfile(cluster_csv): clusters_df = pd.read_csv(cluster_csv) clusters_df['mz'] = clusters_df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float) # ---- 2. spectrum_cluster_annotated.png ---- plt.figure(figsize=(14, 6)) plt.plot(mzs_avg, ints_avg, color='lightgray', linewidth=0.7, label="Average Spectrum") for cluster_id in sorted(clusters_df['cluster'].unique()): sub = clusters_df[clusters_df['cluster'] == cluster_id] color = cluster_colors[int(cluster_id) % 10] for target_mz in sub['mz']: idx = np.argmin(np.abs(mzs_avg - target_mz)) m, i = mzs_avg[idx], ints_avg[idx] plt.vlines(m, 0, i, color=color, linewidth=1.2, alpha=0.9, label=f"Cluster {cluster_id}" if m == sub['mz'].iloc[0] else "") plt.xlabel("m/z") plt.ylabel("Relative Intensity") plt.title(f"Cluster-Annotated Spectrum ({dataset_name})") plt.xlim(min_vis_mz, max_vis_mz) plt.legend(loc='upper right', fontsize=8) plt.box(True) plt.tight_layout() plt.savefig(os.path.join(figures_dir, "spectrum_cluster_annotated.png"), dpi=200) plt.close() print(" Saved: spectrum_cluster_annotated.png") # ---- 3. spectrum per cluster (one PDF per cluster) ---- for cluster_id in sorted(clusters_df['cluster'].unique()): sub = clusters_df[clusters_df['cluster'] == cluster_id] color = cluster_colors[int(cluster_id) % 10] mz_set = set(sub['mz']) cluster_ints = np.where([m in mz_set for m in mzs_avg], ints_avg, 0.0) fig, ax = plt.subplots(figsize=(14, 4)) ax.plot(mzs_avg, ints_avg, color='lightgray', linewidth=0.5) ax.plot(mzs_avg, cluster_ints, color=color, linewidth=1.5) for target_mz in sub['mz']: idx = np.argmin(np.abs(mzs_avg - target_mz)) mi, ii = mzs_avg[idx], ints_avg[idx] ax.vlines(mi, 0, ii, color=color, linewidth=1.0, alpha=0.6) ax.set_title(f"Cluster {cluster_id} (n={len(sub)})", fontsize=12) ax.set_xlabel("m/z") ax.set_ylabel("Relative Intensity") ax.set_xlim(min_vis_mz, max_vis_mz) ax.box(True) fig.tight_layout() fig.savefig(os.path.join(figures_dir, f"spectrum_cluster_{cluster_id}.pdf")) plt.close(fig) print(f" Saved: spectrum_cluster_{cluster_id}.pdf") else: print(f" No cluster CSV found at {cluster_csv} — skipping per-cluster plots") print(f"Done: {dataset_name} spectrum plots -> {figures_dir}")