from __future__ import annotations import json import sqlite3 import numpy as np import pandas as pd import pytest from volve_dia import m5_errors as me KNOWN = {"15_9_F_14_2008_05_23"} @pytest.mark.parametrize("answer,unit,tadi,ext", [ ("3520", "m", True, True), ("3,520.5 m", "", True, True), ("1.48", "g/cm3", True, True), ("12", "hours", False, True), ("12 1/4", "in", False, True), ("3520", "mMD", False, True), ("3520 m MD", "", True, True), ("15/9-F-14", "", False, False), ("MAERSK INSPIRER", "", False, False), ("25", "%", True, True), ("40", "mm", False, False), ("2008-05-23", "", False, False)]) def test_has_measurement(answer, unit, tadi, ext): p = {"answer": answer, "unit": unit} assert me.has_measurement(p) is tadi assert me.has_measurement(p, me.EXTENDED_MEASUREMENT) is ext def test_ddr_reference_and_egs(): cited = {"answer": "3520", "unit": "m", "citations": ["reports:15_9_F_14_2008_05_23"]} assert me.has_ddr_reference(cited, KNOWN) assert me.has_ddr_reference({"citations": ["activities:15_9_F_14_2008_05_23:3"]}, KNOWN) assert not me.has_ddr_reference({"citations": ["reports:15_9_F_99_2008_05_23", "nonsense"]}, KNOWN) assert me.egs(cited, KNOWN) == pytest.approx(2 / 3) assert me.egs({"answer": None, "citations": []}, KNOWN) == 0 def row(**kw): base = {"correct": False, "failed": False, "answerable": True, "abstained": False, "wrong_wellbore": False, "n_citations": 1, "report_recall": 0.0} return base | kw @pytest.mark.parametrize("kw,expected", [ ({"correct": True}, "correct"), ({"failed": True}, "failed"), ({"answerable": False}, "answered_unanswerable"), ({"abstained": True, "wrong_wellbore": True}, "abstained"), ({"wrong_wellbore": True}, "wrong_wellbore"), ({"n_citations": 0}, "no_citation"), ({"report_recall": None}, "evidence_missed"), ({"report_recall": 0.5}, "wrong_with_evidence"), ({"answerable": False, "correct": True}, "correct")]) def test_error_class_first_rule_wins(kw, expected): assert me.error_class(row(**kw)) == expected def store(path, rows, inputs): con = sqlite3.connect(path) con.execute("CREATE TABLE metadata (provenance TEXT)") con.execute("INSERT INTO metadata VALUES (?)", (json.dumps({"inputs": inputs}),)) con.execute("CREATE TABLE predictions (mode TEXT, modality TEXT, seed INT, item TEXT, data TEXT)") con.executemany("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)", rows) con.commit() con.close() def test_load_complete_and_taxonomy(tmp_path): questions = {f"q{i}": {"well": f"W{i % 2}", "family": ("lookup", "aggregation")[i % 2], "template_id": "T", "scope": "single", "answer_type": "number", "answerable": i != 3} for i in range(4)} preds = [] for i in range(4): d = {"item": f"q{i}", "failed": False, "correct": i in (0, 3), "wrong_wellbore": i == 1, "report_recall": 0.0, "prediction": {"answer": None if i == 3 else "10", "unit": "m", "citations": ["reports:15_9_F_14_2008_05_23"]}} preds.append(("rag", "xml", 0, f"q{i}", json.dumps(d))) store(tmp_path / "a.sqlite", preds, {"x": "1"}) store(tmp_path / "b.sqlite", preds[:2], {"x": "1"}) with pytest.raises(ValueError, match="Stale"): me.load_predictions([(tmp_path / "a.sqlite", "m")], {"x": "2"}, questions, KNOWN) frame = me.load_predictions([(tmp_path / "a.sqlite", "m"), (tmp_path / "b.sqlite", "n")], {"x": "1"}, questions, KNOWN) kept, coverage = me.complete_runs(frame, lambda mode: set(questions)) assert set(kept["model"]) == {"m"} and [c["complete"] for c in coverage] == [True, False] assert list(kept.sort_values("item")["error_class"]) == ["correct", "wrong_wellbore", "evidence_missed", "correct"] assert kept.loc[kept["item"] == "q3", "egs"].item() == pytest.approx(1 / 3) tax = me.taxonomy(kept) macro = tax[tax["family"] == "macro"].iloc[0] assert macro["correct"] == pytest.approx((0.5 + 0.5) / 2) and macro["n"] == 4 assert macro["wrong_wellbore"] == pytest.approx((0 + 0.5) / 2) def test_spearman_bootstrap_and_h4(): rng = np.random.default_rng(0) n = 400 frame = pd.DataFrame({"well": rng.choice(list("ABCDEFGH"), n), "egs": rng.choice([0, 1 / 3, 2 / 3], n), "mode": "rag", "modality": "xml", "model": "m", "seed": 0, "answerable": True, "failed": False, "abstained": False}) frame["egs_ext"] = frame["egs"] frame["correct"] = rng.random(n) < 0.2 + 0.6 * frame["egs"] rows = me.rq4(frame, 200, 1) pooled = [r for r in rows if r["variant"] == "primary" and r["mode"] == "pooled"][0] assert pooled["rho"] > 0.3 and pooled["ci95"][0] < pooled["rho"] < pooled["ci95"][1] assert set(pooled["by_level"]) == {"0.000", "0.333", "0.667"} assert me.h4_reading(rows, "m")["reading"] == "not supported" assert me.spearman([0, 0, 0], [1, 0, 1]) is None