"""Tests for src.metric. Run with `python -m pytest tests` or `python tests/test_metric.py`.""" import math import os import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from src.metric import (breakdown, entity_scores, f05_entity, macro_f05, # noqa: E402 read_id_list_tsv, write_id_list_tsv) def test_edge_both_empty(): assert f05_entity(set(), set()) == 1.0 def test_edge_true_empty_pred_nonempty(): assert f05_entity({"S2-1"}, set()) == 0.0 def test_edge_true_nonempty_pred_empty(): assert f05_entity(set(), {"S2-1"}) == 0.0 def test_edge_no_overlap(): assert f05_entity({"S2-1", "S2-2"}, {"S3-9"}) == 0.0 def test_problem_statement_example(): pred = {"S2-00047", "S2-00193", "S3-00812"} true = {"S2-00047", "S3-00812"} f = f05_entity(pred, true) assert round(f, 3) == 0.714 assert math.isclose(f, 5 * 2 / (4 * 3 + 2)) # F = 5 tp / (4|S| + |T|) def test_known_values(): # one correct out of k true: 1.25 / (0.25k + 1) for k, want in [(1, 1.0), (2, 1.25 / 1.5), (3, 1.25 / 1.75), (4, 1.25 / 2.0)]: true = {f"S2-{i}" for i in range(k)} assert math.isclose(f05_entity({"S2-0"}, true), want) # one wrong alongside one right, one true: P=.5, R=1 -> 0.5556 assert math.isclose(f05_entity({"S2-0", "S2-x"}, {"S2-0"}), 1.25 * 0.5 / (0.125 + 1)) def test_macro_missing_key_counts_as_empty(): truth = {"a": set(), "b": {"x"}, "c": {"y", "z"}} pred = {"b": {"x"}, "zzz": {"q"}} # 'a' missing -> empty -> 1; 'c' missing -> 0 assert math.isclose(macro_f05(pred, truth), (1.0 + 1.0 + 0.0) / 3) def test_read_write_tsv_roundtrip(): with tempfile.TemporaryDirectory() as d: p = os.path.join(d, "gt.tsv") with open(p, "w") as fh: fh.write("source1_entity_id\tmatched_entity_ids\n") fh.write("S1-1\tS2-1,S3-4\n") fh.write("S1-2\t\n") # empty list fh.write("S1-3\n") # missing second column fh.write('S1-4\t"S2-9, S2-8"\n') # quoted with spaces fh.write("S1-1\tS2-7\n") # repeated id -> union got = read_id_list_tsv(p) assert got == {"S1-1": {"S2-1", "S3-4", "S2-7"}, "S1-2": set(), "S1-3": set(), "S1-4": {"S2-9", "S2-8"}} p2 = os.path.join(d, "cand.tsv") with open(p2, "w") as fh: fh.write("source1_entity_id\tcandidate_entity_ids\r\nS1-9\tS2-1\r\n") assert read_id_list_tsv(p2) == {"S1-9": {"S2-1"}} p3 = os.path.join(d, "out.tsv") write_id_list_tsv(got, p3, all_ids=["S1-1", "S1-2", "S1-3", "S1-4", "S1-5"]) back = read_id_list_tsv(p3) assert back == {**got, "S1-5": set()} assert macro_f05(back, got) == 1.0 def test_breakdown(): truth = {"a": set(), "b": {"x"}, "c": {"y", "z"}, "d": {"1", "2", "3", "4", "5", "6"}} pred = {"a": {"q"}, "b": {"x"}, "c": {"y"}, "d": {"1"}} groups = {"a": "US", "b": "US", "c": "IN"} # 'd' -> bd = breakdown(pred, truth, groups) overall = bd.loc[("overall", "all")] assert math.isclose(overall["macro_f05"], macro_f05(pred, truth)) assert overall["n"] == 4 assert overall["singleton_acc"] == 0.0 # precision over non-empty preds: a 0, b 1, c 1, d 1 -> 0.75 assert math.isclose(overall["mean_precision"], 0.75) # recall over non-empty truths: b 1, c 1/2, d 1/6 assert math.isclose(overall["mean_recall"], (1 + 0.5 + 1 / 6) / 3) s = entity_scores(pred, truth) assert math.isclose(s["f05"].mean(), overall["macro_f05"]) assert math.isclose(bd.loc[("group", "US"), "macro_f05"], 0.5) assert bd.loc[("group", ""), "n"] == 1 assert bd.loc[("true_count", "5+"), "n"] == 1 assert bd.loc[("true_count", "0"), "singleton_acc"] == 0.0 assert math.isclose(bd.xs("true_count")["loss_share"].sum(), 1.0) def _run_all(): mod = sys.modules[__name__] names = [n for n in dir(mod) if n.startswith("test_") and callable(getattr(mod, n))] failed = 0 for n in names: try: getattr(mod, n)() print(f"PASS {n}") except Exception as e: # noqa: BLE001 failed += 1 print(f"FAIL {n}: {type(e).__name__}: {e}") print(f"{len(names) - failed}/{len(names)} passed") return failed if __name__ == "__main__": raise SystemExit(1 if _run_all() else 0)