Volve-DIA trial audit
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.
"""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"""