| |
| """Per-metric bar charts: PS vs BL across all perturbations, with % difference.""" |
| from __future__ import annotations |
|
|
| import sys |
| from pathlib import Path |
|
|
| _THIS_DIR = Path(__file__).resolve().parent |
| if str(_THIS_DIR.parent) not in sys.path: |
| sys.path.insert(0, str(_THIS_DIR.parent)) |
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import numpy as np |
| import pandas as pd |
|
|
| from prompt_selection import config as cfg |
|
|
| CSV_PATH = cfg.EVAL_DIR / "all_comparison.csv" |
| OUTPUT_DIR = cfg.EVAL_DIR / "per_metric_charts" |
|
|
| |
| SELECTED_METRICS = [ |
| "pearson_delta", |
| "de_direction_match", |
| "de_sig_genes_recall", |
| "roc_auc", |
| "mse", |
| "mae", |
| ] |
|
|
| DISPLAY_NAMES = { |
| "pearson_delta": "Pearson Delta", |
| "de_direction_match": "DE Direction Match", |
| "de_sig_genes_recall": "DE Sig Genes Recall", |
| "roc_auc": "ROC AUC", |
| "mse": "MSE", |
| "mae": "MAE", |
| } |
|
|
| LOWER_IS_BETTER = {"mse", "mae"} |
|
|
|
|
| def plot_one_metric(df_metric: pd.DataFrame, metric_name: str, output_dir: Path): |
| """Generate a grouped bar chart for one metric across all perturbations.""" |
| display_name = DISPLAY_NAMES.get(metric_name, metric_name) |
| lower_better = metric_name in LOWER_IS_BETTER |
|
|
| |
| df_metric = df_metric.sort_values("prompt_selection", ascending=lower_better).reset_index(drop=True) |
|
|
| |
| short_names = { |
| "O-Demethylated Adapalene": "O-Demeth. Adapalene", |
| "Porcn Inhibitor III": "Porcn Inhib. III", |
| "Dimethyl Sulfoxide": "DMSO", |
| } |
| df_metric["display_pert"] = df_metric["perturbation"].map(short_names).fillna(df_metric["perturbation"]) |
|
|
| n = len(df_metric) |
| y = np.arange(n) |
| bar_h = 0.35 |
|
|
| fig, ax = plt.subplots(figsize=(12, max(6, n * 0.55))) |
|
|
| bars_ps = ax.barh(y - bar_h / 2, df_metric["prompt_selection"], bar_h, |
| label="Prompt Selection", color="#4C72B0", edgecolor="white", linewidth=0.5) |
| bars_bl = ax.barh(y + bar_h / 2, df_metric["random_baseline"], bar_h, |
| label="Random Baseline", color="#DD8452", edgecolor="white", linewidth=0.5) |
|
|
| ax.set_yticks(y) |
| ax.set_yticklabels(df_metric["display_pert"], fontsize=11) |
| ax.invert_yaxis() |
| ax.set_xlabel(display_name, fontsize=12) |
| ax.legend(loc="lower right", fontsize=10, framealpha=0.9) |
| ax.grid(axis="x", alpha=0.3, linestyle="--") |
| ax.set_axisbelow(True) |
|
|
| if lower_better: |
| subtitle = "(lower is better)" |
| else: |
| subtitle = "(higher is better)" |
| ax.set_title(f"{display_name} — Prompt Selection vs Random Baseline\n{subtitle}", |
| fontsize=14, fontweight="bold", pad=12) |
|
|
| |
| for idx, row in df_metric.iterrows(): |
| ps_val = row["prompt_selection"] |
| bl_val = row["random_baseline"] |
| max_val = max(abs(ps_val), abs(bl_val)) |
|
|
| if abs(bl_val) > 1e-12: |
| pct = (ps_val - bl_val) / abs(bl_val) * 100 |
| else: |
| pct = 0.0 |
|
|
| if abs(pct) < 0.01: |
| label = "0%" |
| color = "gray" |
| else: |
| sign = "+" if pct > 0 else "" |
| label = f"{sign}{pct:.1f}%" |
| if lower_better: |
| color = "#388E3C" if pct < 0 else "#D32F2F" |
| else: |
| color = "#388E3C" if pct > 0 else "#D32F2F" |
|
|
| |
| text_x = max(ps_val, bl_val) |
| if text_x < 0: |
| text_x = min(ps_val, bl_val) |
| ax.text(text_x * 1.02, idx, label, |
| va="center", ha="right", fontsize=10, fontweight="bold", color=color) |
| else: |
| ax.text(text_x * 1.02 + max_val * 0.01, idx, label, |
| va="center", ha="left", fontsize=10, fontweight="bold", color=color) |
|
|
| |
| x_vals = pd.concat([df_metric["prompt_selection"], df_metric["random_baseline"]]) |
| x_min, x_max = x_vals.min(), x_vals.max() |
| margin = (x_max - x_min) * 0.2 if x_max > x_min else abs(x_max) * 0.3 |
| if x_min < 0: |
| ax.set_xlim(left=x_min - margin * 0.5) |
| ax.set_xlim(right=x_max + margin) |
|
|
| plt.tight_layout() |
| out_path = output_dir / f"{metric_name}.png" |
| fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor="white") |
| plt.close(fig) |
| print(f"Saved: {out_path}") |
|
|
|
|
| def main(): |
| df = pd.read_csv(CSV_PATH) |
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| for metric in SELECTED_METRICS: |
| df_metric = df[df["metric"] == metric].copy() |
| df_metric = df_metric.dropna(subset=["prompt_selection", "random_baseline"]) |
|
|
| if df_metric.empty: |
| print(f"No data for {metric}, skipping.") |
| continue |
|
|
| plot_one_metric(df_metric, metric, OUTPUT_DIR) |
|
|
| print(f"\nAll charts saved to: {OUTPUT_DIR}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|