"""Generate automatic results, coverage and paired whole-well confidence intervals.""" from __future__ import annotations import json import sqlite3 from contextlib import closing import numpy as np import pandas as pd from . import m2, m34 from .m34_classify import prediction_rows from .m34_qa import C4_MODES, MODES, qa_universe CLS_KEYS = ["task", "definition", "mode", "split", "method", "modality"] QA_KEYS = ["model", "mode", "modality"] QA_METRICS = ("correct", "report_precision", "report_recall", "row_precision", "row_recall", "fabricated", "wrong_wellbore", "abstention") def binary_metric(frame): y = frame["target"].eq("True").to_numpy() scores = frame["score"].to_numpy() order = np.argsort(-scores, kind="stable") end = np.r_[np.flatnonzero(np.diff(scores[order])), len(order) - 1] truth = y[order] def ap(weights): w = weights[order] total = w[truth].sum() if not total: return np.nan positives = np.cumsum(w * truth)[end] seen = np.cumsum(w)[end] precision = np.divide(positives, seen, out=np.zeros(len(seen)), where=seen > 0) gains = np.diff(positives, prepend=0) return float(gains @ precision / total) return ap def class_metrics(frame): if frame["task"].iat[0] == "t1": correct = frame["target"].eq(frame["prediction"]).to_numpy() return {"accuracy": lambda w: w @ correct / w.sum()} metrics = {"pr_auc_ap": binary_metric(frame)} if frame["task"].iat[0] == "t3": y = frame["target"].eq("True").to_numpy() p = frame["prediction"].eq("True").to_numpy() metrics["interval_iou"] = lambda w: m34.interval_overlap(y, p, w) return metrics def valid_checksum(meta, expected, file): if not meta.is_file() or m2.read_json(meta)["inputs"] != expected: raise ValueError(f"Missing or stale provenance for {file}.") def load_classification(out, digests): pieces = [] for path in sorted(out.glob("classical_*.parquet")) + sorted((out / "distilbert").rglob("*.parquet")): meta = path.with_suffix(".json") if not meta.is_file(): continue # The writer commits metadata after the prediction file. valid_checksum(meta, digests, path) pieces.append(pd.read_parquet(path)) pieces.extend(load_t2_llm(out, digests)) if not pieces: return pd.DataFrame() frame = pd.concat(pieces, ignore_index=True) if frame.duplicated(CLS_KEYS + ["seed", "item"]).any(): raise ValueError("Duplicate classification predictions.") return frame T2_LLM_SOURCES = (("qwen_zero_shot", "t2_llm/qwen.sqlite"),) V2_T2_MODELS = {"vai-deepseek-v4-1-flash": "vai_deepseek_zero_shot"} V2_QA_MODELS = ("vai-deepseek-v4-1-flash",) def read_t2_scores(db, digests, path, v2=False): with closing(sqlite3.connect(f"{db.resolve().as_uri()}?mode=ro", uri=True)) as con: meta = json.loads(con.execute("SELECT provenance FROM metadata").fetchone()[0]) if meta["inputs"] != digests or meta["features_sha256"] != m2.digest(path): raise ValueError("T2 LLM checkpoint inputs differ.") return pd.read_sql("SELECT * FROM predictions", con) def load_t2_llm(out, digests): path = out / "features_t2.parquet" sources = [(method, out / rel) for method, rel in T2_LLM_SOURCES] for model, method in V2_T2_MODELS.items(): sources += [(method, db) for db in sorted((out / "v2/t2_llm" / model).glob("rep*.sqlite"))] sources = [(method, db) for method, db in sources if db.is_file()] if not sources: return [] features = pd.read_parquet(path, columns=["item", "well", "wellbore", "npt_a", "npt_b", "cause_b"]) runs = [] for method, db in sources: scores = read_t2_scores(db, digests, path) if not scores["item"].isin(features["item"]).all(): raise ValueError("T2 LLM checkpoint contains unknown activities.") scores = scores.merge(features, on="item", validate="many_to_one") for seed, data in scores.groupby("seed"): for definition in ("a", "b"): probabilities = data[definition].to_numpy() run = prediction_rows(data, "t2", f"npt_{definition}", definition, "masked", "well", method, "xml", probabilities >= 0.5, probabilities, int(seed)) runs.append(run.assign(failed=data["error"].notna().to_numpy())) return runs def load_qa(out, digests): pieces = [] dbs = [(db, db.stem) for db in sorted((out / "qa").glob("*.sqlite"))] dbs += [(db, db.parent.name) for db in sorted((out / "v2/qa").glob("*/rep*.sqlite"))] for db, model in dbs: with closing(sqlite3.connect(f"{db.resolve().as_uri()}?mode=ro", uri=True)) as con: meta = json.loads(con.execute("SELECT provenance FROM metadata").fetchone()[0]) if meta["inputs"] != digests: raise ValueError(f"Stale T4 provenance for {db}.") rows = con.execute(""" SELECT mode, modality, seed, item, json_remove(data, '$.prediction', '$.retrieved', '$.trace') FROM predictions """) for mode, modality, seed, item, data in rows: record = json.loads(data) if record["item"] != item: raise ValueError(f"T4 prediction does not match its checkpoint key in {db}.") pieces.append(record | {"model": model, "mode": mode, "modality": modality, "seed": seed}) return pd.DataFrame(pieces) def result_rows(frame, keys, expected): return {"rows": len(frame), "expected": expected, "complete": len(frame) == expected, **dict(zip(keys[0], keys[1]))} def classification_summary(frame, sizes, ci): rows, pairs = [], [] if frame.empty: return rows, pairs for keys, run in frame.groupby(CLS_KEYS + ["seed"], sort=True): task, definition, mode, split, method, modality, seed = keys subsets = [("all", run)] if task == "t1": subsets = list(run.groupby("subset", sort=True)) if task == "t2" and definition == "b": subsets.append(("without_sidetrack", run[run["cause_b"].ne("sidetrack")])) for subset, selected in subsets: base = result_rows(selected, (CLS_KEYS + ["seed"], keys), sizes[task, modality, subset]) base["subset"] = subset base["failed"] = int(selected["failed"].eq(True).sum()) if "failed" in selected else 0 if base["complete"] and len(selected): base["metrics"] = {k: m34.confidence(selected, metric, ci) for k, metric in class_metrics(selected).items()} rows.append(base) for keys, selected in frame[frame["split"].eq("well")].groupby(["task", "definition", "method", "seed"]): task, definition, method, seed = keys xml = selected[selected["modality"].eq("xml")] masked, exposed = [xml[xml["mode"].eq(mode)] for mode in ("masked", "unmasked")] if len(masked) == len(exposed) == sizes[task, "xml", "all"]: pairs.extend(class_delta(masked, exposed, ci, keys, "unmasked_minus_masked", "all")) for side in ("with_date_flags", "without_date_flags"): ocr = selected[selected["modality"].eq("ocr")] ocr_mask = ocr["item"].isin(masked.loc[masked["c4"].eq(True), "item"]) if len(ocr) else [] ocr = ocr.loc[ocr_mask] if len(ocr) else ocr if not len(ocr) or len(ocr) != sizes[task, "ocr", "all"]: continue xml_c4 = masked[masked["item"].isin(ocr["item"])] if side == "without_date_flags": xml_c4 = xml_c4[xml_c4["date_flag"].eq(False)] ocr = ocr[ocr["date_flag"].eq(False)] subsets = ("published", "filled") if task == "t1" else ("all",) for subset in subsets: pairs.extend(class_delta(xml_c4[xml_c4["subset"].eq(subset)], ocr[ocr["subset"].eq(subset)], ci, keys, "ocr_minus_xml", f"{subset}/{side}")) for keys, selected in frame[frame["modality"].eq("xml")].groupby(["task", "mode", "split", "method", "seed"]): task, mode, split, method, seed = keys if task == "t1": continue a, b = [selected[selected["definition"].eq(d)] for d in ("a", "b")] if len(a) == len(b) == sizes[task, "xml", "all"]: pairs.extend(class_delta(a, b, ci, (task, "b", method, seed), "definition_b_minus_a", f"{mode}/{split}")) t2 = frame[(frame["task"].eq("t2") & frame["mode"].eq("masked") & frame["split"].eq("well") & frame["modality"].eq("xml"))] for definition, data in t2.groupby("definition"): classical = data[data["method"].eq("tfidf_logistic")] for (method, seed), llm in data[data["method"].str.endswith("_zero_shot")].groupby(["method", "seed"]): if len(llm) == len(classical) == sizes["t2", "xml", "all"]: label = method.removesuffix("_zero_shot") pairs.extend(class_delta(classical, llm, ci, ("t2", definition, method, seed), f"{label}_minus_tfidf", "all")) for keys, data in frame[frame["modality"].eq("xml")].groupby(["task", "definition", "method", "seed", "mode"]): task, definition, method, seed, mode = keys well, bore = [data[data["split"].eq(split)] for split in ("well", "wellbore")] if len(well) == len(bore) == sizes[task, "xml", "all"]: groups = (list(well["subset"].unique()) if task == "t1" else ["all"]) for subset in groups: pairs.extend(class_delta(well[well["subset"].eq(subset)], bore[bore["subset"].eq(subset)], ci, (task, definition, method, seed), "wellbore_minus_well", f"{mode}/{subset}")) return rows, pairs def class_delta(left, right, ci, keys, contrast, subset): if not len(left) or set(left["item"]) != set(right["item"]): raise ValueError(f"Unpaired classification contrast: {contrast} / {keys}") left, right = [x.sort_values("item") for x in (left, right)] if not np.array_equal(left["well"], right["well"]): raise ValueError("Inconsistent classification clusters.") task, definition, method, seed = keys a, b = class_metrics(left), class_metrics(right) return [{"task": task, "definition": definition, "method": method, "seed": seed, "contrast": contrast, "subset": subset, "metric": k, **m34.confidence(left, lambda w: b[k](w) - a[k](w), ci)} for k in a] def qa_estimates(frame, ci, macro, other=None): """Obtain paired rates from well-by-family sufficient statistics.""" if not len(frame): return {} if other is not None and (not np.array_equal(frame["item"], other["item"]) or not frame["well"].reset_index(drop=True).equals(other["well"].reset_index(drop=True))): raise ValueError("Unpaired T4 contrast.") wells, names = pd.factorize(frame["well"].fillna("__field__"), sort=True) families = pd.factorize(frame["family"], sort=True)[0] if macro else np.zeros(len(frame), dtype=int) n_wells, n_families = len(names), 1 + families.max() rng = np.random.default_rng(ci["seed"]) draws = (rng.multinomial(n_wells, np.full(n_wells, 1 / n_wells), size=ci["resamples"]) if n_wells > 1 else np.empty((0, n_wells), dtype=int)) weights = np.vstack([np.ones(n_wells, dtype=int), draws]) def rates(values): valid = np.isfinite(values) keys = wells * n_families + families n = np.bincount(keys, weights=valid, minlength=n_wells*n_families).reshape(n_wells, n_families) total = np.bincount(keys, weights=np.where(valid, values, 0), minlength=n_wells*n_families).reshape(n_wells, n_families) num, den = weights @ total, weights @ n means = np.divide(num, den, out=np.full(num.shape, np.nan), where=den != 0) finite = np.isfinite(means).sum(axis=1) return np.divide(np.nansum(means, axis=1), finite, out=np.full(len(finite), np.nan), where=finite != 0) estimates = {} for column in QA_METRICS: vals = frame[column].to_numpy(dtype=float, na_value=np.nan) result = rates(vals) if other is not None: result = rates(other[column].to_numpy(dtype=float, na_value=np.nan)) - result draws = result[1:][np.isfinite(result[1:])] alpha = (1 - ci["level"]) / 2 estimates[column] = {"estimate": float(result[0]) if np.isfinite(result[0]) else None, "ci": np.quantile(draws, [alpha, 1-alpha]).tolist() if len(draws) else None, "n_valid": int(np.isfinite(vals).sum()), "finite_resamples": len(draws)} return estimates def qa_summary(frame, questions, paired, blocked, ci): rows, contrasts, coverage = [], [], [] if frame.empty: return rows, contrasts, coverage paired_ids = {q["id"] for q in paired} qa_cases = {"c4": paired_ids, "c4_clean": paired_ids - blocked} all_ids = {q["id"] for q in questions} complete_cases = set() for keys, run in frame.groupby(QA_KEYS + ["seed"], sort=True): model, mode, source, seed = keys expected = qa_cases.get(mode, all_ids) case = dict(zip(QA_KEYS + ["seed"], keys)) complete = len(run) == len(expected) and set(run["item"]) == expected counts = case | {"n": len(run), "expected": len(expected), "failed": int(run["failed"].sum()), "complete": complete} coverage.append(counts) if not complete: continue complete_cases.add(keys) subsets = {"well": run[run["scope"].ne("field")], "field": run[run["scope"].eq("field")]} if mode == "c4": subsets["well_without_date_flags"] = subsets["well"][~subsets["well"]["item"].isin(blocked)] subsets["field_without_date_flags"] = subsets["field"][~subsets["field"]["item"].isin(blocked)] elif mode not in C4_MODES: subsets["xml_only_well"] = subsets["well"][~subsets["well"]["printed"]] subsets["xml_only_field"] = subsets["field"][~subsets["field"]["printed"]] subsets["printed_well"] = subsets["well"][subsets["well"]["printed"]] for name, selected in subsets.items(): if selected.empty: continue for average in ("macro_families", "micro"): rows.append(case | {"subset": name, "average": average, "n": len(selected), "metrics": qa_estimates(selected, ci, average == "macro_families")}) for template, block in selected.groupby("template"): rows.append(case | {"subset": name, "average": "template", "template": template, "n": len(block), "metrics": qa_estimates(block, ci, False)}) for (model, seed), block in frame.groupby(["model", "seed"], sort=True): candidates = { "agent_minus_rag": (("rag", "xml"), ("agent", "xml")), "agent_minus_tool_only": (("tool_only", "xml"), ("agent", "xml")), "rag_minus_zero_shot": (("zero_shot", "xml"), ("rag", "xml")), "few_shot_minus_zero_shot": (("zero_shot", "xml"), ("few_shot", "xml")), "ocr_minus_xml": (("c4", "xml"), ("c4", "ocr")), "html_minus_xml": (("c4", "xml"), ("c4", "html")), "ocr_minus_html": (("c4", "html"), ("c4", "ocr")), "ocr_minus_xml_clean": (("c4_clean", "xml"), ("c4_clean", "ocr")), "html_minus_xml_clean": (("c4_clean", "xml"), ("c4_clean", "html")), "ocr_minus_html_clean": (("c4_clean", "html"), ("c4_clean", "ocr")), } for name, (left, right) in candidates.items(): if (model, *left, seed) not in complete_cases or (model, *right, seed) not in complete_cases: continue pair = [block[block["mode"].eq(mode) & block["modality"].eq(source)].sort_values("item") for mode, source in (left, right)] subsets = {"well": [x[x["scope"].ne("field")] for x in pair], "field": [x[x["scope"].eq("field")] for x in pair]} if left[0] == "c4": subsets |= {f"{key}_without_date_flags": [x[~x["item"].isin(blocked)] for x in p] for key, p in list(subsets.items())} for subset, (a, b) in subsets.items(): if a.empty: continue contrasts.append({"model": model, "seed": int(seed), "contrast": name, "subset": subset, "n": len(a), "metrics": qa_estimates(a, ci, True, b)}) return rows, contrasts, coverage def status(classification, coverage, protocol, sizes): """Every required method, seed and condition requires full coverage before G2 can pass.""" required_cls = set() for task in ("t1", "t2", "t3"): defs = [("section", "masked")] if task == "t1" else [(d, m) for d in ("a", "b") for m in ("masked", "unmasked")] for definition, mode in defs: for split in ("well", "wellbore"): for method, seeds in (("tfidf_logistic", [-1]), ("distilbert", protocol["statistics"]["seeds"])): for seed in seeds: required_cls.add((task, definition, mode, split, method, "xml", seed)) if mode == "masked": methods = ["majority", "comment_length", "lexicon"] if task == "t2" else ["majority"] required_cls.update((task, definition, mode, split, method, "xml", -1) for method in methods) if task in ("t1", "t2"): definition = "section" if task == "t1" else "b" required_cls.add((task, definition, "masked", "well", "tfidf_logistic", "ocr", -1)) required_cls.update(("t2", d, "masked", "well", "qwen_zero_shot", "xml", seed) for d in ("a", "b") for seed in protocol["statistics"]["seeds"]) actual = set() if not classification.empty: actual = {keys for keys, data in classification.groupby(CLS_KEYS + ["seed"]) if len(data) == sizes[keys[0], keys[-2], "all"] and ("failed" not in data or not data["failed"].eq(True).all())} required_qa = {(model, mode, modality, seed) for model in ("qwen", "llama", "api") for mode in MODES for modality in (("xml", "html", "ocr") if mode in C4_MODES else ("xml",)) for seed in protocol["statistics"]["seeds"]} actual_qa = {(x["model"], x["mode"], x["modality"], x["seed"]) for x in coverage if x["complete"] and x["failed"] < x["n"]} missing = [sorted(required_cls - actual), sorted(required_qa - actual_qa)] return {"passed": not any(missing), "missing_classification": missing[0], "missing_qa": missing[1]} def status_v2(classification, coverage, protocol, sizes): """Protocol v2: comparison baselines from v1, VAI T2 zero-shot, and VAI on every T4/C4 cell.""" seeds = protocol["statistics"]["seeds"] v1 = status(classification, coverage, protocol, sizes) llm = {("t2", d, "masked", "well", "vai_deepseek_zero_shot", "xml", seed) for d in ("a", "b") for seed in seeds} own = {k for k in v1["missing_classification"] if k[4] not in ("qwen_zero_shot",)} actual = set() if not classification.empty: actual = {keys for keys, data in classification.groupby(CLS_KEYS + ["seed"]) if len(data) == sizes[keys[0], keys[-2], "all"] and ("failed" not in data or not data["failed"].eq(True).all())} required = {(model, mode, modality, seed) for model in V2_QA_MODELS for mode in MODES for modality in (("xml", "html", "ocr") if mode in C4_MODES else ("xml",)) for seed in seeds} actual_qa = {(x["model"], x["mode"], x["modality"], x["seed"]) for x in coverage if x["complete"] and x["failed"] < x["n"]} missing = [sorted(own | (llm - actual)), sorted(required - actual_qa)] return {"passed": not any(missing), "missing_classification": missing[0], "missing_qa": missing[1]} def build_report(out, root, protocol, digests): qa, paired, _, blocked = qa_universe(root, protocol) tables = {task: pd.read_parquet(out / f"features_{task}.parquet") for task in ("t1", "t2", "t3")} sizes = {} for task, data in tables.items(): variants = [("xml", data)] if task != "t3": variants.append(("ocr", data[data["c4"]])) for modality, frame in variants: sizes[task, modality, "all"] = len(frame) if task == "t1": sizes.update({(task, modality, key): len(x) for key, x in frame.groupby("subset")}) if task == "t2": sizes[task, modality, "without_sidetrack"] = int(frame["cause_b"].ne("sidetrack").sum()) ci = protocol["statistics"]["ci"] classification, qa_frame = load_classification(out, digests), load_qa(out, digests) if not classification.empty: for (task, modality), group in classification.groupby(["task", "modality"]): allowed = tables[task] if modality == "ocr": allowed = allowed[allowed["c4"]] if not group["item"].isin(allowed["item"]).all(): raise ValueError(f"Unknown classification item for {task}/{modality}.") cls_rows, cls_contrasts = classification_summary(classification, sizes, ci) qa_rows, qa_contrasts, coverage = qa_summary(qa_frame, qa, paired, blocked, ci) gate = status(classification, coverage, protocol, sizes) return {"g2": gate, "g2_v2": status_v2(classification, coverage, protocol, sizes), "classification": cls_rows, "classification_contrasts": cls_contrasts, "qa": qa_rows, "qa_contrasts": qa_contrasts, "qa_coverage": coverage, "c4": {"paired": len(paired), "date_flagged": len(blocked), "without_date_flags": len(paired)-len(blocked)}, "provenance": {"inputs": digests, "report_code": m34.code_fingerprint("report")}}