File size: 14,815 Bytes
715cc5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
364
from __future__ import annotations

import argparse
from pathlib import Path
from typing import Any

from src.analysis.compare_predictions import compare_prediction_maps, load_prediction_map, row_id
from src.data.io_utils import read_jsonl, write_jsonl

BIOMEDICAL_RELATIONS = {"TREATS", "PREVENTS", "CAUSES", "INCREASES_RISK", "DECREASES_RISK"}


def compact(text: Any, limit: int = 220) -> str:
    value = " ".join(str(text or "").split())
    if len(value) <= limit:
        return value
    clipped = value[:limit].rsplit(" ", 1)[0].strip()
    return f"{clipped}..."


def load_map(path: Path) -> dict[str, dict[str, Any]]:
    return {row_id(row): row for row in read_jsonl(path)}


def load_claims_map(path: Path) -> dict[str, dict[str, Any]]:
    rows = read_jsonl(path)
    mapping: dict[str, dict[str, Any]] = {}
    for row in rows:
        for key in ("pair_id", "claim_id"):
            value = row.get(key)
            if value:
                mapping[str(value)] = row
    return mapping


def group_rows(path: Path, key_field: str = "claim_id") -> dict[str, list[dict[str, Any]]]:
    grouped: dict[str, list[dict[str, Any]]] = {}
    for row in read_jsonl(path):
        grouped.setdefault(str(row.get(key_field, "")), []).append(row)
    return grouped


def evidence_rows(topk_row: dict[str, Any] | None, limit: int = 3) -> list[dict[str, Any]]:
    if not topk_row:
        return []
    rows: list[dict[str, Any]] = []
    for item in (topk_row.get("candidates") or [])[:limit]:
        rows.append(
            {
                "candidate_id": item.get("candidate_id") or item.get("doc_id"),
                "rank": item.get("rank_wikikg") or item.get("final_rank") or item.get("rank_reranker"),
                "wikikg_score": item.get("wikikg_final_score"),
                "reranker_score": item.get("reranker_score"),
                "text": compact(item.get("text", ""), limit=260),
            }
        )
    return rows


def path_rows(subgraph: dict[str, Any] | None, topk_row: dict[str, Any] | None, limit: int = 3) -> list[dict[str, Any]]:
    if not subgraph:
        return []
    preferred = {
        str(item.get("candidate_id") or item.get("doc_id"))
        for item in (topk_row or {}).get("candidates", [])[:5]
    }
    triples = list(subgraph.get("triples") or [])
    triples.sort(
        key=lambda row: (
            0 if str(row.get("source_doc_id", "")) in preferred else 1,
            str(row.get("triple_id", "")),
        )
    )
    output: list[dict[str, Any]] = []
    for triple in triples[:limit]:
        output.append(
            {
                "path_text": f"{triple.get('head', '')} -- {triple.get('relation', '')} -- {triple.get('tail', '')}",
                "source_doc_id": triple.get("source_doc_id", ""),
                "source_text": compact(triple.get("source_text", ""), limit=260),
            }
        )
    return output


def unsupported_rows(unsupported: list[dict[str, Any]], limit: int = 3) -> list[dict[str, Any]]:
    rows = sorted(
        unsupported,
        key=lambda row: (
            0 if "relation_demoted_to_associated" in set(row.get("removal_reasons") or []) | set(row.get("rule_notes") or []) else 1,
            str(row.get("claim_id", "")),
        ),
    )
    output: list[dict[str, Any]] = []
    for row in rows[:limit]:
        output.append(
            {
                "path_text": f"{row.get('head', '')} -- {row.get('relation', '')} -- {row.get('tail', '')}",
                "nli_label": row.get("nli_label", ""),
                "removal_reasons": row.get("removal_reasons", []),
                "source_text": compact(row.get("source_text", ""), limit=260),
            }
        )
    return output


def feature_summary(feature_row: dict[str, Any] | None) -> dict[str, Any]:
    if not feature_row:
        return {}
    candidates = list(feature_row.get("candidate_features") or [])
    if not candidates:
        return {}
    max_final = max(float(item.get("final_score") or 0.0) for item in candidates)
    max_path = max(float(item.get("kg_path_score") or 0.0) for item in candidates)
    max_provenance = max(float(item.get("provenance_confidence") or 0.0) for item in candidates)
    max_contradiction = max(float(item.get("contradiction_signal") or 0.0) for item in candidates)
    return {
        "max_final_score": round(max_final, 6),
        "max_kg_path_score": round(max_path, 6),
        "max_provenance_confidence": round(max_provenance, 6),
        "max_contradiction_signal": round(max_contradiction, 6),
    }


