File size: 11,246 Bytes
5b6c556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import os
import re
from typing import List, Optional

import matplotlib

matplotlib.use("Agg", force=True)
from matplotlib.patches import Patch
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns


def _parse_score(score_str: str) -> Optional[tuple[int, int]]:
    score_str = score_str.strip()
    if not score_str:
        return None

    match = re.search(r"(\d+)\s*of\s*(\d+)", score_str)
    if not match:
        return None

    obtained, total = int(match.group(1)), int(match.group(2))
    if total == 0:
        return None

    return obtained, total


def load_and_preprocess_faithfulness_data(filepath: str = "user_study/Faithfulness.csv") -> pd.DataFrame:
    """Parses the custom-formatted faithfulness CSV into a tidy dataframe."""
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"The data file was not found at {filepath}")

    raw = pd.read_csv(filepath, header=None).fillna("")

    records: List[dict] = []
    current_analysis: Optional[str] = None
    current_prompt: Optional[str] = None

    for _, row in raw.iterrows():
        cells = [str(cell).strip() for cell in row.tolist()]
        # Early continue if the row is fully empty.
        if not any(cells):
            continue

        primary = cells[0]
        metric = cells[1] if len(cells) > 1 else ""
        extra_cells = cells[2:]

        # Section header row ("Attribution Analysis, Faithfulness Score")
        if primary and metric.lower().startswith("faithfulness score"):
            current_analysis = primary
            current_prompt = None
            continue

        # Skip rows without an active analysis section.
        if current_analysis is None:
            continue

        # Rows that introduce a new prompt.
        if primary:
            current_prompt = primary.strip('"')

        # Skip rows that don't have a prompt in context or a metric label.
        if not current_prompt or not metric:
            continue

        # Collect all valid score cells.
        for raw_cell in extra_cells:
            if not raw_cell:
                continue

            # Handle sub-metric labels such as "L0-L10: 4 of 4".
            sub_label = None
            score_part = raw_cell

            if ":" in raw_cell:
                left, right = raw_cell.split(":", 1)
                if _parse_score(right):
                    sub_label = left.strip()
                    score_part = right.strip()
                else:
                    # Skip notes or malformed values.
                    continue

            parsed_score = _parse_score(score_part)
            if not parsed_score:
                continue

            obtained, total = parsed_score
            metric_name = metric
            if sub_label:
                metric_name = f"{metric} ({sub_label})"

            records.append(
                {
                    "analysis": current_analysis,
                    "prompt": current_prompt,
                    "metric": metric_name,
                    "obtained": obtained,
                    "total": total,
                    "ratio": obtained / total,
                }
            )

    df = pd.DataFrame(records)
    if df.empty:
        raise ValueError("No data could be parsed from the faithfulness CSV.")

    df["metric_base"] = df["metric"].str.replace(r"\s*\(.*\)$", "", regex=True)

    return df


def _configure_plot_style() -> None:
    sns.set_theme(style="ticks", palette="viridis")
    plt.rcParams["font.family"] = "sans-serif"
    plt.rcParams["font.sans-serif"] = "Arial"
    plt.rcParams["axes.labelweight"] = "normal"
    plt.rcParams["axes.titleweight"] = "bold"
    plt.rcParams["figure.titleweight"] = "bold"
    plt.rcParams["savefig.dpi"] = 300
    plt.rcParams["figure.facecolor"] = "white"
    plt.rcParams["axes.facecolor"] = "white"
    plt.rcParams["grid.alpha"] = 0.2
    plt.rcParams["axes.spines.top"] = False
    plt.rcParams["axes.spines.right"] = False


