#!/usr/bin/env python3 """Compute the PhysCount metrics defined in the paper.""" from __future__ import annotations import argparse import json from collections import defaultdict from pathlib import Path QUESTION_TYPES = ("appearance", "entity", "image_formation", "correspondence") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--data-root", type=Path, default=Path(__file__).parents[1]) parser.add_argument("--predictions", type=Path, required=True) parser.add_argument("--output", type=Path) return parser.parse_args() def read_jsonl(path: Path) -> list[dict]: with path.open("r", encoding="utf-8") as handle: return [json.loads(line) for line in handle if line.strip()] def mean(values: list[float]) -> float: return sum(values) / len(values) def reported_mean( values: list[float], scale: float = 1.0, digits: int = 2 ) -> float | None: # An empty support set has no defined mean; serialize it as JSON null. return round(scale * mean(values), digits) if values else None def main() -> None: args = parse_args() questions = read_jsonl(args.data_root / "data" / "questions.jsonl") prediction_rows = read_jsonl(args.predictions) predictions = {row["question_id"]: row for row in prediction_rows} if len(predictions) != len(prediction_rows): raise SystemExit("Predictions contain duplicate question_id values") per_group: dict[str, dict[str, list[dict]]] = defaultdict( lambda: defaultdict(list) ) for question in questions: prediction_row = predictions.get(question["question_id"], {}) prediction = prediction_row.get("prediction") valid = ( bool(prediction_row.get("valid")) and isinstance(prediction, int) and not isinstance(prediction, bool) ) valid = valid and 0 <= prediction < 10_000 gold = question["answer"] absolute_error = abs(prediction - gold) if valid else None normalized_error = ( min(1.0, absolute_error / max(gold, 1)) if valid else 1.0 ) per_group[question["group_id"]][question["question_type"]].append( { "valid": valid, "exact": valid and prediction == gold, "ae": absolute_error, "nae": normalized_error, } ) type_naes: dict[str, list[float]] = defaultdict(list) type_maes: dict[str, list[float]] = defaultdict(list) group_scores: list[float] = [] group_exact: list[bool] = [] phys_grounding: list[float] = [] for type_rows in per_group.values(): accuracies: dict[str, float] = {} all_exact = True for question_type, rows in type_rows.items(): group_nae = mean([row["nae"] for row in rows]) type_naes[question_type].append(group_nae) accuracies[question_type] = 1.0 - group_nae valid_aes = [row["ae"] for row in rows if row["ae"] is not None] if valid_aes: type_maes[question_type].append(mean(valid_aes)) all_exact = all_exact and all(row["exact"] for row in rows) product = 1.0 for value in accuracies.values(): product *= value group_scores.append(product) group_exact.append(all_exact) if set(QUESTION_TYPES).issubset(type_rows): appearance_exact = all( row["exact"] for row in type_rows["appearance"] ) if appearance_exact: values = [ accuracies["entity"], accuracies["image_formation"], accuracies["correspondence"], ] harmonic = 0.0 if min(values) == 0 else 3.0 / sum(1 / v for v in values) phys_grounding.append(harmonic) metrics: dict[str, float | None] = {} short_names = { "appearance": "A", "entity": "E", "image_formation": "I", "correspondence": "C", } for question_type in QUESTION_TYPES: short = short_names[question_type] metrics[f"{short}-MAE"] = reported_mean(type_maes[question_type], digits=3) metrics[f"{short}-NAE"] = reported_mean(type_naes[question_type], scale=100) metrics["Score"] = reported_mean(group_scores, scale=100) metrics["Group-Acc"] = reported_mean([float(x) for x in group_exact], scale=100) metrics["Phys-Gnd"] = reported_mean(phys_grounding, scale=100) output = json.dumps(metrics, indent=2) + "\n" print(output, end="") if args.output: args.output.write_text(output, encoding="utf-8") if __name__ == "__main__": main()