Add M3-M4 baselines, C4 comparison and G2 report

Frozen feature tables for T1-T3, TF-IDF + logistic regression and DistilBERT
baselines with grouped splits, T4/C4 question answering (zero-shot, few-shot,
RAG, tool_only, agent), Qwen zero-shot T2, paired well-cluster bootstrap and
the G2 coverage report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 07:00:36 +00:00
parent 2b59d635ce
commit 59fa1f4d08
16 changed files with 1999 additions and 0 deletions

108
tests/test_m34.py Normal file
View File

@@ -0,0 +1,108 @@
from __future__ import annotations
import numpy as np
import pandas as pd
import pytest
pytest.importorskip("sklearn")
from sklearn.metrics import average_precision_score
from volve_dia import m34, paths
from volve_dia.m34_classify import model_inputs
from volve_dia.m34_qa import QueryTool, few_examples, qa_universe
from volve_dia.m34_report import QA_METRICS, binary_metric, qa_estimates, qa_summary, status
def test_cluster_weighted_ap_matches_sklearn_with_ties():
y = np.array([True, False, True, False, True, False])
scores = np.array([0.4, 0.4, 0.1, 0.2, 0.1, 0.1])
w = np.array([2, 2, 5, 0, 3, 3])
frame = pd.DataFrame({"target": y.astype(str), "score": scores})
assert binary_metric(frame)(w) == pytest.approx(average_precision_score(y, scores, sample_weight=w))
def test_masked_view_has_only_allowed_inputs():
frame = pd.DataFrame({"well": ["well"], "text_xml": ["Circulate"], "codes": ["9 - 8"],
"npt_b": [True], "last_activity": ["timestamp"], "witsml_x": [1.0]})
masked = model_inputs(frame, "masked", "xml")
assert masked.columns.tolist() == ["well", "witsml_x", "text"]
assert masked["text"].iat[0] == "Circulate"
assert model_inputs(frame, "unmasked", "xml")["text"].iat[0].endswith("9 - 8")
def test_few_shot_examples_exclude_held_out_development_well():
qs = [{"id": str(i), "well": well, "answer": i, "unit": "", "question": f"Q{i}", "answerable": True}
for i, well in enumerate(("A", "B", "C"))]
assert [x["question"] for x in few_examples(qs, qs[0], ["A", "B"], 2)] == ["Q1"]
assert not few_examples(qs, {"well": None}, ["A", "B"], 2)
def test_query_parameters_and_row_citations():
import duckdb
with duckdb.connect() as con:
con.execute("CREATE TABLE reports AS SELECT 'r' AS report_id, '15/9-F-1' AS wellbore, 10.0 AS md")
tool = QueryTool.__new__(QueryTool)
tool.con = con
tool.columns = {"reports": ["report_id", "wellbore", "md"]}
eq = {"column": "wellbore", "operator": "eq", "value": "15/9-F-1"}
base = {"table": "reports", "columns": ["md"], "filters": [eq]}
assert tool.run(base)[0]["citation"] == "reports:r"
assert tool.run(base | {"aggregate": "avg"})["result"] == 10
assert not tool.run(base | {"filters": [eq | {"value": "' OR true --"}]})
with pytest.raises(ValueError, match="Unknown column"):
tool.run(base | {"columns": ["bad column"]})
def test_qa_bootstrap_pairs_by_item_and_keeps_field_separate():
frame = pd.DataFrame({"well": ["A", "B"], "item": ["one", "two"], "family": ["lookup", "comparison"]})
for metric in QA_METRICS:
frame[metric] = [0.0, 1.0]
cfg = {"resamples": 10, "seed": 1, "level": 0.95}
assert qa_estimates(frame, cfg, True, frame)["correct"]["ci"] == [0.0, 0.0]
with pytest.raises(ValueError, match="Unpaired"):
qa_estimates(frame, cfg, True, frame.iloc[::-1])
field = frame.assign(well=pd.Series([None, None], dtype="str"))
assert qa_estimates(field, cfg, True)["correct"]["ci"] is None
other = field.set_axis([2, 3]).assign(correct=[1.0, 1.0])
paired = qa_estimates(field, cfg, True, other)["correct"]
assert paired["estimate"] == 0.5
assert paired["ci"] is None
with pytest.raises(ValueError, match="Unpaired"):
qa_estimates(field, cfg, True, other.assign(well=["A", None]))
def test_qa_coverage_requires_the_expected_question_ids():
qa = [{"id": "expected"}]
rows = [{"model": "qwen", "mode": "c4", "modality": source, "seed": 0, "item": item,
"scope": "well", "well": "A", "family": "lookup", "template": "lookup_1", "failed": False}
for source, item in [("xml", "expected"), ("ocr", "other")]]
frame = pd.DataFrame(rows).assign(**dict.fromkeys(QA_METRICS, 0.0))
ci = {"resamples": 10, "seed": 1, "level": 0.95}
results, contrasts, coverage = qa_summary(frame, qa, qa, set(), ci)
assert {x["modality"] for x in results} == {"xml"}
assert not contrasts
by_source = {run["modality"]: run for run in coverage}
assert by_source["ocr"]["n"] == by_source["ocr"]["expected"] == 1
assert not by_source["ocr"]["complete"]
gate = status(pd.DataFrame(), coverage, {"statistics": {"seeds": [0]}}, {})
assert ("qwen", "c4", "ocr", 0) in gate["missing_qa"]
assert ("qwen", "c4", "xml", 0) not in gate["missing_qa"]
@pytest.mark.data
def test_qa_c4_and_t3_feature_provenance():
root = paths.outputs_dir()
if not (root / "m34/features_t3.parquet").is_file():
pytest.skip("M3–M4 prepared outputs are absent")
protocol, _ = m34.configuration()
questions, paired, complete, flagged = qa_universe(root, protocol)
assert (len(questions), len(complete)) == (1662, 1752)
assert flagged <= {q["id"] for q in paired}
assert all(q["printed_in_render"] and q["answerable"] and
all(e["report_id"] in complete for e in q["evidence"]) for q in paired)
t3 = pd.read_parquet(root / "m34/features_t3.parquet")
assert len(t3) == 4894
for endpoint in ("last_activity", "last_report", "last_depth", "last_channel"):
if endpoint in t3:
assert (t3[endpoint].isna() | t3[endpoint].lt(t3["cutoff"])).all()