def build_prediction_case(
    comparison: dict[str, Any],
    category: str,
    claims_map: dict[str, dict[str, Any]],
    topk_map: dict[str, dict[str, Any]],
    feature_map: dict[str, dict[str, Any]],
    subgraph_map: dict[str, dict[str, Any]],
    unsupported_map: dict[str, list[dict[str, Any]]],
) -> dict[str, Any]:
    claim_id = comparison["id"]
    claim_row = claims_map.get(claim_id, {})
    topk_row = topk_map.get(claim_id)
    subgraph = subgraph_map.get(claim_id)
    unsupported = unsupported_map.get(claim_id, [])
    return {
        "dataset": comparison["dataset"],
        "split": comparison["split"],
        "category": category,
        "id": claim_id,
        "claim": comparison["claim"],
        "gold": comparison["gold"],
        "baseline_prediction": comparison["baseline_prediction"],
        "wikikg_prediction": comparison["wikikg_prediction"],
        "alternate_prediction": comparison["alternate_prediction"],
        "baseline_correct": comparison["baseline_correct"],
        "wikikg_correct": comparison["wikikg_correct"],
        "alternate_correct": comparison["alternate_correct"],
        "label": claim_row.get("label", ""),
        "metadata": claim_row.get("metadata", {}),
        "retrieval_metrics": {} if not topk_row else topk_row.get("metrics", {}),
        "path_summary": feature_summary(feature_map.get(claim_id)),
        "num_verified_facts": 0 if not subgraph else int(subgraph.get("num_facts") or 0),
        "num_verified_triples": 0 if not subgraph else int(subgraph.get("num_triples") or 0),
        "top_evidence": evidence_rows(topk_row),
        "top_verified_paths": path_rows(subgraph, topk_row),
        "top_unsupported_triples": unsupported_rows(unsupported),
    }


def pick_prediction_cases(
    comparisons: list[dict[str, Any]],
    dataset: str,
    claims_map: dict[str, dict[str, Any]],
    topk_map: dict[str, dict[str, Any]],
    feature_map: dict[str, dict[str, Any]],
    subgraph_map: dict[str, dict[str, Any]],
    unsupported_map: dict[str, list[dict[str, Any]]],
    sample_per_category: int,
) -> list[dict[str, Any]]:
    used: set[str] = set()
    output: list[dict[str, Any]] = []

    def take(category: str, predicate) -> None:
        count = 0
        for row in sorted(comparisons, key=lambda item: item["id"]):
            if row["id"] in used or not predicate(row):
                continue
            output.append(
                build_prediction_case(
                    row,
                    category,
                    claims_map,
                    topk_map,
                    feature_map,
                    subgraph_map,
                    unsupported_map,
                )
            )
            used.add(row["id"])
            count += 1
            if count >= sample_per_category:
                break

    if dataset == "averitec":
        take("baseline_wrong_wikikg_right", lambda row: row["baseline_correct"] is False and row["wikikg_correct"] is True)
        take(
            "verified_beats_unfiltered",
            lambda row: row["wikikg_correct"] is True and row["alternate_correct"] is False,
        )
        take(
            "nei_recovered_by_paths",
            lambda row: row["gold"] == "NEI" and row["baseline_correct"] is False and row["wikikg_correct"] is True,
        )
        take("conflicting_failure", lambda row: row["gold"] == "CONFLICTING" and row["wikikg_correct"] is False)
        take("wikikg_hurt_case", lambda row: row["baseline_correct"] is True and row["wikikg_correct"] is False)
    else:
        take("baseline_wrong_wikikg_right", lambda row: row["baseline_correct"] is False and row["wikikg_correct"] is True)
        take("wikikg_hurt_case", lambda row: row["baseline_correct"] is True and row["wikikg_correct"] is False)
        take(
            "good_path_wrong_verdict",
            lambda row: row["wikikg_correct"] is False and (subgraph_map.get(row["id"], {}).get("num_triples", 0) or subgraph_map.get(row["id"], {}).get("num_facts", 0)),
        )
    return output


