"""volve_dia.t4: template instantiation, drop rules, sampling, the scorer; and, with the data, the locked counts and the agreement of the SQL answers with the pandas implementation.""" import copy import importlib.util import json import duckdb import pytest from volve_dia import paths, t4 from volve_dia.names import well_of CONFIG = paths.REPO_ROOT / "configs" / "t4_templates.yaml" DDR = paths.REPO_ROOT / "outputs" / "ddr" needs_db = pytest.mark.skipif(not (DDR / "volve_ddr.duckdb").is_file(), reason="missing outputs/ddr/volve_ddr.duckdb") # ---------------------------------------------------------------------------------------------------------------------- # A small database and four templates: a header value with a missing case, a list, a tie, a sampled sum. # ---------------------------------------------------------------------------------------------------------------------- MINI = { "seed": 7, "templates": [ { "id": "T1_deepest", "family": "lookup", "tadi": {"category": 1}, "questions": ["Deepest depth of {wellbore}?", "How deep is {wellbore}?"], "slots": {"wellbore": {"type": "wellbore"}}, "slots_sql": "SELECT DISTINCT wellbore FROM reports ORDER BY 1", "answer_sql": "SELECT max(md) AS answer FROM reports WHERE wellbore = $wellbore", "evidence_sql": "SELECT 'reports' AS \"table\", report_id, NULL AS seq FROM reports WHERE wellbore = " "$wellbore AND md = (SELECT max(md) FROM reports WHERE wellbore = $wellbore)", "evidence_mode": "any", "on_null": "not_reported", "answer": {"type": "number", "unit": "m", "round": 1, "tolerance": {"abs": 1.0}}, "source": ["reports.md"], }, { "id": "T2_holes", "family": "lookup", "tadi": {"category": 1}, "questions": ["Hole sizes of {wellbore}?"], "slots": {"wellbore": {"type": "wellbore"}}, "slots_sql": "SELECT DISTINCT wellbore FROM reports WHERE diaHole IS NOT NULL ORDER BY 1", "answer_sql": "SELECT DISTINCT diaHole AS answer FROM reports WHERE wellbore = $wellbore " "AND diaHole IS NOT NULL ORDER BY 1 DESC", "evidence_sql": "SELECT 'reports' AS \"table\", report_id, NULL AS seq, diaHole AS grp FROM reports " "WHERE wellbore = $wellbore AND diaHole IS NOT NULL", "evidence_mode": "group", "answer": {"type": "list", "item_type": "number", "unit": "in", "tolerance": {"abs": 0.01}}, "source": ["reports.diaHole"], }, { "id": "T3_top_code", "family": "aggregation", "tadi": {"category": 2}, "questions": ["Which code has the most hours in {wellbore}?"], "slots": {"wellbore": {"type": "wellbore"}}, "slots_sql": "SELECT DISTINCT wellbore FROM activities ORDER BY 1", "answer_sql": "WITH h AS (SELECT code, sum(duration_h) AS h FROM activities WHERE wellbore = $wellbore " "GROUP BY 1) SELECT min(code) AS answer, CASE WHEN count(*) > 1 THEN 'tie' END AS " "drop_reason FROM h WHERE h = (SELECT max(h) FROM h)", "evidence_sql": "SELECT 'activities' AS \"table\", report_id, seq FROM activities WHERE wellbore = " "$wellbore AND code = (SELECT code FROM activities WHERE wellbore = $wellbore GROUP BY 1 " "ORDER BY sum(duration_h) DESC LIMIT 1)", "evidence_mode": "all", "answer": {"type": "enumeration", "choices": {"sql": "SELECT DISTINCT code FROM activities ORDER BY 1"}}, "source": ["activities.code"], }, { "id": "T4_hours", "family": "aggregation", "tadi": {"category": 2}, "questions": ["Hours of '{code}' in {wellbore}?"], "slots": {"wellbore": {"type": "wellbore"}, "code": {"type": "string"}}, "slots_sql": "SELECT DISTINCT wellbore, code FROM activities ORDER BY 1, 2", "answer_sql": "SELECT sum(duration_h) AS answer FROM activities WHERE wellbore = $wellbore " "AND code = $code", "evidence_sql": "SELECT 'activities' AS \"table\", report_id, seq FROM activities WHERE wellbore = " "$wellbore AND code = $code", "evidence_mode": "all", "sample": {"by": ["wellbore"], "n": 1}, "answer": {"type": "number", "unit": "h", "round": 2, "tolerance": {"abs": 0.25}}, "source": ["activities.duration_h"], }, ], } @pytest.fixture() def con(): c = duckdb.connect(":memory:") c.execute("CREATE TABLE reports (report_id VARCHAR, wellbore VARCHAR, md DOUBLE, diaHole DOUBLE)") c.execute("""INSERT INTO reports VALUES ('15_9_F_1_2013_08_01', '15/9-F-1', 1000.0, 17.5), ('15_9_F_1_2013_08_02', '15/9-F-1', 2500.5, 12.25), ('15_9_F_1_2013_08_03', '15/9-F-1', 2500.5, 12.25), ('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 3000.0, NULL), ('15_9_F_4_2008_02_19', '15/9-F-4', NULL, NULL)""") c.execute("CREATE TABLE activities (report_id VARCHAR, wellbore VARCHAR, seq BIGINT, code VARCHAR, " "duration_h DOUBLE)") c.execute("""INSERT INTO activities VALUES ('15_9_F_1_2013_08_01', '15/9-F-1', 0, 'drilling -- drill', 10.0), ('15_9_F_1_2013_08_01', '15/9-F-1', 1, 'interruption -- repair', 2.5), ('15_9_F_1_2013_08_02', '15/9-F-1', 0, 'drilling -- drill', 4.0), ('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 0, 'drilling -- drill', 6.0), ('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 1, 'drilling -- trip', 6.0)""") yield c c.close() @pytest.fixture() def mini(): cfg = copy.deepcopy(MINI) for t in cfg["templates"]: t4.validate_template(t) return cfg def by_template(questions): out = {} for q in questions: out.setdefault(q["template_id"], []).append(q) return out def test_instantiation(con, mini): questions, outcomes, summary = t4.build(con, mini) q = by_template(questions) deepest = {x["wellbore"]: x for x in q["T1_deepest"]} assert deepest["15/9-F-1"]["answer"] == 2500.5 and deepest["15/9-F-1"]["answer_text"] == "2500.5 m" assert deepest["15/9-F-1"]["question"] in ("Deepest depth of 15/9-F-1?", "How deep is 15/9-F-1?") assert (deepest["15/9-F-1"]["unit"], deepest["15/9-F-1"]["tolerance_abs"]) == ("m", 1.0) assert deepest["15/9-F-1 A"]["well"] == "15/9-F-1" and deepest["15/9-F-1 A"]["wells"] == ["15/9-F-1"] # evidence mode any: the two reports that state the deepest depth are one group assert [(e["report_id"], e["seq"], e["group"]) for e in deepest["15/9-F-1"]["evidence"]] == [ ("15_9_F_1_2013_08_02", None, 0), ("15_9_F_1_2013_08_03", None, 0)] # the stored SQL is the executed SQL, literals written in assert deepest["15/9-F-1 A"]["sql"] == "SELECT max(md) AS answer FROM reports WHERE wellbore = '15/9-F-1 A'" assert con.execute(deepest["15/9-F-1 A"]["sql"]).fetchone()[0] == 3000.0 # no depth in any report of 15/9-F-4: an unanswerable question, without evidence assert deepest["15/9-F-4"]["answer"] == t4.NOT_REPORTED and not deepest["15/9-F-4"]["answerable"] assert deepest["15/9-F-4"]["evidence"] == [] # a list answer with one evidence group per element holes = q["T2_holes"][0] assert holes["answer"] == [17.5, 12.25] and holes["answer_text"] == "17.5, 12.25 in" assert holes["n_evidence"] == 3 and holes["n_evidence_groups"] == 2 assert summary["questions"] == len(questions) and summary["unanswerable"] == 1 assert len({x["id"] for x in questions}) == len(questions) def test_drops_and_sampling(con, mini): questions, outcomes, summary = t4.build(con, mini) q = by_template(questions) # 15/9-F-1 A: two codes with 6 h each, a tie, dropped and counted assert [x["wellbore"] for x in q["T3_top_code"]] == ["15/9-F-1"] assert q["T3_top_code"][0]["answer"] == "drilling -- drill" assert q["T3_top_code"][0]["choices"] == ["drilling -- drill", "drilling -- trip", "interruption -- repair"] assert summary["per_template"]["T3_top_code"]["dropped"] == {"tie": 1} assert summary["dropped"] == {"tie": 1} and summary["dropped_total"] == 1 # four (wellbore, code) candidates, one kept per wellbore, the same ones on every run hours = summary["per_template"]["T4_hours"] assert (hours["candidates"], hours["questions"], hours["not_sampled"]["answerable"]) == (4, 2, 2) again, _, _ = t4.build(con, mini) assert [x["id"] for x in again] == [x["id"] for x in questions] # every answerable question has evidence rows; the sums are over all rows of the code assert all(x["evidence"] for x in questions if x["answerable"]) for x in q["T4_hours"]: rows = con.execute(x["evidence_sql"]).fetchall() assert len(rows) == x["n_evidence"] == x["n_evidence_groups"] def test_null_answer_is_dropped_without_on_null(con, mini): del mini["templates"][0]["on_null"] _, outcomes, summary = t4.build(con, mini) assert summary["per_template"]["T1_deepest"]["dropped"] == {"null_answer": 1} assert [o.status for o in outcomes["T1_deepest"]] == ["ok", "ok", "drop"] def test_rendering(): assert t4.format_inch(12.25) == '12 1/4" (12.25 in)' and t4.format_inch(36.0) == '36"' assert t4.format_inch(13.375) == '13 3/8" (13.375 in)' and t4.format_inch(9.875) == '9 7/8" (9.875 in)' assert t4.format_number(3520.0) == "3520" and t4.format_number(1.48) == "1.48" sql = t4.render_sql("SELECT 1 WHERE w = $w AND d = $d AND x = $x", {"w": "15/9-F-1 A", "d": 12.25, "x": "o'k"}) assert sql == "SELECT 1 WHERE w = '15/9-F-1 A' AND d = 12.25 AND x = 'o''k'" assert t4.evidence_id("activities", "15_9_F_4_2008_02_19", 10) == "activities:15_9_F_4_2008_02_19:10" assert t4.evidence_id("reports", "15_9_F_4_2008_02_19") == "reports:15_9_F_4_2008_02_19" def test_validate_template(mini): t = copy.deepcopy(mini["templates"][0]) t["questions"] = ["Depth of {well}?"] with pytest.raises(t4.TemplateError, match="undeclared slots"): t4.validate_template(t) t = copy.deepcopy(mini["templates"][0]) t["answer"] = {"type": "number", "unit": "m"} with pytest.raises(t4.TemplateError, match="tolerance"): t4.validate_template(t) t = copy.deepcopy(mini["templates"][0]) t["answer_sql"] = "SELECT max(md) AS answer FROM reports WHERE wellbore = $name" with pytest.raises(t4.TemplateError, match="undeclared parameters"): t4.validate_template(t) t = copy.deepcopy(mini["templates"][3]) t["negatives"] = {"n": 2} with pytest.raises(t4.TemplateError, match="on_null"): t4.validate_template(t) # ---------------------------------------------------------------------------------------------------------------------- # Scorer # ---------------------------------------------------------------------------------------------------------------------- def gold(answer, kind, evidence=(), **kw): q = {"answer": answer, "answer_type": kind, "answerable": True, "evidence": list(evidence), "unit": None, "tolerance_abs": None, "tolerance_rel": None, "tolerance_days": 0, "item_type": None} q.update(kw) return q def test_tolerance(): assert t4.within_tolerance(3520.9, 3520.0, abs_tol=1.0) and not t4.within_tolerance(3521.1, 3520.0, abs_tol=1.0) assert t4.within_tolerance(13.7, 13.45, rel_tol=0.02) and not t4.within_tolerance(13.8, 13.45, rel_tol=0.02) assert t4.within_tolerance(11, 11, abs_tol=0) and not t4.within_tolerance(12, 11, abs_tol=0) assert t4.within_tolerance(1.0, 0.5, abs_tol=0.5, rel_tol=0.01) # the larger of the two limits applies def test_score_number(): q = gold(3520.0, "number", unit="m", tolerance_abs=1.0) assert t4.score(3520.4, q)["correct"] and t4.score("3,520 m", q)["correct"] and t4.score("3520,4", q)["correct"] assert not t4.score(3522, q)["correct"] and not t4.score("deep", q)["correct"] assert t4.score({"answer": 11548.6, "unit": "ft"}, q)["correct"] # 3520.0 m assert t4.score("11548.6 ft", q)["correct"] and t4.score("3520 metres", q)["correct"] assert not t4.score({"answer": 3520, "unit": "ft"}, q)["correct"] and not t4.score("3520 ft", q)["correct"] assert not t4.score({"answer": 3520, "unit": "h"}, q)["correct"] # another dimension rop = gold(13.45, "number", unit="m/h", tolerance_rel=0.02) assert t4.score("13.6 m/h", rop)["correct"] and not t4.score(14.0, rop)["correct"] count = gold(11.0, "number", unit="reports", tolerance_abs=0) assert t4.score({"answer": 11, "unit": "days"}, count)["correct"] and not t4.score(12, count)["correct"] size = gold(12.25, "number", unit="in", tolerance_abs=0.01) assert t4.score('12 1/4"', size)["correct"] and t4.score("12.25 in", size)["correct"] def test_score_date_string_boolean(): d = gold("1997-11-27", "date") assert t4.score("1997-11-27", d)["correct"] and t4.score("27.11.1997", d)["correct"] assert t4.score("27 November 1997", d)["correct"] and t4.score("1997-11-27T14:00:00+01:00", d)["correct"] assert not t4.score("1997-11-28", d)["correct"] and not t4.score("November", d)["correct"] assert t4.score("1997-11-28", gold("1997-11-27", "date", tolerance_days=1))["correct"] rig = gold("MÆRSK INSPIRER", "string") assert t4.score("Mærsk Inspirer.", rig)["correct"] and not t4.score("Byford Dolphin", rig)["correct"] wb = gold("15/9-F-1 B", "enumeration", choices=["15/9-F-1", "15/9-F-1 B"]) assert t4.score("NO 15/9-F-1 B", wb)["correct"] and t4.score("15_9_F_1_B", wb)["correct"] assert not t4.score("15/9-F-1", wb)["correct"] code = gold("interruption -- fish", "enumeration") assert t4.score("Interruption - fish", code)["correct"] and not t4.score("interruption -- repair", code)["correct"] yes, no = gold(True, "boolean"), gold(False, "boolean") assert t4.score("Yes, on 2008-11-14.", yes)["correct"] and t4.score(True, yes)["correct"] assert not t4.score("no", yes)["correct"] and not t4.score("maybe", yes)["correct"] s = t4.score("No such activity is recorded.", no) # a 'no', not an abstention assert s["correct"] and not s["abstained"] assert t4.score("n/a", no)["abstained"] and not t4.score("n/a", no)["correct"] def test_score_list(): q = gold([36.0, 26.0, 17.5], "list", item_type="number", unit="in", tolerance_abs=0.01) s = t4.score([17.5, 36, 26], q) assert s["correct"] and s["list_precision"] == s["list_recall"] == 1.0 assert t4.score('36", 26", 17 1/2"', q)["correct"] s = t4.score([36, 26], q) assert not s["correct"] and s["list_precision"] == 1.0 and s["list_recall"] == pytest.approx(2 / 3) s = t4.score([36, 26, 17.5, 12.25], q) assert not s["correct"] and s["list_precision"] == 0.75 and s["list_recall"] == 1.0 assert not t4.score([36, 36, 26], q)["correct"] # a gold element is matched once def test_score_unanswerable(): q = gold(t4.NOT_REPORTED, "date", answerable=False) for pred in (None, "", "Not reported", "N/A", "no such activity in the reports", "unknown"): s = t4.score(pred, q) assert s["correct"] and s["abstained"] and not s["fabricated"] s = t4.score("1997-11-27", q) assert not s["correct"] and s["fabricated"] and not s["abstained"] answerable = gold(3520.0, "number", unit="m", tolerance_abs=1.0) s = t4.score("not reported", answerable) assert not s["correct"] and s["abstained"] and not s["fabricated"] def test_score_citations(): def rows(*specs): return [{"table": t, "report_id": r, "seq": s, "group": g} for t, r, s, g in specs] rid = "15_9_F_4_2008_02_19" need_all = rows(("activities", rid, 10, 0), ("activities", rid, 11, 1), ("reports", rid, None, 2)) s = t4.score_citations([f"activities:{rid}:10", f"{rid}:011", {"table": "reports", "report_id": rid}], need_all) assert s == {"n_cited": 3, "citation_precision": 1.0, "citation_recall": 1.0} s = t4.score_citations([f"activities:{rid}:10", f"activities:{rid}:99"], need_all) assert s["citation_precision"] == 0.5 and s["citation_recall"] == pytest.approx(1 / 3) any_one = rows(("reports", rid, None, 0), ("reports", "15_9_F_4_2008_02_20", None, 0)) assert t4.score_citations([f"reports:{rid}"], any_one)["citation_recall"] == 1.0 assert t4.score_citations([rid], any_one)["citation_precision"] == 1.0 # a bare report id grouped = rows(("casings", rid, 0, 0), ("casings", rid, 1, 0), ("casings", rid, 2, 1)) assert t4.score_citations([f"casings:{rid}:1"], grouped)["citation_recall"] == 0.5 none = t4.score_citations([], need_all) assert none == {"n_cited": 0, "citation_precision": None, "citation_recall": 0.0} assert t4.score_citations([f"reports:{rid}"], [])["citation_precision"] == 0.0 assert t4.score_citations([f"reports:{rid}"], [])["citation_recall"] is None assert t4.score_citations(["not a citation"], need_all)["citation_precision"] == 0.0 # report level: any row of the report counts s = t4.score_citations([f"fluids:{rid}:0"], need_all, level="report") assert s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0 q = gold(3245.0, "number", evidence=need_all[:1], unit="m", tolerance_abs=1.0) s = t4.score({"answer": "3245 m", "citations": [f"{rid}:010"]}, q) assert s["correct"] and s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0 # ---------------------------------------------------------------------------------------------------------------------- # The configuration, and the build on the DDR tables # ---------------------------------------------------------------------------------------------------------------------- def test_config_is_valid(): from volve_dia import t4_pandas cfg = t4.load_config(CONFIG) ids = [t["id"] for t in cfg["templates"]] assert len(ids) == len(set(ids)) == 39 assert {t["family"] for t in cfg["templates"]} == set(t4.FAMILIES) assert {t["answer"]["type"] for t in cfg["templates"]} == set(t4.ANSWER_TYPES) assert set(ids) == set(t4_pandas.TEMPLATES) # every template has its pandas twin assert [t["id"] for t in cfg["disabled"]] == [ "W01_rop_section_witsml", "W02_max_inclination_trajectory", "W03_formation_at_first_event_picks", "W04_best_bha_run", "W05_parameters_in_formation"] for t in cfg["templates"]: assert t["tadi"].get("fit") in ("direct", "partial", "none") and t.get("caveats") assert t["tadi"].get("category") in (None, 1, 2, 3, 4, 5, 6) @pytest.fixture(scope="module") def built(): from volve_dia import t4_pandas cfg = t4.load_config(CONFIG) with t4.connect(DDR / "volve_ddr.duckdb") as con: questions, outcomes, summary = t4.build(con, cfg) return cfg, questions, outcomes, summary, t4_pandas.Tables(DDR) def script(): spec = importlib.util.spec_from_file_location("t4_questions", paths.REPO_ROOT / "scripts" / "08_t4_questions.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module @pytest.mark.data @needs_db def test_locked_counts(built): _, questions, _, summary, _ = built expected = script().EXPECTED got = {k: summary[k] for k in expected if k != "per_template_questions"} got["per_template_questions"] = {tid: t["questions"] for tid, t in summary["per_template"].items()} assert got == expected assert len(questions) == 1662 and len({q["id"] for q in questions}) == 1662 assert len({q["question"] for q in questions}) == 1662 @pytest.mark.data @needs_db def test_questions_are_well_formed(built): _, questions, _, _, _ = built for q in questions: if q["scope"] != "field": assert q["well"] == well_of(q["wellbore"]) and q["wellbore"] in q["wellbores"] assert q["wells"] == sorted({well_of(w) for w in q["wellbores"]}) assert "{" not in q["question"] and "$" not in q["sql"] and "$" not in q["evidence_sql"] if not q["answerable"]: assert q["answer"] == t4.NOT_REPORTED and not q["evidence"] elif not (q["answer_type"] == "boolean" and q["answer"] is False): assert q["evidence"], q["id"] if q["answer_type"] == "enumeration" and q["answerable"]: assert q["answer"] in q["choices"] assert sum(q["scope"] == "pair" for q in questions) == 92 assert all(len(q["wells"]) == 1 for q in questions if q["scope"] == "pair") # same-well pairs only assert all(len(q["wells"]) == 11 and len(q["wellbores"]) == 26 for q in questions if q["scope"] == "field") assert sum(not q["printed_in_render"] for q in questions) == 215 @pytest.mark.data @needs_db def test_stored_sql_reproduces_answers(built): cfg, questions, _, _, _ = built specs = {t["id"]: t for t in cfg["templates"]} with t4.connect(DDR / "volve_ddr.duckdb") as con: for q in questions[::7]: o = t4.run_instance(con, specs[q["template_id"]], q["slots"]) assert o.sql == q["sql"] and o.answer == q["answer"] and o.evidence == q["evidence"] @pytest.mark.data @needs_db def test_sql_agrees_with_pandas(built): from volve_dia import t4_pandas cfg, _, outcomes, _, tables = built check = t4_pandas.crosscheck(cfg, outcomes, tables) assert check["total"]["instances"] == 3915 and check["total"]["agree"] == 3915 assert check["total"]["slot_differences"] == 0 and check["total"]["templates_in_full_agreement"] == 39 @pytest.mark.data @needs_db def test_crosscheck_detects_a_wrong_template(built): """The comparison is not vacuous: a template whose SQL takes the shallowest depth, or whose evidence SQL misses rows, disagrees with the pandas implementation.""" from volve_dia import t4_pandas cfg, _, _, _, tables = built wrong = copy.deepcopy(next(t for t in cfg["templates"] if t["id"] == "L03_deepest_md")) wrong["answer_sql"] = wrong["answer_sql"].replace("max(md)", "min(md)") loose = copy.deepcopy(next(t for t in cfg["templates"] if t["id"] == "A06_hours_per_code")) loose["evidence_sql"] += " AND seq > 0" with t4.connect(DDR / "volve_ddr.duckdb") as con: outcomes = {t["id"]: t4.run_template(con, t) for t in (wrong, loose)} check = t4_pandas.crosscheck({"templates": [wrong, loose]}, outcomes, tables) assert check["per_template"]["L03_deepest_md"]["answer"] > 0 assert check["per_template"]["A06_hours_per_code"]["evidence"] > 0 assert check["per_template"]["A06_hours_per_code"]["answer"] == 0 @pytest.mark.data @needs_db def test_gold_answers_score_as_correct(built): _, questions, _, _, _ = built result = script().self_score(questions) assert result == {"questions": 1662, "correct": 1662, "wrong": []} @pytest.mark.data @needs_db def test_outputs_match_the_build(built): _, questions, _, summary, _ = built out = paths.REPO_ROOT / "outputs" / "t4" if not (out / "questions.jsonl").is_file(): pytest.skip("outputs/t4 not built: run scripts/08_t4_questions.py") stored = t4.read_jsonl(out / "questions.jsonl") assert stored == json.loads(json.dumps(questions)) assert json.loads((out / "summary.json").read_text(encoding="utf-8"))["questions"] == summary["questions"]