Files
Volve-DIA/scripts/09_audit.py
lamlvh 2b59d635ce Complete M2 validation and lock the G1 evaluation protocol
Run and record both blind LLM validation passes and the external
cross-checks. Freeze the evaluation inputs, well splits, and reporting
scope with a SHA-256 checksum.

Use NPT definition b for DDR-code prediction with definition a as a
sensitivity analysis. Retain the class reporting thresholds and record
the empty set of eligible classes. Make T4 and OCR fidelity the headline
analyses and align the progress report and project documentation.

Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-11-18 04:13:13 +00:00

204 lines
12 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Trial blind audit of the activity labels (plan section 4.4): draw the masked sample, then score the ratings.
python scripts/09_audit.py sample # outputs/audit/trial_100/{audit.html, sheet.csv, key.csv, ...}
python scripts/09_audit.py score RATINGS.csv # agreement with the labels, time per row -> score.json
`sample` draws 100 activities from outputs/labels (scripts/07_labels.py), stratified by NPT zone (a: NPT under both
definitions, b_only: only under the union, none) and, inside a zone, by cause group or operation class, spread over
the 11 wells. The rater sees the masked input view only (no code, no label) in audit.html, which keeps the ratings in
the browser, times every item and exports RATINGS.csv. key.csv holds the labels: do not open it before rating.
`score` compares the ratings with both NPT definitions, the cause groups and the operation classes (Cohen's kappa,
unweighted and weighted back to the population) and projects the time of audit 1 (300 rows).
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
import pandas as pd
from volve_dia import audit, paths
SEED = 20261117
PLAN = {"a": 35, "b_only": 15, "none": 50}
MIN_PER_STRATUM = 2
SHEET_COLUMNS = ["item", "wellbore", "report_date", "start_utc", "end_utc", "duration_h", "md", "rig_phase",
"prev_comment", "comment", "next_comment", "sum24Hr"]
RATING_COLUMNS = ["r_npt", "r_cause", "r_op_class", "r_confidence", "r_seconds", "r_note"]
def out_dir() -> Path:
return paths.outputs_dir() / "audit" / "trial_100"
def sample() -> int:
x = audit.load_activity_labels()
x["zone"] = audit.zone(x["npt_a"], x["npt_b"])
cls = x["cause_a"].where(x["zone"] == "a", x["cause_b"].where(x["zone"] == "b_only", x["op_class"]))
x["stratum"] = x["zone"] + "/" + cls
s = audit.draw(x, PLAN, MIN_PER_STRATUM, SEED)
s.insert(0, "item", [f"T{i + 1:03d}" for i in range(len(s))])
s["report_date"] = s["file_date"].astype(str)
s["comment"] = s["comments"]
for c in ("start_utc", "end_utc"):
s[c] = pd.to_datetime(s[c]).dt.strftime("%Y-%m-%d %H:%M")
od = out_dir()
od.mkdir(parents=True, exist_ok=True)
sheet = s[SHEET_COLUMNS].assign(**{c: "" for c in RATING_COLUMNS})
sheet.to_csv(od / "sheet.csv", index=False, encoding="utf-8-sig")
key = s[["item", "act_id", "well", "zone", "stratum", "n_stratum", "k_stratum", "weight", "npt_a", "npt_b",
"cause_a", "cause_b", "op_class"]]
key.to_csv(od / "key.csv", index=False)
(od / "audit.html").write_text(html_page(sheet), encoding="utf-8")
summary = {"seed": SEED, "plan": PLAN, "min_per_stratum": MIN_PER_STRATUM, "items": len(s),
"population": len(x), "zone_population": x["zone"].value_counts().to_dict(),
"strata": key.groupby("stratum").agg(n=("n_stratum", "first"), k=("k_stratum", "first"))
.reset_index().to_dict("records"),
"wells": key["well"].value_counts().to_dict(), "wellbores": int(s["wellbore"].nunique())}
(od / "sample.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8")
print(json.dumps({k: v for k, v in summary.items() if k != "strata"}, indent=1))
print(f"[audit] {len(s)} items -> {od}/audit.html (rate there; do not open key.csv before rating)")
return 0
def score(ratings: Path) -> int:
od = out_dir()
key = pd.read_csv(od / "key.csv")
r = pd.read_csv(ratings, dtype=str, encoding="utf-8-sig")
r = r[["item"] + [c for c in RATING_COLUMNS if c in r.columns]]
d = key.merge(r, on="item", how="left", validate="1:1")
rated = d["r_npt"].isin(["y", "n"])
d = d[rated].copy()
if d.empty:
print("[audit] no rated items (r_npt must be y or n)")
return 1
d["r_npt_b"] = d["r_npt"] == "y"
d["r_cause_all"] = d["r_cause"].where(d["r_npt_b"], "none").fillna("unspecified")
w = d["weight"]
res: dict = {"ratings_file": str(ratings), "rated": len(d), "unsure_or_blank": int((~rated).sum())}
for defn in ("a", "b"):
lab_npt = d[f"npt_{defn}"].astype(bool)
lab_cause = d[f"cause_{defn}"].fillna("none")
both = d["r_npt_b"] & lab_npt
res[f"npt_{defn}"] = {"raw": audit.agreement(d["r_npt_b"], lab_npt),
"weighted": audit.agreement(d["r_npt_b"], lab_npt, w)}
res[f"cause_{defn}"] = {"raw": audit.agreement(d["r_cause_all"], lab_cause),
"weighted": audit.agreement(d["r_cause_all"], lab_cause, w),
"given_both_npt": audit.agreement(d.loc[both, "r_cause"], lab_cause[both])}
ops = d["op_class"] != "interruption"
res["op_class_non_interruption"] = {"raw": audit.agreement(d.loc[ops, "r_op_class"], d.loc[ops, "op_class"]),
"weighted": audit.agreement(d.loc[ops, "r_op_class"], d.loc[ops, "op_class"],
w[ops])}
sec = pd.to_numeric(d.get("r_seconds"), errors="coerce").dropna()
if len(sec):
res["seconds_per_item"] = {"median": round(float(sec.median()), 1), "mean": round(float(sec.mean()), 1),
"p90": round(float(sec.quantile(0.9)), 1), "total_h": round(sec.sum() / 3600, 2),
"audit_1_300_rows_h": round(300 * float(sec.mean()) / 3600, 1)}
res["by_zone"] = {z: audit.agreement(g["r_npt_b"], g["npt_b"].astype(bool)) for z, g in d.groupby("zone")}
res["confidence"] = d["r_confidence"].value_counts().to_dict()
dis = d[(d["r_npt_b"] != d["npt_b"].astype(bool)) | (d["r_cause_all"] != d["cause_b"].fillna("none"))
| (ops & (d["r_op_class"] != d["op_class"]))]
dis.to_csv(od / "disagreements.csv", index=False)
res["disagreement_rows"] = len(dis)
(od / "score.json").write_text(json.dumps(res, indent=1) + "\n", encoding="utf-8")
print(json.dumps(res, indent=1))
return 0
def html_page(sheet: pd.DataFrame) -> str:
data = json.dumps(sheet[SHEET_COLUMNS].fillna("").astype(str).to_dict("records"), ensure_ascii=False)
data = data.replace("</", "<\\/")
return (HTML.replace("__DATA__", data).replace("__CAUSES__", json.dumps(audit.CAUSES))
.replace("__OPS__", json.dumps(audit.OP_CLASSES)))
HTML = r"""<!doctype html>
<html lang="vi"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Volve-DIA trial audit</title>
<style>
:root{--bg:#fafaf8;--fg:#1d1d1b;--mut:#6b6b66;--line:#d9d9d3;--acc:#2d5b8a;--card:#fff}
@media (prefers-color-scheme:dark){:root{--bg:#18181a;--fg:#e8e8e3;--mut:#9a9a94;--line:#3a3a3d;--acc:#7fb0e0;
--card:#222225}}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
main{max-width:920px;margin:0 auto;padding:16px}
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:14px 16px;margin:10px 0}
.meta{color:var(--mut);font-size:13px}.ctx{color:var(--mut);white-space:pre-wrap}
.cur{font-size:17px;white-space:pre-wrap;border-left:3px solid var(--acc);padding-left:10px}
fieldset{border:1px solid var(--line);border-radius:8px;margin:8px 0}legend{color:var(--mut);font-size:13px}
label{display:inline-block;margin:2px 10px 2px 0;cursor:pointer}
button{font:inherit;padding:6px 14px;border:1px solid var(--line);border-radius:6px;background:var(--card);
color:var(--fg);cursor:pointer}button.pri{background:var(--acc);color:#fff;border-color:var(--acc)}
.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}textarea{width:100%;font:inherit;background:var(--bg);
color:var(--fg);border:1px solid var(--line);border-radius:6px}details{margin-top:6px}
</style></head><body><main>
<div class="bar"><strong>Volve-DIA trial audit</strong><span id="prog" class="meta"></span>
<span style="flex:1"></span><button id="exp">Xuất RATINGS.csv</button></div>
<p class="meta">Mã hoạt động và nhãn đã bị che. Hãy chấm theo nội dung, không mở key.csv. Thời gian mỗi mục được
đo tự động (chỉ khi tab đang hiển thị). Dữ liệu lưu trong trình duyệt; xuất CSV khi xong.</p>
<div class="card"><div id="meta" class="meta"></div>
<details><summary class="meta">Tóm tắt 24 giờ của báo cáo</summary><div id="sum" class="ctx"></div></details>
<p class="ctx" id="prev"></p><p class="cur" id="cur"></p><p class="ctx" id="next"></p></div>
<form id="f" class="card">
<fieldset><legend>NPT? (thời gian không sản xuất)</legend><span id="npt"></span></fieldset>
<fieldset><legend>Nhóm nguyên nhân (chỉ khi NPT = có)</legend><span id="cause"></span></fieldset>
<fieldset><legend>Loại thao tác</legend><span id="op"></span></fieldset>
<fieldset><legend>Độ tự tin</legend><span id="conf"></span></fieldset>
<textarea id="note" rows="2" placeholder="Ghi chú (tuỳ chọn)"></textarea>
<div class="bar" style="margin-top:8px"><button type="button" id="back">← Trước</button>
<button type="button" class="pri" id="go">Lưu &amp; tiếp →</button></div></form>
</main><script>
const D=__DATA__,CAUSES=__CAUSES__,OPS=__OPS__,K="volve-dia-trial-audit-v1";
let S={};try{S=JSON.parse(localStorage.getItem(K)||"{}")}catch(e){}
let i=Math.max(0,D.findIndex(d=>!(S[d.item]&&S[d.item].r_npt)));if(i<0)i=0;
let t0=Date.now(),acc=0;
document.addEventListener("visibilitychange",()=>{if(document.hidden){acc+=Date.now()-t0}else{t0=Date.now()}});
function radios(el,name,vals,labels){el.textContent="";vals.forEach((v,k)=>{const l=document.createElement("label");
const r=document.createElement("input");r.type="radio";r.name=name;r.value=v;l.append(r," "+(labels?labels[k]:v));
el.append(l)})}
radios(npt,"r_npt",["y","n","?"],["có","không","không rõ"]);radios(cause,"r_cause",CAUSES);radios(op,"r_op_class",OPS);
radios(conf,"r_confidence",["1","2","3"],["1 thấp","2","3 cao"]);
function save(){try{localStorage.setItem(K,JSON.stringify(S))}catch(e){}}
function show(){const d=D[i],s=S[d.item]||{};
meta.textContent=`${d.item} · ${d.wellbore} · báo cáo ${d.report_date} · ${d.start_utc} → ${d.end_utc} · `+
`${d.duration_h} h · MD ${d.md} m · ${d.rig_phase}`;
sum.textContent=d.sum24Hr;prev.textContent=d.prev_comment?"Trước: "+d.prev_comment:"(hoạt động đầu tiên)";
cur.textContent=d.comment;next.textContent=d.next_comment?"Sau: "+d.next_comment:"(hoạt động cuối cùng)";
for(const n of["r_npt","r_cause","r_op_class","r_confidence"])f.querySelectorAll(`input[name=${n}]`)
.forEach(r=>r.checked=s[n]===r.value);note.value=s.r_note||"";
prog.textContent=`${i+1}/${D.length} · đã chấm ${D.filter(d=>S[d.item]&&S[d.item].r_npt).length}`;
t0=Date.now();acc=0;window.scrollTo(0,0)}
function store(){const d=D[i],s=S[d.item]||{};const fd=new FormData(f);
for(const n of["r_npt","r_cause","r_op_class","r_confidence"])s[n]=fd.get(n)||"";s.r_note=note.value;
s.r_seconds=String(Math.round(((s.r_seconds?+s.r_seconds:0)*1000+acc+(document.hidden?0:Date.now()-t0))/1000));
S[d.item]=s;save()}
go.onclick=()=>{if(!new FormData(f).get("r_npt")){alert("Chọn NPT trước");return}store();
if(i<D.length-1){i++;show()}else{alert("Đã hết mục. Hãy xuất RATINGS.csv.")}};
back.onclick=()=>{store();if(i>0){i--;show()}};
exp.onclick=()=>{store();const cols=["item","r_npt","r_cause","r_op_class","r_confidence","r_seconds","r_note"];
const q=v=>'"'+String(v??"").replace(/"/g,'""')+'"';
const csv=[cols.join(",")].concat(D.map(d=>{const s=S[d.item]||{};return[d.item].concat(cols.slice(1)
.map(c=>s[c]||"")).map(q).join(",")})).join("\n");
const a=document.createElement("a");a.href=URL.createObjectURL(new Blob([""+csv],{type:"text/csv"}));
a.download="RATINGS.csv";a.click()};
show();
</script></body></html>
"""
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("sample")
sc = sub.add_parser("score")
sc.add_argument("ratings", type=Path)
a = ap.parse_args()
return sample() if a.cmd == "sample" else score(a.ratings)
if __name__ == "__main__":
sys.exit(main())