def pick_healthver_relation_cases(
    claims_map: dict[str, dict[str, Any]],
    verified_map: dict[str, list[dict[str, Any]]],
    unsupported_map: dict[str, list[dict[str, Any]]],
    baseline_map: dict[str, dict[str, Any]] | None,
    wikikg_map: dict[str, dict[str, Any]] | None,
    sample_per_category: int,
) -> list[dict[str, Any]]:
    used: set[tuple[str, str]] = set()
    output: list[dict[str, Any]] = []

    def add_case(category: str, row: dict[str, Any]) -> None:
        key = (category, str(row.get("triple_id", "")))
        if key in used:
            return
        claim_id = str(row.get("claim_id", ""))
        claim_row = claims_map.get(claim_id, {})
        baseline_pred = "" if not baseline_map or claim_id not in baseline_map else baseline_map[claim_id].get("prediction", "")
        wikikg_pred = "" if not wikikg_map or claim_id not in wikikg_map else wikikg_map[claim_id].get("prediction", "")
        output.append(
            {
                "dataset": "healthver",
                "split": row.get("split", ""),
                "category": category,
                "id": claim_id,
                "claim": row.get("claim", ""),
                "gold": claim_row.get("label", ""),
                "baseline_prediction": baseline_pred,
                "wikikg_prediction": wikikg_pred,
                "relation_original": row.get("relation_original", ""),
                "relation": row.get("relation", ""),
                "nli_label": row.get("nli_label", ""),
                "entailment_score": row.get("entailment_score", ""),
                "rule_notes": row.get("rule_notes", []),
                "removal_reasons": row.get("removal_reasons", []),
                "source_text": compact(row.get("source_text", ""), limit=320),
                "verbalized_triple": row.get("verbalized_triple", ""),
                "metadata": claim_row.get("metadata", {}),
            }
        )
        used.add(key)

    demoted_verified = [
        row
        for rows in verified_map.values()
        for row in rows
        if row.get("relation_original") and row.get("relation_original") != row.get("relation")
    ]
    demoted_removed = [
        row
        for rows in unsupported_map.values()
        for row in rows
        if "relation_demoted_to_associated" in set(row.get("removal_reasons") or []) | set(row.get("rule_notes") or [])
    ]
    strong_verified = [
        row
        for rows in verified_map.values()
        for row in rows
        if row.get("relation") in BIOMEDICAL_RELATIONS and not row.get("relation_original")
    ]
    strong_removed = [
        row
        for rows in unsupported_map.values()
        for row in rows
        if row.get("relation") in BIOMEDICAL_RELATIONS or row.get("relation_original") in BIOMEDICAL_RELATIONS
    ]

    for bucket_name, rows in (
        ("demoted_verified_relation", demoted_verified),
        ("removed_strong_relation", demoted_removed),
        ("verified_strong_relation", strong_verified),
        ("unsupported_biomedical_relation", strong_removed),
    ):
        count = 0
        for row in sorted(rows, key=lambda item: str(item.get("claim_id", ""))):
            add_case(bucket_name, row)
            count += 1
            if count >= sample_per_category:
                break
    return output


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--dataset", required=True, choices=["averitec", "vifactcheck", "healthver"])
    parser.add_argument("--split", required=True)
    parser.add_argument("--claims", type=Path, required=True)
    parser.add_argument("--retrieval-topk", type=Path)
    parser.add_argument("--path-features", type=Path)
    parser.add_argument("--verified-subgraphs", type=Path)
    parser.add_argument("--verified-triples", type=Path, required=True)
    parser.add_argument("--unsupported-triples", type=Path, required=True)
    parser.add_argument("--baseline-pred", type=Path)
    parser.add_argument("--wikikg-pred", type=Path)
    parser.add_argument("--alternate-pred", type=Path)
    parser.add_argument("--sample-per-category", type=int, default=3)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    claims_map = load_claims_map(args.claims)
    verified_map = group_rows(args.verified_triples)
    unsupported_map = group_rows(args.unsupported_triples)

    if args.dataset == "healthver":
        baseline_map = load_prediction_map(args.baseline_pred) if args.baseline_pred else None
        wikikg_map = load_prediction_map(args.wikikg_pred) if args.wikikg_pred else None
        rows = pick_healthver_relation_cases(
            claims_map=claims_map,
            verified_map=verified_map,
            unsupported_map=unsupported_map,
            baseline_map=baseline_map,
            wikikg_map=wikikg_map,
            sample_per_category=args.sample_per_category,
        )
        write_jsonl(args.output, rows)
        print(f"Wrote {len(rows)} healthver relation cases to {args.output}")
        return

    if not (args.baseline_pred and args.wikikg_pred and args.retrieval_topk and args.path_features and args.verified_subgraphs):
        raise SystemExit("Prediction-comparison datasets require baseline/wikikg predictions and retrieval/subgraph inputs")

    baseline_map = load_prediction_map(args.baseline_pred)
    wikikg_map = load_prediction_map(args.wikikg_pred)
    alternate_map = load_prediction_map(args.alternate_pred) if args.alternate_pred else None
    comparisons = compare_prediction_maps(baseline_map, wikikg_map, alternate_map)
    topk_map = load_map(args.retrieval_topk)
    feature_map = load_map(args.path_features)
    subgraph_map = load_map(args.verified_subgraphs)
    rows = pick_prediction_cases(
        comparisons=comparisons,
        dataset=args.dataset,
        claims_map=claims_map,
        topk_map=topk_map,
        feature_map=feature_map,
        subgraph_map=subgraph_map,
        unsupported_map=unsupported_map,
        sample_per_category=args.sample_per_category,
    )
    write_jsonl(args.output, rows)
    print(f"Wrote {len(rows)} case studies to {args.output}")


if __name__ == "__main__":
    main()