""" Ablation analysis — mirrors all_chrom_evaluation.ipynb but for: - Ablation_no_partition, Ablation_no_priority, Ablation_no_length - Plus Baseline_bpe_5120 and Merged_uni_len2_5120 as references Saves all plots to eval_outputs_ablation/plots/ """ import os import pandas as pd import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import seaborn as sns # ── Directories ────────────────────────────────────────────────────────────── ABLATION_DIR = "/home/n5huang/dna_token/tokenizer_evaluation/eval_outputs_ablation" MERGED_DIR = "/home/n5huang/dna_token/tokenizer_evaluation/eval_outputs_all_chrom" BASELINE_DIR = "/home/n5huang/dna_token/tokenizer_evaluation/eval_outputs_all_chrom_baseline_bpe" PLOT_DIR = os.path.join(ABLATION_DIR, "plots") os.makedirs(PLOT_DIR, exist_ok=True) pd.set_option("display.max_columns", 20) pd.set_option("display.width", 200) pd.set_option("display.float_format", "{:.6f}".format) # ── Helper: compute summary row from an agg CSV ───────────────────────────── def summarize_agg(agg: pd.DataFrame, name: str, scope: str, region: str = None): row = { "tokenizer": name, "scope": scope, "mean_of_mean_phyloP": agg["mean_mean"].mean(), "median_of_mean_phyloP": agg["mean_mean"].median(), "pct_mean_phyloP_above_0": (agg["mean_mean"] > 0).mean() * 100, "mean_of_variance": agg["mean_var"].mean(), "median_of_variance": agg["mean_var"].median(), "pct_variance_below_0.1": (agg["mean_var"] < 0.1).mean() * 100, "num_tokens": len(agg), "mean_token_count": agg["count"].mean(), "median_token_count": agg["count"].median(), } if region: row["region"] = region return row # ── 1. Window-Based Summary ────────────────────────────────────────────────── print("=" * 80) print("1. WINDOW-BASED SUMMARY") print("=" * 80) ablation_names = ["Ablation_no_partition", "Ablation_no_priority", "Ablation_no_length"] ref_names = { "Baseline_bpe_5120": os.path.join(BASELINE_DIR, "agg_Baseline_bpe_5120.csv"), "Merged_uni_len2_5120": os.path.join(MERGED_DIR, "agg_Merged_uni_len2_5120.csv"), } # Load all agg data (window) agg_data = {} window_summaries = [] for name in ablation_names: path = os.path.join(ABLATION_DIR, f"agg_{name}.csv") agg = pd.read_csv(path) agg_data[name] = agg window_summaries.append(summarize_agg(agg, name, "all_chrom_window")) for name, path in ref_names.items(): agg = pd.read_csv(path) agg_data[name] = agg window_summaries.append(summarize_agg(agg, name, "all_chrom_window")) df_window = pd.DataFrame(window_summaries) cols = ["tokenizer", "mean_of_mean_phyloP", "median_of_mean_phyloP", "pct_mean_phyloP_above_0", "mean_of_variance", "median_of_variance", "pct_variance_below_0.1", "num_tokens", "mean_token_count", "median_token_count"] df_window = df_window[cols] print(df_window.to_string(index=False)) df_window.to_csv(os.path.join(ABLATION_DIR, "summary_ablation_window.csv"), index=False) # ── 2. Region-Based Summary ───────────────────────────────────────────────── print("\n" + "=" * 80) print("2. REGION-BASED SUMMARY") print("=" * 80) agg_region = {} region_summaries = [] for name in ablation_names: for region in ["conserved", "neutral", "accelerated"]: path = os.path.join(ABLATION_DIR, f"agg_{name}_{region}.csv") if os.path.exists(path): agg = pd.read_csv(path) agg_region[(name, region)] = agg region_summaries.append(summarize_agg(agg, name, "all_chrom_region", region)) for name, base_path in ref_names.items(): base_dir = os.path.dirname(base_path) for region in ["conserved", "neutral", "accelerated"]: path = os.path.join(base_dir, f"agg_{name}_{region}.csv") if os.path.exists(path): agg = pd.read_csv(path) agg_region[(name, region)] = agg region_summaries.append(summarize_agg(agg, name, "all_chrom_region", region)) df_region = pd.DataFrame(region_summaries) cols_region = ["tokenizer", "region", "mean_of_mean_phyloP", "median_of_mean_phyloP", "pct_mean_phyloP_above_0", "mean_of_variance", "median_of_variance", "pct_variance_below_0.1", "num_tokens", "mean_token_count", "median_token_count"] df_region = df_region[cols_region] for region in ["conserved", "neutral", "accelerated"]: print(f"\n=== {region.upper()} ===") print(df_region[df_region["region"] == region].to_string(index=False)) df_region.to_csv(os.path.join(ABLATION_DIR, "summary_ablation_all_regions.csv"), index=False) # ── Color scheme ───────────────────────────────────────────────────────────── COLORS = { "Baseline_bpe_5120": "steelblue", "Merged_uni_len2_5120": "tomato", "Ablation_no_partition": "#2ca02c", # green "Ablation_no_priority": "#9467bd", # purple "Ablation_no_length": "#ff7f0e", # orange } # ── 3. Scatter: Mean phyloP vs Variance (Window) ──────────────────────────── print("\n" + "=" * 80) print("3. SCATTER PLOTS: Mean phyloP vs Variance") print("=" * 80) fig, axes = plt.subplots(1, 2, figsize=(18, 8)) for ax_idx, (xcol, xlabel) in enumerate([("mean_mean", "Mean phyloP"), ("median_mean", "Median Mean phyloP")]): ax = axes[ax_idx] for name, color in COLORS.items(): if name in agg_data: d = agg_data[name] ax.scatter(d[xcol], d["mean_var"], alpha=0.4, s=20, label=name, color=color) ax.set_xlabel(xlabel) ax.set_ylabel("Mean Variance") ax.set_title(f"Token Conservation: {xlabel} vs Variance") ax.legend(fontsize=8) plt.tight_layout() plt.savefig(os.path.join(PLOT_DIR, "scatter_mean_vs_var.png"), dpi=150, bbox_inches="tight") plt.close() print(f" Saved scatter_mean_vs_var.png") # ── 4. Histograms: Mean phyloP and Variance distributions ─────────────────── print("\n" + "=" * 80) print("4. HISTOGRAMS") print("=" * 80) fig, axes = plt.subplots(1, 2, figsize=(18, 6)) ax = axes[0] for name, color in COLORS.items(): if name in agg_data: ax.hist(agg_data[name]["mean_mean"], bins=50, alpha=0.5, label=name, color=color) ax.set_xlabel("Mean phyloP") ax.set_ylabel("Token Count") ax.set_title("Mean Conservation Distribution") ax.legend(fontsize=8) ax = axes[1] for name, color in COLORS.items(): if name in agg_data: ax.hist(agg_data[name]["mean_var"], bins=50, alpha=0.5, label=name, color=color) ax.set_xlabel("Mean Variance") ax.set_ylabel("Token Count") ax.set_title("Variance Distribution") ax.legend(fontsize=8) plt.tight_layout() plt.savefig(os.path.join(PLOT_DIR, "histograms_mean_var.png"), dpi=150, bbox_inches="tight") plt.close() print(f" Saved histograms_mean_var.png") # ── 5. Region scatter: by region ───────────────────────────────────────────── print("\n" + "=" * 80) print("5. REGION SCATTER PLOTS") print("=" * 80) fig, axes = plt.subplots(1, 3, figsize=(21, 7)) for i, region in enumerate(["conserved", "neutral", "accelerated"]): ax = axes[i] for name, color in COLORS.items(): key = (name, region) if key in agg_region: d = agg_region[key] ax.scatter(d["mean_mean"], d["mean_var"], alpha=0.4, s=20, label=name, color=color) ax.set_xlabel("Mean phyloP") ax.set_ylabel("Mean Variance") ax.set_title(f"{region.capitalize()} Regions") ax.legend(fontsize=7, loc="upper left") plt.suptitle("Region-Based: Ablation vs References", fontsize=14) plt.tight_layout() plt.savefig(os.path.join(PLOT_DIR, "scatter_by_region.png"), dpi=150, bbox_inches="tight") plt.close() print(f" Saved scatter_by_region.png") # ── 6. Bar charts: Summary metrics by tokenizer and region ────────────────── print("\n" + "=" * 80) print("6. BAR CHARTS: Summary metrics") print("=" * 80) metrics = ["mean_of_mean_phyloP", "pct_mean_phyloP_above_0", "mean_of_variance", "pct_variance_below_0.1"] metric_labels = ["Mean of Mean phyloP", "% Mean phyloP > 0", "Mean of Variance", "% Variance < 0.1"] fig, axes = plt.subplots(2, 2, figsize=(18, 12)) for idx, (metric, label) in enumerate(zip(metrics, metric_labels)): ax = axes[idx // 2, idx % 2] for region in ["conserved", "neutral", "accelerated"]: subset = df_region[df_region["region"] == region].copy() subset = subset.sort_values("tokenizer") x = range(len(subset)) offset = {"conserved": -0.25, "neutral": 0, "accelerated": 0.25}[region] color = {"conserved": "forestgreen", "neutral": "gray", "accelerated": "firebrick"}[region] ax.bar([xi + offset for xi in x], subset[metric], width=0.25, label=region, color=color, alpha=0.8) ax.set_xticks(range(len(subset))) ax.set_xticklabels(subset["tokenizer"], rotation=45, ha="right", fontsize=8) ax.set_ylabel(label) ax.set_title(label) ax.legend(fontsize=8) plt.suptitle("Ablation: Region-Based Metrics", fontsize=14) plt.tight_layout() plt.savefig(os.path.join(PLOT_DIR, "bar_region_metrics.png"), dpi=150, bbox_inches="tight") plt.close() print(f" Saved bar_region_metrics.png") # ── 7. Grouped bar: Ablation comparison (window metrics) ──────────────────── print("\n" + "=" * 80) print("7. GROUPED BAR: Window metrics comparison") print("=" * 80) order = ["Baseline_bpe_5120", "Ablation_no_partition", "Ablation_no_priority", "Ablation_no_length", "Merged_uni_len2_5120"] df_w_ordered = df_window.set_index("tokenizer").loc[order].reset_index() fig, axes = plt.subplots(1, 3, figsize=(20, 6)) # Mean phyloP ax = axes[0] bars = ax.barh(df_w_ordered["tokenizer"], df_w_ordered["mean_of_mean_phyloP"], color=[COLORS[n] for n in df_w_ordered["tokenizer"]]) ax.set_xlabel("Mean of Mean phyloP") ax.set_title("Conservation Signal (Higher is Better)") ax.invert_yaxis() for bar, val in zip(bars, df_w_ordered["mean_of_mean_phyloP"]): ax.text(bar.get_width() + 0.001, bar.get_y() + bar.get_height()/2, f"{val:.4f}", va="center", fontsize=9) # % above 0 ax = axes[1] bars = ax.barh(df_w_ordered["tokenizer"], df_w_ordered["pct_mean_phyloP_above_0"], color=[COLORS[n] for n in df_w_ordered["tokenizer"]]) ax.set_xlabel("% Mean phyloP > 0") ax.set_title("Positive Conservation Rate (Higher is Better)") ax.invert_yaxis() for bar, val in zip(bars, df_w_ordered["pct_mean_phyloP_above_0"]): ax.text(bar.get_width() + 0.1, bar.get_y() + bar.get_height()/2, f"{val:.1f}%", va="center", fontsize=9) # Mean variance ax = axes[2] bars = ax.barh(df_w_ordered["tokenizer"], df_w_ordered["mean_of_variance"], color=[COLORS[n] for n in df_w_ordered["tokenizer"]]) ax.set_xlabel("Mean of Variance") ax.set_title("Internal Variance (Lower is Better)") ax.invert_yaxis() for bar, val in zip(bars, df_w_ordered["mean_of_variance"]): ax.text(bar.get_width() + 0.001, bar.get_y() + bar.get_height()/2, f"{val:.4f}", va="center", fontsize=9) plt.suptitle("Ablation: Window-Based Summary Metrics", fontsize=14) plt.tight_layout() plt.savefig(os.path.join(PLOT_DIR, "bar_window_comparison.png"), dpi=150, bbox_inches="tight") plt.close() print(f" Saved bar_window_comparison.png") # ── 8. Print final comparison table ───────────────────────────────────────── print("\n" + "=" * 80) print("8. FINAL COMPARISON TABLE") print("=" * 80) print("\nWindow-based:") print(df_w_ordered[["tokenizer", "mean_of_mean_phyloP", "pct_mean_phyloP_above_0", "mean_of_variance", "pct_variance_below_0.1", "num_tokens"]].to_string(index=False)) print("\nRegion-based (conserved only):") cons = df_region[df_region["region"] == "conserved"].copy() cons = cons[cons["tokenizer"].isin(order)] print(cons[["tokenizer", "mean_of_mean_phyloP", "pct_mean_phyloP_above_0", "mean_of_variance", "num_tokens"]].to_string(index=False)) print(f"\nAll plots saved to: {PLOT_DIR}/") print("All summary CSVs saved to:", ABLATION_DIR)