from __future__ import annotations import math from typing import Any def query_metrics(candidates: list[dict[str, Any]], gold_ids: set[str] | None, cutoffs: tuple[int, ...] = (5, 10, 30, 100)) -> dict[str, Any]: if gold_ids is None: return { "has_gold": None, **{f"gold_at_{k}": None for k in cutoffs}, "mrr": None, "ndcg_at_10": None, } has_gold = bool(gold_ids) ranks = [idx + 1 for idx, row in enumerate(candidates) if row["candidate_id"] in gold_ids] first_rank = min(ranks) if ranks else None metrics = {"has_gold": has_gold} for cutoff in cutoffs: metrics[f"gold_at_{cutoff}"] = bool(first_rank is not None and first_rank <= cutoff) metrics["mrr"] = 1.0 / first_rank if first_rank else 0.0 dcg = 0.0 for idx, row in enumerate(candidates[:10], start=1): if row["candidate_id"] in gold_ids: dcg += 1.0 / math.log2(idx + 1) ideal_hits = min(len(gold_ids), 10) idcg = sum(1.0 / math.log2(idx + 1) for idx in range(1, ideal_hits + 1)) metrics["ndcg_at_10"] = dcg / idcg if idcg > 0 else 0.0 return metrics def aggregate_metrics(dataset: str, split: str, method: str, rows: list[dict[str, Any]], notes: str) -> dict[str, Any]: evaluable = [row for row in rows if row["metrics"].get("has_gold") is not None] if not evaluable: return { "Dataset": dataset, "Split": split, "Method": method, "R@5": "N/A", "R@10": "N/A", "R@30": "N/A", "R@100": "N/A", "MRR": "N/A", "nDCG@10": "N/A", "candidate_count_avg": round(sum(len(row["candidates"]) for row in rows) / max(1, len(rows)), 4), "gold_coverage": "N/A", "Notes": notes, } with_gold = [row for row in evaluable if row["metrics"].get("has_gold")] denom = max(1, len(with_gold)) def avg_bool(key: str) -> float: return sum(1 for row in with_gold if row["metrics"].get(key)) / denom return { "Dataset": dataset, "Split": split, "Method": method, "R@5": round(avg_bool("gold_at_5"), 6), "R@10": round(avg_bool("gold_at_10"), 6), "R@30": round(avg_bool("gold_at_30"), 6), "R@100": round(avg_bool("gold_at_100"), 6), "MRR": round(sum(float(row["metrics"].get("mrr", 0.0)) for row in with_gold) / denom, 6), "nDCG@10": round(sum(float(row["metrics"].get("ndcg_at_10", 0.0)) for row in with_gold) / denom, 6), "candidate_count_avg": round(sum(len(row["candidates"]) for row in rows) / max(1, len(rows)), 4), "gold_coverage": round(len(with_gold) / max(1, len(evaluable)), 6), "Notes": notes, }