"""T4: evidence-grounded question answering over the Volve daily drilling reports (DDR). Source of every answer: the DDR tables that `scripts/02_parse_ddr.py` builds from the DDR XML files (`outputs/ddr/volve_ddr.duckdb`). Nothing is taken from the HTML or PDF renders, and no language model is involved. Rules (plan §4.3, AGENTS.md): * a question is a deterministic template (`configs/t4_templates.yaml`) filled with slot values that a SQL query enumerates from the data; * the gold answer is the result of the template's answer SQL, and the evidence is the set of rows (table, report_id, seq) that the template's evidence SQL returns. Both queries are stored with the question, with the slot values written in as literals, so each can be re-run as is; * an instance is dropped, and counted with its reason, when the answer is missing, ambiguous (several published values, a tie) or flagged by the template itself (`drop_reason` column of the answer SQL). A template with `on_null: not_reported` keeps instances without an answer as unanswerable questions (gold answer "not reported"); * trouble and NPT questions are phrased on the published codes (`proprietaryCode`, `stateDetailActivity`), never on the NPT definition of T2, which is not locked yet; * each question carries its wellbore(s) and well(s), the groups of the evaluation split. Evidence modes. `all`: every row is needed (sums, counts). `any`: every row states the answer by itself (a header value repeated in each report). `group`: the rows fall into groups and one row per group is enough (a list answer: one group per element). Citation recall is the share of groups with at least one cited row; citation precision is the share of cited rows that are evidence rows. `score(prediction, gold)` compares a predicted answer with the gold answer by answer type, within the tolerance of the template, and computes citation precision and recall. An independent pandas implementation of every template is in `volve_dia/t4_pandas.py`; `scripts/08_t4_questions.py` compares the two on every candidate instance. """ from __future__ import annotations import datetime as dt import hashlib import json import math import re import unicodedata from dataclasses import dataclass, field from fractions import Fraction from pathlib import Path from typing import Any import yaml from .names import canonical, well_of NOT_REPORTED = "not reported" ANSWER_TYPES = ("number", "date", "string", "enumeration", "boolean", "list") EVIDENCE_MODES = ("all", "any", "group") SLOT_TYPES = ("wellbore", "inch", "number", "date", "string") FAMILIES = ("lookup", "aggregation", "temporal_event", "comparison", "multi_hop") SCOPES = ("single", "pair", "field") #: Reasons the engine itself assigns; a template may add its own through the `drop_reason` column. DROP_NULL, DROP_DUPLICATE, DROP_NO_EVIDENCE = "null_answer", "duplicate", "no_evidence" _PARAM = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)") _FIELD = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}") # ---------------------------------------------------------------------------------------------------------------------- # Templates # ---------------------------------------------------------------------------------------------------------------------- class TemplateError(ValueError): """A template of the configuration is malformed, or its SQL returned something the rules do not allow.""" def load_config(path: Path | str) -> dict: """Read and validate `configs/t4_templates.yaml`. Returns the configuration with only the enabled templates in `templates`; disabled ones (the WITSML and formation-tops proposals) are kept in `disabled`.""" cfg = yaml.safe_load(Path(path).read_text(encoding="utf-8")) templates = cfg.get("templates") or [] ids = [t.get("id") for t in templates] if len(set(ids)) != len(ids): raise TemplateError(f"duplicate template ids: {sorted(i for i in set(ids) if ids.count(i) > 1)}") for t in templates: validate_template(t) cfg["disabled"] = [t for t in templates if not t.get("enabled", True)] + list(cfg.get("planned") or []) cfg["templates"] = [t for t in templates if t.get("enabled", True)] return cfg def validate_template(t: dict) -> None: tid = t.get("id", "?") def need(cond: bool, msg: str) -> None: if not cond: raise TemplateError(f"template {tid}: {msg}") for key in ("id", "family", "tadi", "questions", "slots", "slots_sql", "answer_sql", "evidence_sql", "evidence_mode", "answer", "source"): need(key in t, f"missing key {key!r}") need(t["family"] in FAMILIES, f"unknown family {t['family']!r}") need(t.get("scope", "single") in SCOPES, f"unknown scope {t.get('scope')!r}") need(t["evidence_mode"] in EVIDENCE_MODES, f"unknown evidence_mode {t['evidence_mode']!r}") need(t.get("on_null", "drop") in ("drop", "not_reported"), "on_null must be drop or not_reported") need(isinstance(t["questions"], list) and t["questions"], "questions must be a non-empty list") answer = t["answer"] need(answer.get("type") in ANSWER_TYPES, f"unknown answer type {answer.get('type')!r}") if answer["type"] == "list": need(answer.get("item_type") in ("number", "string"), "a list answer needs item_type number or string") if answer["type"] == "number" or answer.get("item_type") == "number": tol = answer.get("tolerance") or {} need("unit" in answer, "a numeric answer needs a unit (null for a pure count is not allowed: name what " "is counted)") need("abs" in tol or "rel" in tol, "a numeric answer needs tolerance.abs and/or tolerance.rel") slots = t["slots"] for name, spec in slots.items(): need(spec.get("type") in SLOT_TYPES, f"slot {name}: unknown type {spec.get('type')!r}") if t.get("scope", "single") != "field": need(any(s["type"] == "wellbore" for s in slots.values()), "a single or pair template needs a wellbore slot") for pattern in t["questions"]: unknown = set(_FIELD.findall(pattern)) - set(slots) need(not unknown, f"question uses undeclared slots {sorted(unknown)}") for key in ("answer_sql", "evidence_sql"): unknown = set(_PARAM.findall(t[key])) - set(slots) need(not unknown, f"{key} uses undeclared parameters {sorted(unknown)}") for spec_key in ("sample", "negatives"): if spec_key in t: cap = t[spec_key] need(isinstance(cap.get("n"), int) and cap["n"] > 0, f"{spec_key}.n must be a positive int") need(set(cap.get("by", [])) <= set(slots) | {"answer"}, f"{spec_key}.by must name slots or 'answer'") need("negatives" not in t or t.get("on_null") == "not_reported", "negatives needs on_null: not_reported") # ---------------------------------------------------------------------------------------------------------------------- # Rendering # ---------------------------------------------------------------------------------------------------------------------- def sql_literal(value: Any) -> str: if value is None: return "NULL" if isinstance(value, bool): return "TRUE" if value else "FALSE" if isinstance(value, (int, float)): if isinstance(value, float) and not math.isfinite(value): raise TemplateError(f"not a finite number: {value!r}") return repr(value) return "'" + str(value).replace("'", "''") + "'" def render_sql(sql: str, slots: dict) -> str: """The SQL with every `$slot` replaced by the literal of its value: what is executed and what is stored.""" return _PARAM.sub(lambda m: sql_literal(slots[m.group(1)]), sql).strip() def format_number(x: float, decimals: int | None = None) -> str: """'3520' for 3520.0, '1.48' for 1.48: how a number is written in a question or an answer text.""" if decimals is not None: x = round(x, decimals) return str(int(x)) if float(x).is_integer() else repr(float(x)) def format_inch(x: float) -> str: """Hole, bit and casing sizes as the reports write them, with the decimal value: 12.25 -> '12 1/4" (12.25 in)'.""" frac = Fraction(x).limit_denominator(16) if abs(float(frac) - x) > 1e-9: return f"{format_number(x)} in" whole, rest = divmod(frac, 1) if rest == 0: return f'{whole}"' return f'{whole} {rest.numerator}/{rest.denominator}" ({format_number(x)} in)' def display(slot_type: str, value: Any) -> str: if slot_type == "inch": return format_inch(float(value)) if slot_type == "number": return format_number(float(value)) return str(value) def render_question(pattern: str, slot_specs: dict, slots: dict) -> str: return pattern.format(**{k: display(slot_specs[k]["type"], v) for k, v in slots.items()}) def evidence_id(table: str, report_id: str, seq: int | None = None) -> str: """'activities:15_9_F_4_2008_02_19:10', 'reports:15_9_F_4_2008_02_19' (a report row has no sequence number).""" return f"{table}:{report_id}" if seq is None else f"{table}:{report_id}:{int(seq)}" def slot_key(template_id: str, slots: dict) -> str: return template_id + "|" + json.dumps(slots, sort_keys=True, ensure_ascii=False) def _rank(seed: int, key: str) -> str: return hashlib.sha256(f"{seed}|{key}".encode()).hexdigest() # ---------------------------------------------------------------------------------------------------------------------- # Instantiation # ---------------------------------------------------------------------------------------------------------------------- @dataclass class Outcome: """What one candidate instance (one row of the slot enumeration) of a template came to.""" template_id: str slots: dict status: str # "ok", "not_reported" or "drop" reason: str | None = None # the drop reason answer: Any = None evidence: list[dict] = field(default_factory=list) # {"table", "report_id", "seq", "group"} sql: str = "" evidence_sql: str = "" @property def key(self) -> str: return slot_key(self.template_id, self.slots) def evidence_partition(self) -> frozenset[frozenset[str]]: """The evidence as a set of groups of row ids: the form in which two implementations are compared.""" groups: dict[int, set[str]] = {} for e in self.evidence: groups.setdefault(e["group"], set()).add(evidence_id(e["table"], e["report_id"], e["seq"])) return frozenset(frozenset(g) for g in groups.values()) def _py(value: Any) -> Any: """DuckDB and numpy scalars as plain Python values (None for NULL and NaN).""" if value is None: return None if hasattr(value, "item"): value = value.item() if isinstance(value, float) and math.isnan(value): return None if isinstance(value, (dt.datetime, dt.date)): return value.isoformat()[:10] return value def coerce_answer(spec: dict, values: list[Any]) -> Any: """The answer SQL's `answer` column as the gold answer of the template's type.""" kind = spec["type"] def one(v: Any, item_kind: str) -> Any: if item_kind == "number": v = float(v) return round(v, spec["round"]) if "round" in spec else v if item_kind == "boolean": return bool(v) return str(v) if kind == "list": return [one(v, spec["item_type"]) for v in values] return one(values[0], kind if kind in ("number", "boolean") else "string") def group_evidence(mode: str, rows: list[dict]) -> list[dict]: """Evidence rows with their group number: one group per row (`all`), one group (`any`) or the `grp` column.""" rows = sorted(rows, key=lambda r: (r["table"], r["report_id"], -1 if r["seq"] is None else r["seq"])) seen, out = set(), [] labels: dict[Any, int] = {} for r in rows: rid = evidence_id(r["table"], r["report_id"], r["seq"]) if (rid, r.get("grp")) in seen: continue seen.add((rid, r.get("grp"))) if mode == "all": group = len(out) elif mode == "any": group = 0 else: group = labels.setdefault(r["grp"], len(labels)) out.append({"table": r["table"], "report_id": r["report_id"], "seq": r["seq"], "group": group}) return out def _rows(con, sql: str) -> list[dict]: cur = con.execute(sql) cols = [d[0] for d in cur.description] return [dict(zip(cols, (_py(v) for v in row))) for row in cur.fetchall()] def run_instance(con, tpl: dict, slots: dict) -> Outcome: """Run the answer SQL and the evidence SQL of one candidate instance and apply the drop rules.""" spec = tpl["answer"] sql, ev_sql = render_sql(tpl["answer_sql"], slots), render_sql(tpl["evidence_sql"], slots) out = Outcome(tpl["id"], slots, "drop", sql=sql, evidence_sql=ev_sql) rows = _rows(con, sql) if rows and "answer" not in rows[0]: raise TemplateError(f"template {tpl['id']}: the answer SQL has no `answer` column") reasons = [r["drop_reason"] for r in rows if r.get("drop_reason")] if reasons: out.reason = reasons[0] return out values = [r["answer"] for r in rows if r["answer"] is not None] if spec["type"] != "list" and len(rows) > 1: raise TemplateError(f"template {tpl['id']}: {len(rows)} answer rows for {slots} (a scalar answer needs one)") if not values: if tpl.get("on_null", "drop") == "not_reported": out.status, out.answer = "not_reported", NOT_REPORTED else: out.reason = DROP_NULL return out out.answer = coerce_answer(spec, values) ev_rows = _rows(con, ev_sql) for r in ev_rows: r.setdefault("seq", None) if tpl["evidence_mode"] == "group" and "grp" not in r: raise TemplateError(f"template {tpl['id']}: evidence_mode group needs a `grp` column") out.evidence = group_evidence(tpl["evidence_mode"], ev_rows) if not out.evidence and not (spec["type"] == "boolean" and out.answer is False): out.reason = DROP_NO_EVIDENCE # an answer that no row supports is not a benchmark item return out out.status = "ok" return out def run_template(con, tpl: dict) -> list[Outcome]: """Every candidate instance of a template, in the order of its slot enumeration.""" slot_names = list(tpl["slots"]) cur = con.execute(tpl["slots_sql"]) cols = [d[0] for d in cur.description] if cols != slot_names: raise TemplateError(f"template {tpl['id']}: slots_sql returns {cols}, the template declares {slot_names}") outcomes, seen = [], set() for row in cur.fetchall(): slots = dict(zip(cols, (_py(v) for v in row))) if any(v is None for v in slots.values()): raise TemplateError(f"template {tpl['id']}: NULL slot value in {slots}") o = run_instance(con, tpl, slots) if o.key in seen: o.status, o.reason = "drop", DROP_DUPLICATE seen.add(o.key) outcomes.append(o) return outcomes def _sample(outcomes: list[Outcome], spec: dict | None, seed: int) -> tuple[list[Outcome], int]: """At most `n` outcomes per group of `by` (slot names or 'answer'), chosen by a seeded hash of the instance key, so the choice does not depend on the order of the enumeration.""" if not spec: return outcomes, 0 groups: dict[tuple, list[Outcome]] = {} for o in outcomes: key = tuple(json.dumps(o.answer if b == "answer" else o.slots[b], sort_keys=True) for b in spec.get("by", [])) groups.setdefault(key, []).append(o) kept = [o for g in groups.values() for o in sorted(g, key=lambda o: _rank(seed, o.key))[:spec["n"]]] return kept, len(outcomes) - len(kept) def select(tpl: dict, outcomes: list[Outcome], seed: int) -> tuple[list[Outcome], dict]: """The instances that become questions: answerable ones (capped by `sample`) and, for `on_null: not_reported`, unanswerable ones (capped by `negatives`).""" ok, n_ok = _sample([o for o in outcomes if o.status == "ok"], tpl.get("sample"), seed) neg, n_neg = _sample([o for o in outcomes if o.status == "not_reported"], tpl.get("negatives"), seed) return ok + neg, {"answerable": n_ok, "unanswerable": n_neg} def _choices(con, tpl: dict, slots: dict) -> list[str] | None: spec = tpl["answer"].get("choices") if not spec: return None if "slots" in spec: return [str(slots[s]) for s in spec["slots"]] if "_choices" not in tpl: tpl["_choices"] = [str(r[0]) for r in con.execute(spec["sql"]).fetchall()] return tpl["_choices"] def answer_text(spec: dict, answer: Any) -> str: """The gold answer as a reader would write it: '3520 m', '2007-08-26', '36, 26, 17.5 in', 'yes'.""" unit = f" {spec['unit']}" if spec.get("unit") else "" if answer == NOT_REPORTED: return NOT_REPORTED if spec["type"] == "number": return format_number(answer) + unit if spec["type"] == "boolean": return "yes" if answer else "no" if spec["type"] == "list": items = [format_number(v) if spec["item_type"] == "number" else str(v) for v in answer] return ", ".join(items) + unit return str(answer) def make_question(con, tpl: dict, o: Outcome, all_wellbores: list[str], seed: int) -> dict: spec, tol = tpl["answer"], tpl["answer"].get("tolerance") or {} scope = tpl.get("scope", "single") if scope == "field": wellbores = list(all_wellbores) else: wellbores = [canonical(o.slots[k]) for k, s in tpl["slots"].items() if s["type"] == "wellbore"] wells = sorted({well_of(w) for w in wellbores}) pattern_index = int(_rank(seed, "pattern|" + o.key), 16) % len(tpl["questions"]) digest = hashlib.sha256(o.key.encode()).hexdigest()[:10] return { "id": f"T4-{tpl['id']}-{digest}", "template_id": tpl["id"], "family": tpl["family"], "tadi_category": tpl["tadi"].get("category"), "tadi_subcategory": tpl["tadi"].get("subcategory"), "scope": scope, "wellbore": None if scope == "field" else wellbores[0], "well": None if scope == "field" else well_of(wellbores[0]), "wellbores": wellbores, "wells": wells, "question": render_question(tpl["questions"][pattern_index], tpl["slots"], o.slots), "pattern_index": pattern_index, "slots": o.slots, "answer": o.answer, "answer_text": answer_text(spec, o.answer), "answer_type": spec["type"], "item_type": spec.get("item_type"), "unit": spec.get("unit"), "tolerance_abs": tol.get("abs"), "tolerance_rel": tol.get("rel"), "tolerance_days": tol.get("days", 0) if spec["type"] == "date" else None, "choices": _choices(con, tpl, o.slots), "answerable": o.status == "ok", "sql": o.sql, "evidence_sql": o.evidence_sql, "evidence": o.evidence, "evidence_mode": tpl["evidence_mode"], "printed_in_render": bool((tpl.get("render") or {}).get("printed", True)), "n_evidence": len(o.evidence), "n_evidence_groups": len({e["group"] for e in o.evidence}), "source": list(tpl["source"]), "caveats": list(tpl.get("caveats") or []), } def build(con, cfg: dict) -> tuple[list[dict], dict[str, list[Outcome]], dict]: """All questions, the outcome of every candidate instance per template (for the cross-check) and the summary.""" seed = int(cfg.get("seed", 0)) all_wellbores = [r[0] for r in con.execute("SELECT DISTINCT wellbore FROM reports ORDER BY 1").fetchall()] questions, outcomes, per_template = [], {}, {} texts: dict[str, str] = {} for tpl in cfg["templates"]: outs = run_template(con, tpl) outcomes[tpl["id"]] = outs kept, not_sampled = select(tpl, outs, seed) drops: dict[str, int] = {} for o in outs: if o.status == "drop": drops[o.reason] = drops.get(o.reason, 0) + 1 n_q = {"answerable": 0, "unanswerable": 0} for o in sorted(kept, key=lambda o: o.key): q = make_question(con, tpl, o, all_wellbores, seed) if q["question"] in texts: # the same text from two instances: keep the first only drops[DROP_DUPLICATE] = drops.get(DROP_DUPLICATE, 0) + 1 continue texts[q["question"]] = q["id"] questions.append(q) n_q["answerable" if q["answerable"] else "unanswerable"] += 1 per_template[tpl["id"]] = { "family": tpl["family"], "answer_type": tpl["answer"]["type"], "candidates": len(outs), "dropped": dict(sorted(drops.items())), "not_sampled": not_sampled, "questions": n_q["answerable"] + n_q["unanswerable"], **n_q, } if len({q["id"] for q in questions}) != len(questions): raise TemplateError("question ids are not unique") return questions, outcomes, summarise(questions, per_template) def summarise(questions: list[dict], per_template: dict) -> dict: def count(key) -> dict: out: dict[str, int] = {} for q in questions: k = key(q) out[k] = out.get(k, 0) + 1 return dict(sorted(out.items())) drops: dict[str, int] = {} for t in per_template.values(): for reason, n in t["dropped"].items(): drops[reason] = drops.get(reason, 0) + n sizes = sorted(q["n_evidence"] for q in questions if q["answerable"] and q["n_evidence"]) return { "questions": len(questions), "answerable": sum(q["answerable"] for q in questions), "unanswerable": sum(not q["answerable"] for q in questions), "templates": len(per_template), "candidates": sum(t["candidates"] for t in per_template.values()), "dropped": dict(sorted(drops.items())), "dropped_total": sum(drops.values()), "not_sampled": {k: sum(t["not_sampled"][k] for t in per_template.values()) for k in ("answerable", "unanswerable")}, "per_family": count(lambda q: q["family"]), "per_answer_type": count(lambda q: q["answer_type"]), "per_scope": count(lambda q: q["scope"]), "per_tadi_category": count(lambda q: str(q["tadi_category"])), "per_wellbore": count(lambda q: q["wellbore"] or "(field)"), "per_well": count(lambda q: q["well"] or "(field)"), "evidence_rows": {"min": sizes[0], "median": sizes[len(sizes) // 2], "max": sizes[-1], "over_50": sum(s > 50 for s in sizes)} if sizes else {}, "per_template": per_template, } def connect(db_path: Path | str): """The DDR database, read-only, with the session time zone fixed so no result depends on the machine.""" import duckdb con = duckdb.connect(str(db_path), read_only=True) con.execute("SET TimeZone = 'UTC'") return con def write(questions: list[dict], out_dir: Path) -> None: """questions.jsonl (native values) and questions.parquet (answer and slots as JSON text; evidence as a list of {table, report_id, seq, group} structs, seq NULL for a row of `reports`).""" import pyarrow as pa import pyarrow.parquet as pq out_dir.mkdir(parents=True, exist_ok=True) with (out_dir / "questions.jsonl").open("w", encoding="utf-8") as f: for q in questions: f.write(json.dumps(q, ensure_ascii=False) + "\n") strings = pa.list_(pa.string()) types = { "tadi_category": pa.int8(), "pattern_index": pa.int16(), "n_evidence": pa.int32(), "n_evidence_groups": pa.int32(), "tolerance_abs": pa.float64(), "tolerance_rel": pa.float64(), "tolerance_days": pa.int16(), "answerable": pa.bool_(), "printed_in_render": pa.bool_(), "wellbores": strings, "wells": strings, "choices": strings, "source": strings, "caveats": strings, "evidence": pa.list_(pa.struct([("table", pa.string()), ("report_id", pa.string()), ("seq", pa.int32()), ("group", pa.int32())])), } as_json = ("answer", "slots") columns = list(questions[0]) if questions else [] arrays = [] for col in columns: values = [q[col] for q in questions] if col in as_json: values = [json.dumps(v, ensure_ascii=False, sort_keys=True) for v in values] arrays.append(pa.array(values, type=types.get(col, pa.string()))) pq.write_table(pa.Table.from_arrays(arrays, names=columns), out_dir / "questions.parquet") def read_jsonl(path: Path | str) -> list[dict]: with Path(path).open(encoding="utf-8") as f: return [json.loads(line) for line in f if line.strip()] # ---------------------------------------------------------------------------------------------------------------------- # Scoring # ---------------------------------------------------------------------------------------------------------------------- #: Factor from a unit to the reference unit of its dimension. A prediction in another unit of the same dimension is #: converted before the tolerance is applied; a unit of another dimension, or an unknown one, is a wrong answer. UNITS = { "m": ("length", 1.0), "ft": ("length", 0.3048), "km": ("length", 1000.0), "metres": ("length", 1.0), "meters": ("length", 1.0), "feet": ("length", 0.3048), "h": ("time", 1.0), "hr": ("time", 1.0), "hrs": ("time", 1.0), "hour": ("time", 1.0), "hours": ("time", 1.0), "min": ("time", 1 / 60), "d": ("time", 24.0), "day": ("time", 24.0), "days": ("time", 24.0), "g/cm3": ("density", 1.0), "sg": ("density", 1.0), "kg/l": ("density", 1.0), "kg/m3": ("density", 0.001), "ppg": ("density", 0.119826427), "m/h": ("rate", 1.0), "m/hr": ("rate", 1.0), "ft/h": ("rate", 0.3048), "ft/hr": ("rate", 0.3048), "deg": ("angle", 1.0), "dega": ("angle", 1.0), "degrees": ("angle", 1.0), "°": ("angle", 1.0), "in": ("size", 1.0), "inch": ("size", 1.0), "inches": ("size", 1.0), '"': ("size", 1.0), } _ABSTAIN = re.compile(r"^\W*(not\s+(reported|available|recorded|stated|found|applicable)|no\s+(such\s+)?(record|data|" r"information|event|activity|value)\w*(\s.*)?|unknown|n/?a|none|null|unanswerable|" r"cannot\s+be\s+(determined|answered).*)\W*$", re.I) _NUMBER = re.compile(r"[-+]?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?|[-+]?\.\d+") _REPORT_ID = re.compile(r"\d+_\d+_.+_\d{4}_\d{2}_\d{2}") _DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%d-%m-%Y", "%d %B %Y", "%d %b %Y", "%B %d, %Y", "%b %d, %Y", "%B %d %Y", "%b %d %Y", "%Y/%m/%d") def is_abstention(answer: Any) -> bool: """None, an empty string or a phrase such as 'not reported', 'N/A', 'no such event'.""" if answer is None: return True if isinstance(answer, (list, tuple)): return len(answer) == 0 if isinstance(answer, str): return not answer.strip() or bool(_ABSTAIN.match(answer.strip())) return False def parse_number(value: Any) -> float | None: """A number from a number or from text ('3,520 m', '1,48', '12 1/4"'). The first number of the text is used; '1,48' is read as a decimal comma, '3,520' as a thousands separator.""" if isinstance(value, bool): return None if isinstance(value, (int, float)): return float(value) if math.isfinite(value) else None if not isinstance(value, str): return None mixed = re.match(r'^\s*(\d+)\s+(\d+)/(\d+)\s*("|in\b|inch)?', value) # 12 1/4" if mixed and int(mixed.group(3)): return int(mixed.group(1)) + int(mixed.group(2)) / int(mixed.group(3)) m = _NUMBER.search(value) if not m: return None text = m.group(0).rstrip(",") if "," in text: if re.fullmatch(r"[-+]?\d{1,3}(,\d{3})+(\.\d+)?", text): text = text.replace(",", "") elif text.count(",") == 1 and "." not in text: text = text.replace(",", ".") else: text = text.replace(",", "") try: return float(text) except ValueError: return None def parse_date(value: Any) -> dt.date | None: if isinstance(value, dt.datetime): return value.date() if isinstance(value, dt.date): return value if not isinstance(value, str): return None text = value.strip() m = re.match(r"\d{4}-\d{2}-\d{2}", text) if m: text = m.group(0) for fmt in _DATE_FORMATS: try: return dt.datetime.strptime(text, fmt).date() except ValueError: continue return None def parse_boolean(value: Any) -> bool | None: if isinstance(value, bool): return value if isinstance(value, (int, float)) and value in (0, 1): return bool(value) if isinstance(value, str): m = re.match(r"^\W*(yes|true|no|false)\b", value.strip(), re.I) if m: return m.group(1).lower() in ("yes", "true") return None def normalise_text(value: Any) -> str: """Case, accents, punctuation and spacing removed: 'Mærsk Inspirer.' and 'MÆRSK INSPIRER' compare equal.""" text = unicodedata.normalize("NFKD", str(value)).casefold() text = "".join(c for c in text if not unicodedata.combining(c)) return re.sub(r"[^0-9a-zæøå]+", " ", text).strip() def _same_text(pred: Any, gold: str) -> bool: if normalise_text(pred) == normalise_text(gold): return True try: # wellbore names: 'NO 15/9-F-1 B', '15_9_F_1_B' return canonical(str(pred)) == canonical(gold) except ValueError: return False def convert_unit(value: float, unit: str | None, gold_unit: str | None) -> float | None: """`value` in `unit` expressed in `gold_unit`; None if the two are not of the same known dimension. A prediction without a unit is taken to be in the gold unit. A gold unit that names what is counted ('reports', 'entries') is a label, not a physical unit: the predicted unit is then ignored.""" if not unit or not gold_unit: return value u, g = unit.strip().lower().replace(" ", ""), gold_unit.strip().lower() if u == g or g not in UNITS: return value if u not in UNITS or UNITS[u][0] != UNITS[g][0]: return None return value * UNITS[u][1] / UNITS[g][1] def within_tolerance(pred: float, gold: float, abs_tol: float | None = None, rel_tol: float | None = None) -> bool: """|pred - gold| <= max(abs_tol, rel_tol * |gold|), with a small allowance for floating-point noise.""" limit = max(abs_tol or 0.0, (rel_tol or 0.0) * abs(gold)) return abs(pred - gold) <= limit + 1e-9 * max(1.0, abs(gold)) def inline_unit(text: Any) -> str | None: """The unit written after the first number of a text answer ('11548.6 ft' -> 'ft'), if it is a known unit.""" if not isinstance(text, str): return None m = _NUMBER.search(text) if not m: return None u = re.match(r"\s*([A-Za-z°\"][A-Za-z0-9/]*)", text[m.end():]) return u.group(1).lower() if u and u.group(1).lower() in UNITS else None def _match_value(pred: Any, gold: Any, kind: str, q: dict, unit: str | None) -> bool: if kind == "number": p = parse_number(pred) if p is None: return False unit = unit or inline_unit(pred) p = convert_unit(p, unit, q.get("unit")) return p is not None and within_tolerance(p, float(gold), q.get("tolerance_abs"), q.get("tolerance_rel")) if kind == "date": p = parse_date(pred) return p is not None and abs((p - parse_date(gold)).days) <= (q.get("tolerance_days") or 0) if kind == "boolean": p = parse_boolean(pred) return p is not None and p == bool(gold) return _same_text(pred, gold) def parse_citation(c: Any) -> str | None: """A citation as an evidence id. Accepted: {'table', 'report_id', 'seq'}, 'table:report_id:seq', 'reports:report_id', an activity id as the DDR tables write it ('15_9_F_4_2008_02_19:010') and a bare report id ('15_9_F_4_2008_02_19', read as the row of `reports`).""" if isinstance(c, dict): if "act_id" in c and "table" not in c: return parse_citation(c["act_id"]) if not c.get("table") or not c.get("report_id"): return None return evidence_id(c["table"], c["report_id"], c.get("seq")) if not isinstance(c, str): return None parts = c.strip().split(":") try: if len(parts) == 1 and _REPORT_ID.fullmatch(parts[0]): return evidence_id("reports", parts[0]) if len(parts) == 3: return evidence_id(parts[0], parts[1], int(parts[2])) if len(parts) == 2 and parts[1].isdigit() and _REPORT_ID.fullmatch(parts[0]): return evidence_id("activities", parts[0], int(parts[1])) if len(parts) == 2: return evidence_id(parts[0], parts[1]) except ValueError: return None return None def _report_level(eid: str) -> str: return "report:" + eid.split(":")[1] def score_citations(citations: list | None, evidence: list[dict], level: str = "row") -> dict: """Citation precision (cited rows that are evidence rows / cited rows) and recall (evidence groups with a cited row / evidence groups). None where the ratio has no denominator: precision without citations, recall for a question without evidence rows. With `level="report"` a citation and an evidence row match when they are in the same report, whatever the table and row: the lenient reading for answers that cite a report rather than a row. A citation that cannot be parsed counts as a cited row that is not evidence.""" if level not in ("row", "report"): raise ValueError(f"level must be 'row' or 'report', not {level!r}") parsed = [parse_citation(c) for c in (citations or [])] n_invalid = sum(c is None for c in parsed) cited = {c for c in parsed if c is not None} if level == "report": cited = {_report_level(c) for c in cited} groups: dict[int, set[str]] = {} for e in evidence: eid = evidence_id(e["table"], e["report_id"], e["seq"]) groups.setdefault(e["group"], set()).add(_report_level(eid) if level == "report" else eid) gold_ids = set().union(*groups.values()) if groups else set() n_cited = len(cited) + n_invalid return { "n_cited": n_cited, "citation_precision": len(cited & gold_ids) / n_cited if n_cited else None, "citation_recall": sum(bool(g & cited) for g in groups.values()) / len(groups) if groups else None, } def score(prediction: Any, gold: dict, citation_level: str = "row") -> dict: """Score one prediction against one question record (a row of questions.jsonl). `prediction` is {"answer": ..., "unit": optional, "citations": optional list} or the bare answer. Returns `correct` (type-aware match within the tolerance of the template), `abstained` (the prediction gives no answer), `fabricated` (a concrete answer to a question whose gold answer is "not reported"), the citation scores and, for a list answer, `list_precision` and `list_recall`. An abstention is correct only for an unanswerable question. """ if not (isinstance(prediction, dict) and ("answer" in prediction or "citations" in prediction)): prediction = {"answer": prediction} pred, unit = prediction.get("answer"), prediction.get("unit") kind = gold["answer_type"] answerable = gold.get("answerable", True) abstained = is_abstention(pred) if answerable and kind == "boolean" and parse_boolean(pred) is not None: abstained = False # "No such activity is recorded" answers a yes/no question out = {"correct": False, "abstained": abstained, "fabricated": False} out.update(score_citations(prediction.get("citations"), gold.get("evidence") or [], citation_level)) if not answerable: out["correct"] = out["abstained"] out["fabricated"] = not out["abstained"] return out if out["abstained"]: return out if kind == "list": items = pred if isinstance(pred, (list, tuple)) else re.split(r"\s*[;,]\s*|\s+and\s+", str(pred)) items = [i for i in items if not (isinstance(i, str) and not i.strip())] left = list(gold["answer"]) hits = 0 for item in items: for g in left: if _match_value(item, g, gold["item_type"], gold, unit): left.remove(g) hits += 1 break out["list_precision"] = hits / len(items) if items else 0.0 out["list_recall"] = hits / len(gold["answer"]) out["correct"] = hits == len(items) == len(gold["answer"]) return out out["correct"] = _match_value(pred, gold["answer"], kind, gold, unit) return out