TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
2.69 kB
"""The retrieval hit rule and its metrics, shared by the Step 3d dev probes and Step 4.
Hit rule (SPEC Step 4, from the 2d audit): a retrieved chunk hits an expected section
when its section IS that section or a DESCENDANT of it ("6.4.2" hits "6.4"), never an
ancestor (a whole-Section chunk does not hit "6.4"): two-way matching inflated System
A's hits for 6.4.2 from 6 windows to 17. Ancestry comes from sections.parquet's
parent_source_id, so laws don't nest (s. 268.3 is not inside s. 268) and "8.10" is
not inside "8.1".
"""
import pandas as pd
def ancestry(sections: pd.DataFrame) -> dict[str, frozenset[str]]:
"""source_id -> itself and every ancestor, following parent_source_id to the root.
A parent missing from the table ends the chain there; a cycle stops at the repeat."""
parent = dict(zip(sections.source_id, sections.parent_source_id, strict=True))
out = {}
for source in parent:
chain, node = set(), source
while node is not None and node not in chain:
chain.add(node)
node = parent.get(node)
out[source] = frozenset(chain)
return out
def first_hit(
sources: list[str], expected: frozenset[str], lineage: dict[str, frozenset[str]]
) -> int | None:
"""1-based rank of the first retrieved source that is an expected section or inside
one, or None. A source missing from the sections table counts as itself only."""
for rank, source in enumerate(sources, start=1):
if lineage.get(source, frozenset({source})) & expected:
return rank
return None
def first_hit_sets(
retrieved: list[frozenset[str]], expected: frozenset[str], lineage: dict[str, frozenset[str]]
) -> int | None:
"""first_hit for retrieved items that each cover SEVERAL sections (System A's
naive windows: covers_sources). A window hits when any section it covers is an
expected section or inside one. Never ancestor matching (2d audit)."""
for rank, sources in enumerate(retrieved, start=1):
if any(lineage.get(s, frozenset({s})) & expected for s in sources):
return rank
return None
def summarize(ranks: list[int | None]) -> dict[str, float]:
"""hit@1/5/10 (share of questions with a hit at or above that rank) and MRR (mean
of 1/rank, 0 for a miss): MRR rewards ranking the answer first, hit@k only finding it."""
if not ranks:
raise ValueError("no ranks to summarize")
n = len(ranks)
out = {f"hit@{k}": sum(r is not None and r <= k for r in ranks) / n for k in (1, 5, 10)}
out["mrr"] = sum(1 / r for r in ranks if r is not None) / n
return out