File size: 5,029 Bytes
0161e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python3
"""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"

# Metrics to visualize
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

    # Sort by PS value (descending for quality, ascending for error)
    df_metric = df_metric.sort_values("prompt_selection", ascending=lower_better).reset_index(drop=True)

    # Shorten long perturbation names for display
    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)

    # Annotate percentage difference
    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"  # green if lower (better)
            else:
                color = "#388E3C" if pct > 0 else "#D32F2F"  # green if higher (better)

        # Position label to the right of the longer bar
        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)

    # Add margin for labels
    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()