def plot_average_faithfulness_by_metric(
    df: pd.DataFrame,
    output_dir: str = "writing/ELIA__EACL_2026_System_Demonstrations_/figures",
) -> None:
    os.makedirs(output_dir, exist_ok=True)
    _configure_plot_style()

    aggregates = (
        df.groupby(["analysis", "metric_base"])
        .agg(mean_ratio=("ratio", "mean"))
        .reset_index()
    )

    analyses = aggregates["analysis"].unique().tolist()
    desired_order = ["Attribution Analysis", "Function Vectors", "Circuit Tracing"]
    analyses = [a for a in desired_order if a in analyses] + [
        a for a in analyses if a not in desired_order
    ]
    if not analyses:
        return

    metric_order = (
        aggregates[["metric_base"]]
        .drop_duplicates()
        .sort_values("metric_base")
        .squeeze()
        .tolist()
    )
    desired_metric_order = [
        "Occlusion",
        "Saliency",
        "Integrated Gradients",
        "Category Analysis",
        "Overall Placement",
        "Function Type Attribution",
        "Layer Evolution",
        "Circuit Overview",
        "Subnetwork Explorer",
        "Feature Explorer",
    ]
    metric_order = [m for m in desired_metric_order if m in metric_order] + [
        m for m in metric_order if m not in desired_metric_order
    ]
    palette = sns.color_palette("colorblind", n_colors=len(metric_order))
    color_map = dict(zip(metric_order, palette))

    fig_height = max(7, len(analyses) * 3.5)
    fig, axes = plt.subplots(len(analyses), 1, figsize=(10, fig_height), sharex=True)
    if len(analyses) == 1:
        axes = [axes]

    for ax, analysis in zip(axes, analyses):
        subset = aggregates[aggregates["analysis"] == analysis].copy()
        subset["metric_base"] = pd.Categorical(
            subset["metric_base"],
            categories=metric_order,
            ordered=True,
        )
        subset = subset.sort_values("metric_base").reset_index(drop=True)
        analysis_order = [m for m in metric_order if m in subset["metric_base"].unique()]
        sns.barplot(
            data=subset,
            x="mean_ratio",
            y="metric_base",
            hue="metric_base",
            palette=color_map,
            orient="h",
            dodge=False,
            legend=False,
            ax=ax,
            order=analysis_order,
        )

        if ax.legend_:
            ax.legend_.remove()

        ax.set_xlim(0, 1.04)
        ax.set_xlabel("")
        ax.set_ylabel("")
        ax.set_title(analysis, fontsize=18, pad=14)
        ax.xaxis.set_major_locator(MultipleLocator(0.1))
        ax.tick_params(axis="x", labelsize=14)
        ax.set_yticklabels([])
        ax.tick_params(axis="y", length=0)
        ax.grid(
            axis="x",
            linestyle="--",
            linewidth=0.7,
            alpha=0.35,
            color="#6b6b6b",
        )
        ax.set_axisbelow(True)

        for patch in ax.patches:
            width = patch.get_width()
            y_mid = patch.get_y() + patch.get_height() / 2
            label_x = min(width + 0.008, 1.038)
            ax.text(
                label_x,
                y_mid,
                f"{width:.2f}",
                va="center",
                ha="left",
                fontsize=14,
                color="#2c2c2c",
                fontweight="medium",
            )

    axes[-1].set_xlabel("Average Faithfulness Ratio", fontsize=16, labelpad=10)

    fig.tight_layout(rect=(0, 0.13, 1, 0.98))

    legend_groups = [
        [m for m in metric_order if m in ["Occlusion", "Saliency", "Integrated Gradients"]],
        [
            m
            for m in metric_order
            if m in ["Category Analysis", "Overall Placement", "Function Type Attribution", "Layer Evolution"]
        ],
        [
            m
            for m in metric_order
            if m.startswith("Circuit Overview")
            or m.startswith("Subnetwork Explorer")
            or m.startswith("Feature Explorer")
        ],
    ]

    legend_positions = [0.18, 0.5, 0.82]

    for group, x_pos in zip(legend_groups, legend_positions):
        handles = [Patch(color=color_map[m], label=m) for m in group if m in color_map]
        labels = [h.get_label() for h in handles]
        if not handles:
            continue
        fig.legend(
            handles,
            labels,
            loc="upper center",
            bbox_to_anchor=(x_pos, 0.14),
            frameon=False,
            fontsize=14,
            ncol=1,
            columnspacing=1.0,
            handlelength=1.2,
        )
    output_path = os.path.join(output_dir, "faithfulness_average_overview.png")
    fig.savefig(output_path)
    plt.close(fig)


def plot_faithfulness_heatmaps(
    df: pd.DataFrame,
    output_dir: str = "writing/ELIA__EACL_2026_System_Demonstrations_/figures",
) -> None:
    os.makedirs(output_dir, exist_ok=True)
    _configure_plot_style()

    cmap = sns.color_palette("viridis", as_cmap=True)

    for analysis, data in df.groupby("analysis"):
        pivot = (
            data.pivot_table(
                index="prompt",
                columns="metric",
                values="ratio",
                aggfunc="mean",
            )
            .sort_index()
        )

        plt.figure(figsize=(max(8, pivot.shape[1] * 1.5), max(6, pivot.shape[0] * 0.6)))
        sns.heatmap(
            pivot,
            annot=True,
            fmt=".2f",
            cmap=cmap,
            vmin=0,
            vmax=1,
            cbar_kws={"label": "Faithfulness Ratio"},
        )
        plt.title(f"{analysis} Faithfulness Heatmap", fontsize=18)
        plt.xlabel("Metric", fontsize=14)
        plt.ylabel("Prompt", fontsize=14)
        plt.xticks(rotation=30, ha="right")
        plt.yticks(rotation=0)
        plt.tight_layout()
        filename = f"faithfulness_heatmap_{analysis.lower().replace(' ', '_')}.png"
        plt.savefig(os.path.join(output_dir, filename))
        plt.close()


def plot_faithfulness_distribution(
    df: pd.DataFrame,
    output_dir: str = "writing/ELIA__EACL_2026_System_Demonstrations_/figures",
) -> None:
    os.makedirs(output_dir, exist_ok=True)
    _configure_plot_style()

    plt.figure(figsize=(10, 6))
    sns.boxplot(
        data=df,
        x="analysis",
        y="ratio",
        hue="metric_base",
        palette="colorblind",
        fliersize=0,
    )
    plt.ylim(0, 1)
    plt.ylabel("Faithfulness Ratio", fontsize=16)
    plt.xlabel("Analysis", fontsize=16)
    plt.title("Faithfulness Distribution by Analysis and Metric", fontsize=18)
    plt.xticks(rotation=15)
    plt.legend(title="Metric", fontsize=12)
    plt.yticks([i / 10 for i in range(0, 11)])
    plt.tight_layout()
    plt.savefig(os.path.join(output_dir, "faithfulness_distribution.png"))
    plt.close()


if __name__ == "__main__":
    try:
        data = load_and_preprocess_faithfulness_data("user_study/Faithfulness.csv")
        plot_average_faithfulness_by_metric(data)
        plot_faithfulness_heatmaps(data)
        plot_faithfulness_distribution(data)
        print("Faithfulness plots generated successfully.")
    except Exception as exc:
        print(f"An error occurred while generating faithfulness plots: {exc}")