"""Recompute G1 inputs and split coverage, then freeze the evaluation protocol after both M2 passes.""" from __future__ import annotations import argparse import fcntl from datetime import datetime from pathlib import Path import pandas as pd import yaml from volve_dia import m2, paths PROTOCOL = m2.PROTOCOL CHECKSUM = PROTOCOL.with_suffix(".yaml.sha256") def targets(root: Path, draft: dict) -> dict[str, pd.DataFrame]: reports = pd.read_parquet(root / "t1_reports.parquet") reports = reports.loc[reports["scope"].eq("drilling_day")].copy() reports["source"] = reports["filled_by"].eq("diaHole").map({True: "published", False: "filled"}) activity = pd.read_parquet(root / "t1_activities.parquet") npt = pd.read_parquet(root / "t2_labels.parquet") result = {"section": reports[["well", "section"]].rename(columns={"section": "label"}), "section_published": reports.loc[reports["source"].eq("published"), ["well", "section"]] .rename(columns={"section": "label"}), "section_filled": reports.loc[reports["source"].eq("filled"), ["well", "section"]] .rename(columns={"section": "label"}), "operation": activity.loc[activity["op_class"].ne("interruption"), ["well", "op_class"]] .rename(columns={"op_class": "label"})} for definition in ("a", "b"): result[f"npt_{definition}"] = npt[["well", f"npt_{definition}"]].rename(columns={f"npt_{definition}": "label"}) result[f"npt_{definition}"]["label"] = result[f"npt_{definition}"]["label"].map({True: "yes", False: "no"}) cause = f"cause_{definition}" result[cause] = npt.loc[npt[f"npt_{definition}"], ["well", cause]].rename(columns={cause: "label"}) preview = draft["class_evaluability"]["preview"] for target, rules in (("section", preview["t1_section"]), ("cause_a", preview["t2_cause"]), ("cause_b", preview["t2_cause"])): mapping = {child: parent for parent, children in rules["merges"].items() for child in children} for t in [target, "section_published", "section_filled"] if target == "section" else [target]: result[f"{t}_pooled"] = result[t].assign(label=result[t]["label"].replace(mapping)) return result def coverage(frame: pd.DataFrame, limits: dict) -> dict: counts = frame.groupby(["label", "well"]).size() return {label: {"n": int(n.sum()), "n_wells_min_items": int(n.ge(limits["min_items_per_well"]).sum()), "evaluable": bool(n.ge(limits["min_items_per_well"]).sum() >= limits["min_wells"]), "counts_by_well": n.droplevel("label").to_dict()} for label, n in counts.groupby(level="label")} def preflight(draft: dict) -> dict: out = paths.outputs_dir() source_hashes = {} for name, record in draft["inputs"].items(): if isinstance(record, dict) and "file" in record: source_hashes[name] = m2.digest(paths.REPO_ROOT / record["file"]) elif isinstance(record, dict) and "dir" in record: source_hashes[name] = m2.digest(out / Path(record["dir"]).name / "summary.json") if m2.read_json(out / "labels/summary.json")["labels_yaml"]["sha256"] != source_hashes["labels_config"]: raise ValueError("The M1 labels were generated with a different labels.yaml.") if m2.read_json(out / "t4/summary.json")["config"]["sha256"] != source_hashes["t4_templates"]: raise ValueError("The M1 questions were generated with a different t4_templates.yaml.") logs = pd.read_parquet(out / "witsml/wellbores.parquet") cells = pd.read_parquet(out / "labels/t3_cells.parquet") wellbores = sorted(logs.loc[logs["in_ddr"] & logs["n_time_logs"].gt(0), "wellbore"].unique()) relevant = cells.loc[cells["wellbore"].isin(wellbores) & cells["in_own_hole"]] folds = {} for well in sorted(relevant["well"].unique()): train = relevant.loc[relevant["well"].ne(well)] test = relevant.loc[relevant["well"].eq(well)] folds[well] = { "train_cells": len(train), "test_cells": len(test), "train_positive": {d: int(train[f"label_{d}"].sum()) for d in ("a", "b")}, "test_positive": {d: int(test[f"label_{d}"].sum()) for d in ("a", "b")}, } if not folds or any(any(n < 1 or n >= f["train_cells"] for n in f["train_positive"].values()) for f in folds.values()): raise ValueError("At least one T3 training fold lacks positives or negatives.") scopes = {name: coverage(frame, draft["class_evaluability"]) for name, frame in targets(out / "labels", draft).items()} table_names = ("t1_activities", "t1_reports", "t2_labels", "t3_cells") table_hashes = {name: m2.digest(out / "labels" / f"{name}.parquet") for name in table_names} return {"input_hashes": source_hashes, "label_table_hashes": table_hashes, "class_coverage": scopes, "t3": { "eligible_wellbores": wellbores, "eligible_wells": sorted(folds), "logo_folds": folds, "cells": len(relevant), "wellbores_table_sha256": m2.digest(out / "witsml/wellbores.parquet"), "cells_table_sha256": m2.digest(out / "labels/t3_cells.parquet"), }} def class_decisions(draft: dict, first: dict, pre: dict, definition: str) -> dict: limits = draft["class_merging"] coverage_table = pre["class_coverage"] result = {} for target in ("section", "operation", f"cause_{definition}", f"npt_{definition}"): score = first["targets"][target] names = coverage_table[target] | coverage_table.get(f"{target}_pooled", {}) pooled = score.get("pooled_classes", {}) preview = draft["class_evaluability"]["preview"] merges = (preview["t1_section"]["merges"] if target == "section" else preview["t2_cause"]["merges"] if target.startswith("cause_") else {}) members = {child: parent for parent, children in merges.items() for child in children} eligible = {} for name, cover in names.items(): s = (score["by_class"] | pooled).get(name, {}) kappa = s.get("median_weighted_kappa") rated = s.get("rated_items", 0) checks = {"well_support": cover["evaluable"], "rated": rated >= limits["min_audit_items"], "agreement": kappa is not None and kappa >= limits["min_kappa"]} eligible[name] = {"checks": checks, "rated_items": rated, "median_weighted_kappa": kappa, "status": "keep" if all(checks.values()) else "drop"} for child, parent in members.items(): if child in eligible: eligible[child]["parent"] = parent if eligible[parent]["status"] == "keep": eligible[child]["within_parent_reportable"] = eligible[child]["status"] == "keep" eligible[child]["status"] = "merge" if target.startswith("cause_"): for name in ("sidetrack", "hse"): if name in eligible: eligible[name]["status"] = "drop" result[target] = eligible return result def check_panel(root: Path, pass_number: int, panel: dict, config: dict, sample: dict) -> None: previous = root / "ratings" / "pass1" names = set(config["raters"]) if panel["pass"] != pass_number or set(panel["provenance"]) != names: raise ValueError(f"Incomplete agreement report for pass {pass_number}.") minimum_gap = m2.repeatability_gap() if pass_number == 2 else None for name, source in panel["provenance"].items(): file = root / "ratings" / f"pass{pass_number}" / f"{name}.json" state = m2.read_json(file) provenance = state["provenance"] if (m2.digest(file) != source["ratings_sha256"] or not state.get("completed_at") or len(state["responses"]) != sum(a["items"] for a in sample.values()) or provenance["settings"]["spec_sha256"] != m2.digest(m2.VALIDATION) or provenance["model"] != config["raters"][name]): raise ValueError(f"Rating is incomplete or has changed: {file}") if minimum_gap is not None: first = m2.read_json(previous / file.name) if (first["provenance"] != provenance or datetime.fromisoformat(state["started_at"]) < datetime.fromisoformat(first["completed_at"]) + minimum_gap): raise ValueError(f"Second-pass timing or provenance failed: {file}") def freeze(draft: dict, pre: dict) -> None: root = m2.directory() sample = m2.read_json(root / "sample.json") for kind, hashes in sample.items(): if (m2.digest(root / f"key_{kind}.csv") != hashes["key_sha256"] or m2.digest(root / "blind" / f"{kind}.jsonl") != hashes["blind_sha256"] or m2.digest(root / "blind" / f"{kind}_prompt.txt") != hashes["prompt_sha256"]): raise ValueError(f"M2 sample or rubric was modified: {kind}") first_file, second_file = (root / f"agreement_pass{n}.json" for n in (1, 2)) if not first_file.is_file() or not second_file.is_file(): raise ValueError("G1 requires completed agreement reports from both M2 passes.") first, second = m2.read_json(first_file), m2.read_json(second_file) config = m2.spec() if second["pass1_agreement_sha256"] != m2.digest(first_file): raise ValueError("First-pass agreement changed after the repeatability report.") if second["minimum_repeat_gap_days"] != m2.repeatability_gap().days: raise ValueError("The repeatability timing rule changed after the second pass was scored.") for n, panel in enumerate((first, second), start=1): check_panel(root, n, panel, config, sample) cross_file = root / "cross_checks/summary.json" if not first["npt_candidate"]: raise ValueError("The first pass did not yield a defined NPT decision for the complete panel.") definition = first["npt_candidate"]["primary"] final = class_decisions(draft, first, pre, definition) draft["status"] = "locked" draft["locked_at_utc"] = m2.utc_now().isoformat() draft["before_lock"] = [] for name, value in pre["input_hashes"].items(): record = draft["inputs"][name] record["sha256" if "file" in record else "summary_sha256"] = value draft["tasks"]["t2"]["npt_definition"]["primary"] = definition draft["tasks"]["t3"]["wellbores"] = pre["t3"]["eligible_wellbores"] draft["class_evaluability"]["final"] = pre["class_coverage"] draft["class_merging"]["merges"] = final draft["reporting"]["separate_class_scores"] = { target: sorted(name for name, row in classes.items() if row["status"] == "keep") for target, classes in final.items() } draft["inputs"]["label_tables"]["tables_sha256"] = pre["label_table_hashes"] draft["validation"]["m2_evidence"] = { "sample_sha256": m2.digest(root / "sample.json"), "configuration_sha256": m2.digest(m2.VALIDATION), "agreement_pass1_sha256": m2.digest(first_file), "agreement_pass2_sha256": m2.digest(second_file), "cross_checks_sha256": m2.digest(cross_file), "npt_selection": first["npt_candidate"], "t3_split": pre["t3"], } output = yaml.safe_dump(draft, sort_keys=False, width=110, allow_unicode=True) candidate = root / "protocol_v1.candidate.yaml" candidate.write_text(output, encoding="utf-8") temp = PROTOCOL.with_suffix(".yaml.tmp") temp.write_text(output, encoding="utf-8") temp.replace(PROTOCOL) write_checksum() print(f"G1 locked: NPT definition {definition}; {CHECKSUM.relative_to(paths.REPO_ROOT)}") def write_checksum() -> None: line = f"{m2.digest(PROTOCOL)} {PROTOCOL.relative_to(paths.REPO_ROOT)}\n" temp = CHECKSUM.with_suffix(".tmp") temp.write_text(line, encoding="utf-8") temp.replace(CHECKSUM) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("preflight", "review", "lock")) action = parser.parse_args().action root = m2.directory() root.mkdir(parents=True, exist_ok=True) with (root / "protocol.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) draft = yaml.safe_load(PROTOCOL.read_text(encoding="utf-8")) if CHECKSUM.exists(): recorded = CHECKSUM.read_text(encoding="utf-8").split()[0] if draft["status"] != "locked" or recorded != m2.digest(PROTOCOL): raise ValueError("Existing G1 checksum does not match the locked protocol.") print("G1 protocol checksum verified.") elif draft["status"] == "locked": candidate = root / "protocol_v1.candidate.yaml" if action != "lock" or not candidate.is_file() or m2.digest(PROTOCOL) != m2.digest(candidate): raise ValueError("The protocol says locked but its checksum is missing.") write_checksum() print("Recovered the checksum of the existing G1 candidate.") else: if draft["status"] != "draft": raise ValueError(f"Unsupported protocol status: {draft['status']}") pre = preflight(draft) snapshot = root / "g1_preflight.json" if action != "preflight" and (not snapshot.is_file() or m2.read_json(snapshot) != pre): raise ValueError("G1 input tables differ from the preflight snapshot.") if action == "preflight": m2.write_json(snapshot, pre) print(f"{len(pre['t3']['eligible_wellbores'])} T3 wellbores and " f"{len(pre['t3']['eligible_wells'])} wells with both classes in every LOGO training fold") if action == "review": first_file = root / "agreement_pass1.json" first = m2.read_json(first_file) config = m2.spec() check_panel(root, 1, first, config, m2.read_json(root / "sample.json")) selection = first["npt_candidate"] decisions = class_decisions(draft, first, pre, selection["primary"]) if selection else {} m2.write_json(root / "g1_class_review_pass1.json", { "agreement_sha256": m2.digest(first_file), "provisional_npt": selection, "status": "provisional", "classes": decisions, }) print(f"Provisional first-pass class decisions: {root / 'g1_class_review_pass1.json'}") elif action == "lock": freeze(draft, pre) if __name__ == "__main__": main()