Add M1: OCR hub import, WITSML, labels T1-T3, T4 questions, trial raters, draft protocol
- OCR: match the colleague's full-set Dataset Hub export to the DDRs by content (3,059/3,066 pages) and QC it against the HTML (CER 2.40%, exact 0.9181). - WITSML parser and formation tops: 21 DDR wellbores with time logs, 1,384 reports; WITSML 15/9-F-15 S is DDR 15/9-F-15. - Deterministic labels T1-T3 (configs/labels.yaml), 1,662 T4 questions with SQL, pandas and raw-XML answers in full agreement. - Trial label validation by three blind LLM raters (not an author or expert audit) and rater agreement script; draft protocol_v1 (not locked): split by well. - Literature notes and BibTeX; docs, report and run_m1.sh synchronised. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,8 +3,8 @@
|
||||
python scripts/00_data_manifest.py # create/update data_manifest/volve_dia.json
|
||||
python scripts/00_data_manifest.py --check # check only; exit 1 on a missing file or a hash mismatch
|
||||
|
||||
Only the subtrees in SUBTREES are hashed (~20 GB, mostly WITSML); the rest of data/Volve (well logs, seismic) is
|
||||
not read by this project.
|
||||
Only the subtrees in SUBTREES and the single files in FILES are hashed (~20 GB, mostly WITSML); the rest of
|
||||
data/Volve (well logs, seismic) is not read by this project.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +22,8 @@ from volve_dia.paths import REPO_ROOT, volve_root
|
||||
MANIFEST = REPO_ROOT / "data_manifest" / "volve_dia.json"
|
||||
DESCRIPTION = "Volve data village (Equinor and the Volve licence partners), CC BY-NC-SA 4.0"
|
||||
SUBTREES = ["Well_technical_data", "Reports", "WITSML Realtime drilling data"]
|
||||
#: Single files read from outside the subtrees: the formation tops (scripts/06_parse_witsml.py).
|
||||
FILES = ["Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat"]
|
||||
|
||||
|
||||
def sha256(path: Path, chunk: int = 1 << 22) -> str:
|
||||
@@ -33,7 +35,8 @@ def sha256(path: Path, chunk: int = 1 << 22) -> str:
|
||||
|
||||
|
||||
def scan(root: Path) -> dict[str, dict]:
|
||||
files = sorted(p for sub in SUBTREES for p in (root / sub).rglob("*") if p.is_file())
|
||||
files = sorted([p for sub in SUBTREES for p in (root / sub).rglob("*") if p.is_file()]
|
||||
+ [root / f for f in FILES])
|
||||
with ThreadPoolExecutor(max_workers=8) as ex:
|
||||
digests = list(ex.map(sha256, files))
|
||||
return {
|
||||
@@ -48,7 +51,7 @@ def main() -> int:
|
||||
args = ap.parse_args()
|
||||
|
||||
root = volve_root()
|
||||
missing_dirs = [s for s in SUBTREES if not (root / s).is_dir()]
|
||||
missing_dirs = [s for s in SUBTREES if not (root / s).is_dir()] + [f for f in FILES if not (root / f).is_file()]
|
||||
if missing_dirs:
|
||||
print(f"missing under {root}: {missing_dirs}")
|
||||
return 1
|
||||
@@ -69,6 +72,7 @@ def main() -> int:
|
||||
"dataset": DESCRIPTION,
|
||||
"root": root.relative_to(REPO_ROOT).as_posix() if root.is_relative_to(REPO_ROOT) else str(root),
|
||||
"subtrees": SUBTREES,
|
||||
"files_outside_subtrees": FILES,
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"n_files": len(current),
|
||||
"total_bytes": sum(v["size_bytes"] for v in current.values()),
|
||||
|
||||
244
scripts/04_ocr_hub.py
Normal file
244
scripts/04_ocr_hub.py
Normal file
@@ -0,0 +1,244 @@
|
||||
"""Import the Dataset Hub OCR export (configs/ocr_hub.yaml) as page records of the DDR PDFs, outputs/ocr/hub/.
|
||||
|
||||
python scripts/04_ocr_hub.py
|
||||
|
||||
Every PDF page under the Volve root (the 3,066 DDR pages and the other PDFs, so that every image is accounted for) is
|
||||
matched to an image of the export by text, then by image (`volve_dia.ocr_hub`). Only DDR pages are written as page
|
||||
records. Writes outputs/ocr/hub/{pages/, match.csv, candidates.csv, service_vs_hub.csv, summary.json} and
|
||||
outputs/ocr/hub_docs.csv (one row per report, the columns of ddr_docs.csv). The summary checks the dates of every
|
||||
dated page against its OCR text and how much the choice depends on `tie_eps`. DDR pages the export does not hold
|
||||
are written with status `missing` and listed in the summary.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
from rapidfuzz.distance import Levenshtein
|
||||
|
||||
from volve_dia import ocr, ocr_hub, paths
|
||||
|
||||
|
||||
def pdf_pages(root: Path) -> pd.DataFrame:
|
||||
import pymupdf
|
||||
|
||||
rows = []
|
||||
for p in sorted(q for q in root.rglob("*") if q.suffix.lower() == ".pdf"):
|
||||
sha = ocr.sha256_file(p)
|
||||
with pymupdf.open(p) as doc:
|
||||
for k, page in enumerate(doc, 1):
|
||||
rows.append({"file": str(p.relative_to(root)), "doc_sha256": sha, "page": k,
|
||||
"n_pages": doc.page_count, "text": page.get_text()})
|
||||
df = pd.DataFrame(rows)
|
||||
df["ddr"] = df["file"].str.startswith(str(paths.ddr_pdf_dir().relative_to(root)) + "/")
|
||||
return df
|
||||
|
||||
|
||||
def page_text(content: str) -> str:
|
||||
return "\n".join(b.text for b in ocr.html_blocks(content, 1))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
t0 = time.time()
|
||||
hc = ocr_hub.load_config()
|
||||
exp = ocr_hub.load_export(hc.dir)
|
||||
root = paths.volve_root()
|
||||
pages = pdf_pages(root)
|
||||
print(f"[hub] export {exp.file.name}: {len(exp.images)} images, {sum(map(len, exp.blocks.values()))} blocks, "
|
||||
f"{len(exp.orphans)} PNGs without a record; {len(pages)} PDF pages ({int(pages['ddr'].sum())} DDR)",
|
||||
flush=True)
|
||||
|
||||
ids = sorted(exp.images)
|
||||
contents = [ocr_hub.page_content(exp.blocks.get(i, []), exp.categories, exp.images[i]["width"],
|
||||
exp.images[i]["height"]) for i in ids]
|
||||
img_toks = [ocr_hub.tokens(c) for c in contents]
|
||||
img_dates = [ocr_hub.iso_dates(" ".join(t)) for t in img_toks]
|
||||
page_toks = [ocr_hub.tokens(t) for t in pages["text"]]
|
||||
ix = ocr_hub.TextIndex(page_toks, img_toks)
|
||||
print(f"[hub] text index done ({time.time() - t0:.0f} s)", flush=True)
|
||||
|
||||
import numpy as np
|
||||
import pymupdf
|
||||
|
||||
thumbs: dict[int, object] = {}
|
||||
|
||||
def thumb(i: int):
|
||||
if i not in thumbs:
|
||||
thumbs[i] = ocr_hub.image_thumb(hc.dir / exp.images[ids[i]]["file_name"], hc.thumb_shrink)
|
||||
return thumbs[i]
|
||||
|
||||
coarse_all = None
|
||||
|
||||
def by_image(j: int, pt) -> list[tuple[int, float]]:
|
||||
"""Fallback: the best images of the whole export by coarse correlation, with their text F1."""
|
||||
nonlocal coarse_all
|
||||
if coarse_all is None:
|
||||
coarse_all = np.stack([ocr_hub.coarse(ocr_hub.image_thumb(hc.dir / exp.images[i]["file_name"],
|
||||
hc.thumb_shrink)) for i in ids])
|
||||
print(f"[hub] coarse thumbnails of all images ({time.time() - t0:.0f} s)", flush=True)
|
||||
return [(int(i), ix.f1(j, int(i))) for i in np.argsort(-(coarse_all @ ocr_hub.coarse(pt)))[:hc.fallback_top_k]]
|
||||
|
||||
page_thumbs = {}
|
||||
rows, cand_rows = [], []
|
||||
open_doc = (None, None)
|
||||
for j, r in enumerate(pages.itertuples(index=False)):
|
||||
if open_doc[0] != r.file:
|
||||
if open_doc[1] is not None:
|
||||
open_doc[1].close()
|
||||
open_doc = (r.file, pymupdf.open(root / r.file))
|
||||
pt = ocr_hub.page_thumb(open_doc[1], r.page, hc.thumb_dpi)
|
||||
cands = ix.candidates(j, hc.prefilter, hc.top_k)
|
||||
stage = "text"
|
||||
min_f1 = hc.min_text_f1 if len(page_toks[j]) >= hc.f1_min_tokens else 0.0
|
||||
scored = [(ocr_hub.correlation(pt, thumb(i)), f1, i) for i, f1 in cands]
|
||||
best = ocr_hub.select(scored, hc.min_corr, hc.tie_eps, min_f1)
|
||||
if best is None and r.ddr:
|
||||
stage = "image"
|
||||
seen = {s[2] for s in scored}
|
||||
scored += [(ocr_hub.correlation(pt, thumb(i)), f1, i) for i, f1 in by_image(j, pt) if i not in seen]
|
||||
best = ocr_hub.select(scored, hc.min_corr, hc.tie_eps, min_f1)
|
||||
scored.sort(reverse=True)
|
||||
if r.ddr:
|
||||
cand_rows += [{"file": r.file, "page": r.page, "image_id": ids[i], "corr": round(c, 4),
|
||||
"text_f1": round(f1, 4)} for c, f1, i in scored]
|
||||
if best is None:
|
||||
if r.ddr:
|
||||
page_thumbs[j] = pt
|
||||
stage = "none"
|
||||
best = scored[0] if scored else (0.0, 0.0, -1)
|
||||
others = [s[0] for s in scored if s[2] != best[2]]
|
||||
dates = ocr_hub.iso_dates(r.text)
|
||||
rows.append({"file": r.file, "doc_sha256": r.doc_sha256, "page": r.page, "n_pages": r.n_pages, "ddr": r.ddr,
|
||||
"pdf_tokens": len(page_toks[j]), "image_id": ids[best[2]] if best[2] >= 0 else None,
|
||||
"image_file": exp.images[ids[best[2]]]["file_name"] if best[2] >= 0 else None,
|
||||
"corr": round(best[0], 4), "corr_other": round(max(others), 4) if others else None,
|
||||
"text_f1": round(best[1], 4), "text_f1_max": round(max((s[1] for s in scored), default=0.0), 4),
|
||||
"stage": stage, "matched": stage != "none",
|
||||
"pdf_dates": len(dates),
|
||||
"dates_agree": (dates <= img_dates[best[2]]) if dates and stage != "none" else None})
|
||||
if j % 500 == 0:
|
||||
print(f"[hub] {j}/{len(pages)} pages ({time.time() - t0:.0f} s)", flush=True)
|
||||
if open_doc[1] is not None:
|
||||
open_doc[1].close()
|
||||
m = pd.DataFrame(rows)
|
||||
cand = pd.DataFrame(cand_rows)
|
||||
|
||||
# Orphan PNGs (no record, so no OCR text): which unmatched DDR page do they show?
|
||||
orphan_rows = []
|
||||
for name in exp.orphans:
|
||||
ot = ocr_hub.image_thumb(hc.dir / name, hc.thumb_shrink)
|
||||
best = max(((ocr_hub.correlation(pt, ot), j) for j, pt in page_thumbs.items()), default=(0.0, -1))
|
||||
orphan_rows.append({"image_file": name, "corr": round(best[0], 4),
|
||||
"file": pages["file"].iat[best[1]] if best[1] >= 0 else None,
|
||||
"page": int(pages["page"].iat[best[1]]) if best[1] >= 0 else None})
|
||||
orphans = pd.DataFrame(orphan_rows, columns=["image_file", "corr", "file", "page"])
|
||||
|
||||
out = paths.outputs_dir() / "ocr" / "hub"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
m.to_csv(out / "match.csv", index=False)
|
||||
cand.to_csv(out / "candidates.csv", index=False)
|
||||
|
||||
# How much does the choice depend on tie_eps? Re-select every DDR page for a grid of values and check the dates.
|
||||
id_dates = dict(zip(ids, img_dates))
|
||||
page_dates = {(f, p): ocr_hub.iso_dates(t) for f, p, t in pages[pages["ddr"]][["file", "page", "text"]].values}
|
||||
floor = {(f, p): hc.min_text_f1 if t >= hc.f1_min_tokens else 0.0
|
||||
for f, p, t in m[m["ddr"]][["file", "page", "pdf_tokens"]].values}
|
||||
sens = []
|
||||
for eps in (0.0, 0.002, 0.005, 0.01, 0.02, 0.05):
|
||||
picks = {k: ocr_hub.select(list(zip(g["corr"], g["text_f1"], g["image_id"])), hc.min_corr, eps, floor[k])
|
||||
for k, g in cand.groupby(["file", "page"])}
|
||||
final = dict(zip(zip(m["file"], m["page"]), m["image_id"].where(m["matched"])))
|
||||
dated = [k for k, d in page_dates.items() if d and picks.get(k)]
|
||||
sens.append({"tie_eps": eps, "matched": sum(v is not None for v in picks.values()),
|
||||
"differs_from_used": sum((v[2] if v else None) != final.get(k) for k, v in picks.items()
|
||||
if not (v is None and pd.isna(final.get(k)))),
|
||||
"dated_pages": len(dated),
|
||||
"dates_disagree": sum(not page_dates[k] <= id_dates[picks[k][2]] for k in dated)})
|
||||
|
||||
# Page records of the DDR pages.
|
||||
shutil.rmtree(ocr_hub.cache_dir(), ignore_errors=True)
|
||||
by_id = dict(zip(ids, contents))
|
||||
ddr = m[m["ddr"]]
|
||||
shared = ddr[ddr["matched"]].groupby("image_id")["file"].transform("size")
|
||||
for r in ddr.assign(shared=shared).itertuples(index=False):
|
||||
rec = {"doc_sha256": r.doc_sha256, "file": r.file, "page": r.page, "n_pages": r.n_pages, "source": "hub",
|
||||
"export_file": exp.file.name, "export_sha256": exp.sha256,
|
||||
"status": "ok" if r.matched else "missing", "blank_pdf_page": r.pdf_tokens == 0,
|
||||
"image_file": r.image_file if r.matched else None,
|
||||
"match": {"stage": r.stage, "corr": r.corr, "corr_other": r.corr_other, "text_f1": r.text_f1,
|
||||
"text_f1_max": r.text_f1_max,
|
||||
"dates_agree": None if pd.isna(r.dates_agree) else bool(r.dates_agree),
|
||||
"pages_sharing_image": int(r.shared) if r.matched else 0}}
|
||||
if r.matched:
|
||||
rec["content"] = by_id[r.image_id]
|
||||
rec["content_sha256"] = ocr_hub.content_sha256(rec["content"])
|
||||
ocr_hub.write_page(rec)
|
||||
|
||||
docs = (ddr.assign(report_id=ddr["file"].map(lambda f: Path(f).stem), ok=ddr["matched"].astype(int),
|
||||
missing=(~ddr["matched"]).astype(int))
|
||||
.groupby(["report_id", "doc_sha256", "n_pages"], as_index=False)[["ok", "missing"]].sum())
|
||||
for col in ("failed", "skipped", "looped", "length_capped", "prompt_tokens", "completion_tokens"):
|
||||
docs[col] = 0
|
||||
docs["seconds"] = 0.0
|
||||
docs = docs[["report_id", "doc_sha256", "n_pages", "ok", "failed", "skipped", "missing", "looped",
|
||||
"length_capped", "seconds", "prompt_tokens", "completion_tokens"]]
|
||||
docs.to_csv(paths.outputs_dir() / "ocr" / "hub_docs.csv", index=False)
|
||||
|
||||
# The same pages read through the service (the pilot): how far apart are the two OCRs?
|
||||
cfg = ocr.load_config()
|
||||
comp = []
|
||||
for r in ddr[ddr["matched"]].itertuples(index=False):
|
||||
rec = ocr.cached(r.doc_sha256, r.page, cfg)
|
||||
if rec is None or rec["status"] != "ok":
|
||||
continue
|
||||
a, b = page_text(rec["content"]), page_text(by_id[r.image_id])
|
||||
comp.append({"file": r.file, "page": r.page, "service_chars": len(a), "hub_chars": len(b),
|
||||
"edits": Levenshtein.distance(a, b), "identical": a == b,
|
||||
"service_blocks": len(ocr.html_blocks(rec["content"], 1)),
|
||||
"hub_blocks": len(ocr.html_blocks(by_id[r.image_id], 1))})
|
||||
comp = pd.DataFrame(comp)
|
||||
comp.to_csv(out / "service_vs_hub.csv", index=False)
|
||||
|
||||
used = set(m.loc[m["matched"], "image_id"])
|
||||
nonblank = ddr[ddr["pdf_tokens"] > 0]
|
||||
same_text = ddr[ddr["matched"]].groupby("image_id")["pdf_tokens"].nunique()
|
||||
summary = {
|
||||
"export_file": exp.file.name, "export_sha256": exp.sha256, "images": len(ids),
|
||||
"blocks": sum(map(len, exp.blocks.values())), "orphan_pngs": len(exp.orphans),
|
||||
"pdf_pages": len(m), "ddr_pages": len(ddr), "ddr_pages_matched": int(ddr["matched"].sum()),
|
||||
"ddr_blank_pages": int((ddr["pdf_tokens"] == 0).sum()),
|
||||
"ddr_blank_pages_matched": int(ddr.loc[ddr["pdf_tokens"] == 0, "matched"].sum()),
|
||||
"ddr_text_pages_missing": nonblank.loc[~nonblank["matched"], ["file", "page", "corr"]].to_dict("records"),
|
||||
"ddr_reports": len(docs), "ddr_reports_complete": int((docs["ok"] == docs["n_pages"]).sum()),
|
||||
"other_pages_matched": int(m.loc[~m["ddr"], "matched"].sum()), "other_pages": int((~m["ddr"]).sum()),
|
||||
"images_used": len(used), "images_unused": len(ids) - len(used),
|
||||
"images_shared_by_ddr_pages": int((ddr[ddr["matched"]].groupby("image_id").size() > 1).sum()),
|
||||
"shared_images_with_different_token_counts": int((same_text > 1).sum()),
|
||||
"ddr_corr_quantiles": {q: round(float(ddr.loc[ddr["matched"], "corr"].quantile(q)), 4)
|
||||
for q in (0.0, 0.01, 0.5)},
|
||||
"ddr_stage": ddr["stage"].value_counts().to_dict(),
|
||||
"ddr_ties_within_eps": int((ddr["matched"] & (ddr["corr_other"] >= ddr["corr"] - hc.tie_eps)).sum()),
|
||||
"ddr_text_f1_below_candidate_max": int((ddr["matched"] & (ddr["text_f1"] < ddr["text_f1_max"])).sum()),
|
||||
"ddr_dated_pages": int(ddr["dates_agree"].notna().sum()),
|
||||
"ddr_dates_disagree": ddr.loc[ddr["dates_agree"] == False, # noqa: E712
|
||||
["file", "page", "image_id", "stage", "corr", "text_f1"]].to_dict("records"),
|
||||
"ddr_rejected_by_text_f1": int((~ddr["matched"] & (ddr["corr"] >= hc.min_corr)).sum()),
|
||||
"tie_eps_sensitivity": sens,
|
||||
"orphans": orphans.to_dict("records"),
|
||||
"service_vs_hub": {"pages": len(comp), "identical_pages": int(comp["identical"].sum()) if len(comp) else 0,
|
||||
"char_edit_rate": round(comp["edits"].sum() / comp["service_chars"].sum(), 5)
|
||||
if len(comp) else None},
|
||||
"seconds": round(time.time() - t0, 1),
|
||||
}
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
print(json.dumps(summary, indent=1, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,6 +1,7 @@
|
||||
"""OCR fidelity: does chandra read from the PDF what the publisher HTML prints?
|
||||
|
||||
python scripts/05_ocr_qc.py # after 04_ocr.py; every report whose pages are all read
|
||||
python scripts/05_ocr_qc.py # after 04_ocr.py; every report whose pages are all read
|
||||
python scripts/05_ocr_qc.py --source hub # after 04_ocr_hub.py: the Dataset Hub OCR export
|
||||
|
||||
ref = the publisher HTML (`rendered.parse_html`), hyp = chandra's blocks of the PDF (`rendered.parse_ocr`), compared
|
||||
with `qc.exact` (whitespace collapsed, nothing else forgiven). The PDF is a render of the HTML, so the HTML is the
|
||||
@@ -10,12 +11,13 @@ fields, texts and tables that chandra read but the HTML does not print) as inser
|
||||
counted on near misses only (edits at most `NEAR` of the reference characters): a cell read into the wrong row or
|
||||
column is a structure error, not a character error.
|
||||
|
||||
Writes outputs/ocr_qc/{items.parquet, doc_metrics.csv, by_field.csv, by_column.csv, confusions.csv, examples.csv,
|
||||
summary.json, summary.md}.
|
||||
Writes outputs/ocr_qc/ (outputs/ocr_qc_hub/ with --source hub): items.parquet, doc_metrics.csv, by_field.csv,
|
||||
by_column.csv, confusions.csv, examples.csv, summary.json, summary.md.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
import sys
|
||||
@@ -23,7 +25,7 @@ import sys
|
||||
import pandas as pd
|
||||
from rapidfuzz.distance import Levenshtein
|
||||
|
||||
from volve_dia import ocr, paths
|
||||
from volve_dia import ocr, ocr_hub, paths
|
||||
from volve_dia.ddr import qc
|
||||
from volve_dia.ddr.rendered import parse_html, parse_ocr
|
||||
|
||||
@@ -56,17 +58,29 @@ def confusions(df: pd.DataFrame) -> pd.DataFrame:
|
||||
return pd.DataFrame([{"op": t, "ref": a, "hyp": b, "n": n} for (t, a, b), n in c.most_common()])
|
||||
|
||||
|
||||
SOURCES = {"service": ("ddr_docs.csv", "ocr_qc", "chandra OCR of the PDF (OCR service)"),
|
||||
"hub": ("hub_docs.csv", "ocr_qc_hub", "chandra OCR of the PDF (Dataset Hub export)")}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--source", choices=sorted(SOURCES), default="service")
|
||||
args = ap.parse_args()
|
||||
docs_csv, out_name, title = SOURCES[args.source]
|
||||
cfg = ocr.load_config()
|
||||
docs = pd.read_csv(paths.outputs_dir() / "ocr" / "ddr_docs.csv")
|
||||
|
||||
def load(sha: str, n: int):
|
||||
return ocr_hub.load_blocks(sha, n) if args.source == "hub" else ocr.load_blocks(sha, n, cfg)
|
||||
|
||||
docs = pd.read_csv(paths.outputs_dir() / "ocr" / docs_csv)
|
||||
complete = docs[docs["ok"] == docs["n_pages"]]
|
||||
out = paths.outputs_dir() / "ocr_qc"
|
||||
out = paths.outputs_dir() / out_name
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
rows, metrics = [], []
|
||||
for d in complete.to_dict("records"):
|
||||
html = (paths.ddr_html_dir() / f"{d['report_id']}.html").read_text(encoding="utf-8")
|
||||
blocks, _ = ocr.load_blocks(d["doc_sha256"], int(d["n_pages"]), cfg)
|
||||
blocks, _ = load(d["doc_sha256"], int(d["n_pages"]))
|
||||
hyp = parse_ocr(blocks)
|
||||
its = [{"doc": d["report_id"], **it} for it in qc.compare(parse_html(html), hyp)]
|
||||
rows += its
|
||||
@@ -104,7 +118,8 @@ def main() -> int:
|
||||
by_table = table((("cell", t, ""), g) for t, g in df[df["part"] == "cell"].groupby("table"))
|
||||
notes = collections.Counter(n.split(":")[0] for s in dm["notes"] for n in s.split(" | ") if n)
|
||||
summary = {
|
||||
"docs": len(dm), "docs_partly_read": int(((docs["ok"] > 0) & (docs["ok"] < docs["n_pages"])).sum()),
|
||||
"source": args.source, "docs": len(dm), "docs_not_complete": int((docs["ok"] < docs["n_pages"]).sum()),
|
||||
"docs_partly_read": int(((docs["ok"] > 0) & (docs["ok"] < docs["n_pages"])).sum()),
|
||||
"pages": int(dm["pages"].sum()),
|
||||
"content": rates(content),
|
||||
"by_part": {p: rates(g) for p, g in df.groupby("part")},
|
||||
@@ -118,7 +133,7 @@ def main() -> int:
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
|
||||
c = summary["content"]
|
||||
lines = ["# OCR fidelity: publisher HTML vs chandra OCR of the PDF", "",
|
||||
lines = [f"# OCR fidelity: publisher HTML vs {title}", "",
|
||||
f"{summary['docs']} reports, {summary['pages']} pages. Content items (header, fields, texts, table "
|
||||
f"cells and column heads): {c['n']:,}, exact {c['exact_rate']:.4f}, CER {pct(c['cer'])}, "
|
||||
f"WER {pct(c['wer'])}.", "", "| part | items | exact rate | CER | WER |", "|---|---:|---:|---:|---:|"]
|
||||
|
||||
650
scripts/06_parse_witsml.py
Normal file
650
scripts/06_parse_witsml.py
Normal file
@@ -0,0 +1,650 @@
|
||||
"""Parse the WITSML real-time objects and the formation tops into tables.
|
||||
|
||||
python scripts/06_parse_witsml.py [--workers 8]
|
||||
python scripts/06_parse_witsml.py --match F-15S # a subset, for testing: written to outputs/witsml_subset/,
|
||||
# no EXPECTED check, no cross-source checks
|
||||
|
||||
Writes outputs/witsml/ (needs outputs/ddr/volve_ddr.duckdb from 02 for the cross-source checks):
|
||||
|
||||
time_log/<wellbore>.parquet, depth_log/<wellbore>.parquet long log tables, one file per wellbore, sorted by
|
||||
(mnemonic, index); zstd
|
||||
<table>.parquet every other table
|
||||
volve_witsml.duckdb the small tables, and views over the parquet files
|
||||
for the log data (`time_log`, `depth_log`, their
|
||||
`_dedup` versions, `drill_depth`)
|
||||
summary.json counts, duplicates, sentinels, cross-source checks
|
||||
|
||||
and outputs/tops/{well_picks,shared_trunk_picks}.parquet (also tables `formation_tops`, `formation_tops_shared`
|
||||
and the view `formation_tops_all` of volve_witsml.duckdb).
|
||||
|
||||
Fails if a count differs from EXPECTED, so a parser change that loses or adds rows is caught, and if the hole
|
||||
depth of a WITSML wellbore agrees better with another DDR wellbore than with the one it is mapped to.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import duckdb
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
|
||||
from volve_dia import paths, tops, witsml
|
||||
|
||||
warnings.filterwarnings("ignore", message=".*inplace keyword.*") # raised inside duckdb's .df() by pandas 3.1
|
||||
|
||||
#: Counts of the run of 17/11/2026 (2,047 logs in 7,150 files; 33 wellbore folders -> 21 DDR wellbores).
|
||||
#: `log_values` are the rows of time_log and depth_log; `log_values_dropped_in_log` the repeats removed inside a
|
||||
#: log; `log_values_ranked` the rows with dup_rank > 0 (the same mnemonic and index in another log of the wellbore).
|
||||
EXPECTED = {
|
||||
"log_files": 7150,
|
||||
"logs": {"depth": 960, "time": 1087},
|
||||
"log_rows": {"depth": 2740760, "time": 53301664},
|
||||
"log_values": {"depth": 45436597, "time": 2249583611},
|
||||
"log_values_dropped_in_log": {"depth": 1311, "time": 2904492},
|
||||
"log_values_ranked": {"depth": 7543003, "time": 107353349},
|
||||
"log_bad_rows": 0,
|
||||
"wellbores_with_logs": 21,
|
||||
"trajectories": 63, "trajectory_stations": 5561,
|
||||
"messages": 11134, "bha_runs": 161,
|
||||
"mudlogs": 8, "mudlog_intervals": 2882, "mudlog_lithology": 3617, "mudlog_qualifiers": 2951,
|
||||
"sentinels_replaced": 3703,
|
||||
"formation_tops": 409, "formation_tops_wellbores": 35, "formation_tops_ddr_wellbores": 24,
|
||||
"formation_tops_shared": 6,
|
||||
}
|
||||
|
||||
HEADER_FIELDS = ["uidWell", "uidWellbore", "uid", "nameWell", "nameWellbore", "name", "serviceCompany",
|
||||
"runNumber", "bhaRunNumber", "pass", "creationDate", "description", "objectGrowing", "indexType",
|
||||
"indexCurve", "direction", "nullValue", "startIndex", "endIndex", "startDateTimeIndex",
|
||||
"endDateTimeIndex", "commonData_sourceName", "commonData_dTimCreation",
|
||||
"commonData_dTimLastChange"]
|
||||
CURVE_FIELDS = ["unit", "typeLogData", "nullValue", "classWitsml", "curveDescription", "dataSource", "mnemAlias",
|
||||
"alternateIndex"]
|
||||
CURVE_COUNTS = ["n_values", "n_text", "n_not_number", "n_nan", "n_null_value", "n_dup_same", "n_dup_conflict",
|
||||
"n_out_of_order", "n_ranked"]
|
||||
#: A DDR depth and a WITSML depth are compared when the WITSML value is at most this old at the report end.
|
||||
MAX_AGE = "1 hour"
|
||||
#: A DDR survey station and a WITSML trajectory station are the same station when their MD differ by at most this.
|
||||
SURVEY_MD_TOLERANCE = 0.5
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# logs: one worker per wellbore
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def log_tasks(root: Path, out: Path, match: str | None) -> list[tuple]:
|
||||
"""Logs grouped by DDR wellbore (the header of the first chunk file names it), largest wellbore first."""
|
||||
groups: dict[str, list] = collections.defaultdict(list)
|
||||
for log_id, (folder, wb_dir, directory, files) in enumerate(witsml.find_logs(root)):
|
||||
if match and match not in str(directory):
|
||||
continue
|
||||
h = witsml.read_log_file(files[0], header_only=True).header
|
||||
wellbore, _ = witsml.wellbore_name(h.get("nameWell", ""), h.get("nameWellbore", ""), h.get("uidWellbore"))
|
||||
groups[wellbore].append((log_id, folder, wb_dir, directory, files))
|
||||
size = {wb: sum(f.stat().st_size for log in logs for f in log[4]) for wb, logs in groups.items()}
|
||||
return [(wb, groups[wb], root, out) for wb in sorted(groups, key=lambda wb: -size[wb])]
|
||||
|
||||
|
||||
def one_thread() -> None:
|
||||
"""Worker initialiser: Arrow would otherwise start one thread per core in every worker."""
|
||||
pa.set_cpu_count(1)
|
||||
pa.set_io_thread_count(1)
|
||||
|
||||
|
||||
def process_wellbore(task) -> dict:
|
||||
"""Parse every log of one wellbore, write its two long tables, return the catalog rows."""
|
||||
wellbore, logs, root, out = task
|
||||
catalog, curve_rows = [], {}
|
||||
curves: dict[str, dict[str, list]] = {"time": collections.defaultdict(list),
|
||||
"depth": collections.defaultdict(list)}
|
||||
hours: set[int] = set()
|
||||
for log_id, folder, wb_dir, directory, files in logs:
|
||||
t0 = time.time()
|
||||
log = witsml.parse_log(files)
|
||||
h = log.header
|
||||
name_well, name_wellbore = h.get("nameWell", ""), h.get("nameWellbore", "")
|
||||
_, source = witsml.wellbore_name(name_well, name_wellbore, h.get("uidWellbore"))
|
||||
settings = h.get("name") in witsml.SETTINGS_LOGS
|
||||
cat = {"log_id": log_id, "wellbore": wellbore, "wellbore_source": source,
|
||||
"wellbore_witsml": witsml.published_wellbore(name_well, name_wellbore)[0], "folder": folder,
|
||||
"wb_dir": wb_dir, "path": directory.relative_to(root).as_posix(), "kind": log.kind,
|
||||
"log_class": "settings" if settings else "data", "n_files": len(files),
|
||||
"bytes": sum(f.stat().st_size for f in files)}
|
||||
cat.update({k: h.get(k) for k in HEADER_FIELDS})
|
||||
cat["index_unit"] = log.index_unit
|
||||
ist = log.index_stats()
|
||||
cat.update(n_rows=log.counts["rows"], n_bad_rows=log.counts["bad_rows"],
|
||||
n_index_distinct=ist.get("n_index_distinct", 0), n_index_backwards=ist.get("n_index_backwards", 0),
|
||||
step_median=ist.get("step_median"), step_p10=ist.get("step_p10"), step_p90=ist.get("step_p90"),
|
||||
n_curves_declared=len(log.curve_info))
|
||||
index_key = "time" if log.kind == "time" else "md"
|
||||
if ist["n_index_values"]:
|
||||
cat[f"{index_key}_min"], cat[f"{index_key}_max"] = ist["index_min"], ist["index_max"]
|
||||
if log.kind == "time" and not settings:
|
||||
hours.update(np.unique(np.concatenate(log.index_values) // 3_600_000).tolist())
|
||||
declared = dict(log.curve_info)
|
||||
n_values = n_with_data = 0
|
||||
for c in log.curves(log_id):
|
||||
info = declared.pop(c.mnemonic)
|
||||
row = {"log_id": log_id, "wellbore": wellbore, "kind": log.kind, "mnemonic": c.mnemonic,
|
||||
"is_index": False, "undeclared": bool(info.get("undeclared"))}
|
||||
row.update({k: info.get(k) for k in CURVE_FIELDS})
|
||||
row.update({k: v for k, v in c.stats.items()})
|
||||
row[f"{index_key}_min"], row[f"{index_key}_max"] = c.index[0], c.index[-1]
|
||||
curve_rows[(log_id, c.mnemonic)] = row
|
||||
curves[log.kind][c.mnemonic].append(c)
|
||||
n_values += len(c.index)
|
||||
n_with_data += 1
|
||||
for name, info in declared.items(): # declared, without a value in any chunk file
|
||||
row = {"log_id": log_id, "wellbore": wellbore, "kind": log.kind, "mnemonic": name,
|
||||
"is_index": name == h.get("indexCurve"), "undeclared": False, "n_values": 0}
|
||||
row.update({k: info.get(k) for k in CURVE_FIELDS})
|
||||
curve_rows[(log_id, name)] = row
|
||||
cat.update(n_curves_with_data=n_with_data, n_values=n_values, seconds=round(time.time() - t0, 2))
|
||||
catalog.append(cat)
|
||||
del log
|
||||
overlaps, written = [], {}
|
||||
for kind, by_mnemonic in curves.items():
|
||||
if not by_mnemonic:
|
||||
continue
|
||||
target = out / f"{kind}_log" / f"{witsml.wellbore_dir(wellbore)}.parquet"
|
||||
writer = witsml.LongWriter(target, kind, wellbore, list(by_mnemonic))
|
||||
for mnemonic in sorted(by_mnemonic):
|
||||
log_id, index, value, text, chunk, rank, pairs = witsml.merge_curve(by_mnemonic[mnemonic])
|
||||
by_mnemonic[mnemonic] = None # free the per-log arrays
|
||||
writer.write(mnemonic, log_id, index, value, text, chunk, rank)
|
||||
for p in pairs:
|
||||
overlaps.append({"wellbore": wellbore, "kind": kind, "mnemonic": mnemonic, **p})
|
||||
if pairs:
|
||||
ids, counts = np.unique(log_id[rank > 0], return_counts=True)
|
||||
for i, n in zip(ids.tolist(), counts.tolist()):
|
||||
curve_rows[(i, mnemonic)]["n_ranked"] = n
|
||||
writer.close()
|
||||
written[kind] = {"file": target.relative_to(out).as_posix(), "rows": writer.rows,
|
||||
"bytes": target.stat().st_size}
|
||||
return {"wellbore": wellbore, "catalog": catalog, "curves": list(curve_rows.values()), "overlaps": overlaps,
|
||||
"written": written, "hours": sorted(hours)}
|
||||
|
||||
|
||||
def log_tables(results: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
cat = pd.DataFrame([c for r in results for c in r["catalog"]]).sort_values("log_id", ignore_index=True)
|
||||
cur = pd.DataFrame([c for r in results for c in r["curves"]]).sort_values(["log_id", "mnemonic"],
|
||||
ignore_index=True)
|
||||
for c in CURVE_COUNTS:
|
||||
cur[c] = cur[c].fillna(0).astype("int64") if c in cur else 0
|
||||
stat_cols = sorted(c for c in cur.columns if c.startswith(("suspect:", "sentinel:")))
|
||||
stats = cur.melt(id_vars=["log_id", "wellbore", "kind", "mnemonic"], value_vars=stat_cols, var_name="stat",
|
||||
value_name="n")
|
||||
stats = stats[stats["n"] > 0].astype({"n": "int64"})
|
||||
stats[["stat", "value"]] = stats["stat"].str.split(":", n=1, expand=True) if len(stats) else None
|
||||
suspects = stats.loc[stats["stat"] == "suspect", ["log_id", "wellbore", "kind", "mnemonic", "value", "n"]]
|
||||
removed = [{"table": f"{r.kind}_log", "column": r.mnemonic, "value": float(r.value), "n": r.n,
|
||||
"kind": "sentinel"} for r in stats[stats["stat"] == "sentinel"].itertuples()]
|
||||
removed += [{"table": f"{r.kind}_log", "column": r.mnemonic, "value": float(r.nullValue), "n": r.n_null_value,
|
||||
"kind": "nullValue"} for r in cur[cur["n_null_value"] > 0].itertuples()]
|
||||
cur = cur.drop(columns=stat_cols)
|
||||
for df in (cat, cur):
|
||||
for c in ("time_min", "time_max"):
|
||||
if c in df:
|
||||
df[c] = pd.to_datetime(df[c], unit="ms", utc=True)
|
||||
counts = cur.groupby("log_id")[["n_dup_same", "n_dup_conflict", "n_out_of_order", "n_ranked", "n_text"]].sum()
|
||||
cat = cat.join(counts, on="log_id")
|
||||
cat[counts.columns] = cat[counts.columns].fillna(0).astype("int64")
|
||||
ov = pd.DataFrame([o for r in results for o in r["overlaps"]],
|
||||
columns=["wellbore", "kind", "mnemonic", "log_id", "other_log_id", "n", "n_same",
|
||||
"n_rounding", "n_conflict", "max_abs_diff"])
|
||||
hours = pd.DataFrame([(r["wellbore"], h) for r in results for h in r["hours"]], columns=["wellbore", "hour"])
|
||||
hours["hour"] = pd.to_datetime(hours["hour"] * 3600, unit="s", utc=True)
|
||||
sent = pd.DataFrame(removed, columns=["table", "column", "value", "n", "kind"])
|
||||
if len(sent):
|
||||
sent = sent.groupby(["table", "column", "value", "kind"], as_index=False)["n"].sum()
|
||||
units = cur[cur["n_values"] > 0].groupby(["kind", "mnemonic", "unit"], dropna=False).agg(
|
||||
n=("n_values", "sum"), n_logs=("log_id", "count")).reset_index()
|
||||
units = pd.DataFrame({"table": units["kind"] + "_log", "column": units["mnemonic"], "uom": units["unit"],
|
||||
"n": units["n"], "uom_stored": units["unit"], "factor": 1.0, "n_logs": units["n_logs"]})
|
||||
return {"log_catalog": cat, "log_curves": cur, "log_overlaps": ov, "log_hours": hours,
|
||||
"log_suspects": suspects.sort_values(["log_id", "mnemonic", "value"], ignore_index=True),
|
||||
"_sentinels": sent, "_units": units}
|
||||
|
||||
|
||||
def wellbores_table(t: dict[str, pd.DataFrame], ddr_wellbores: set[str]) -> pd.DataFrame:
|
||||
"""One row per WITSML wellbore (well folder + numbered subfolder): names, DDR wellbore, object counts."""
|
||||
key = ["folder", "wb_dir", "uidWellbore", "nameWell", "nameWellbore", "wellbore_witsml", "wellbore",
|
||||
"wellbore_source"]
|
||||
parts = []
|
||||
cat = t["log_catalog"]
|
||||
for kind in ("time", "depth"):
|
||||
part = cat[cat["kind"] == kind].groupby(key, dropna=False).agg(
|
||||
n=("log_id", "count"), n_values=("n_values", "sum")).reset_index()
|
||||
parts.append(part.rename(columns={"n": f"n_{kind}_logs", "n_values": f"n_{kind}_values"}))
|
||||
for table, column in (("trajectory_catalog", "n_trajectories"), ("messages", "n_messages"),
|
||||
("bha_runs", "n_bha_runs"), ("mudlog_catalog", "n_mudlogs")):
|
||||
df = t[table].assign(wb_dir=t[table]["path"].str.split("/").str[1])
|
||||
parts.append(df.groupby(key, dropna=False).size().rename(column).reset_index())
|
||||
out = parts[0]
|
||||
for p in parts[1:]:
|
||||
out = out.merge(p, on=key, how="outer")
|
||||
counts = [c for c in out.columns if c.startswith("n_")]
|
||||
out[counts] = out[counts].fillna(0).astype("int64")
|
||||
out["in_ddr"] = out["wellbore"].isin(ddr_wellbores)
|
||||
return out.sort_values(["wellbore", "folder", "wb_dir"], ignore_index=True)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# DuckDB and the cross-source checks
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def build_db(out: Path, tables: dict[str, pd.DataFrame], ddr_db: Path, workers: int) -> duckdb.DuckDBPyConnection:
|
||||
db = out / "volve_witsml.duckdb.tmp"
|
||||
db.unlink(missing_ok=True)
|
||||
con = duckdb.connect(str(db))
|
||||
con.execute(f"SET threads = {workers}")
|
||||
con.execute("SET memory_limit = '32GB'")
|
||||
for name in tables:
|
||||
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
|
||||
for name, sql in witsml.view_sql(out.resolve()).items():
|
||||
con.execute(f"CREATE VIEW {name} AS {sql}")
|
||||
con.execute("CREATE VIEW formation_tops_all AS SELECT *, NULL::VARCHAR AS inherited_from, NULL::DOUBLE AS "
|
||||
"md_kickoff FROM formation_tops UNION ALL SELECT * FROM formation_tops_shared")
|
||||
con.execute(f"ATTACH '{ddr_db}' AS ddr (READ_ONLY)")
|
||||
return con
|
||||
|
||||
|
||||
def _quantiles(s: pd.Series, digits: int = 3) -> dict:
|
||||
if not len(s):
|
||||
return {"n": 0}
|
||||
q = s.quantile([0.05, 0.25, 0.5, 0.75, 0.95])
|
||||
return {"n": int(len(s)), "p05": round(float(q[0.05]), digits), "p25": round(float(q[0.25]), digits),
|
||||
"median": round(float(q[0.5]), digits), "p75": round(float(q[0.75]), digits),
|
||||
"p95": round(float(q[0.95]), digits), "max_abs": round(float(s.abs().max()), digits)}
|
||||
|
||||
|
||||
def check_identity(con) -> tuple[pd.DataFrame, list[str]]:
|
||||
"""Hole depth of every WITSML wellbore at the end of the DDR report periods of every DDR wellbore of its
|
||||
slot. A WITSML wellbore must agree best with the DDR wellbore it is mapped to."""
|
||||
con.execute(f"""
|
||||
CREATE TEMP TABLE hole_uid AS
|
||||
SELECT c.uidWellbore, any_value(c.wellbore) AS wellbore, any_value(c.wellbore_witsml) AS wellbore_witsml,
|
||||
d.time, first(d.value ORDER BY c.n_values DESC, c.log_id) AS md
|
||||
FROM time_log d JOIN log_catalog c USING (log_id)
|
||||
WHERE d.mnemonic IN ({', '.join(repr(m) for m in witsml.HOLE_DEPTH)}) AND d.value IS NOT NULL
|
||||
AND ({witsml.depth_filter(witsml.HOLE_DEPTH)})
|
||||
GROUP BY c.uidWellbore, d.time""")
|
||||
df = con.execute(f"""
|
||||
WITH u AS (SELECT DISTINCT uidWellbore, wellbore, wellbore_witsml FROM hole_uid),
|
||||
r AS (SELECT u.*, p.wellbore AS ddr_wellbore, p.end_utc, p.md AS ddr_md
|
||||
FROM ddr.reports p JOIN u ON split_part(p.wellbore, ' ', 1) = split_part(u.wellbore, ' ', 1)
|
||||
WHERE p.md IS NOT NULL)
|
||||
SELECT r.uidWellbore, r.wellbore_witsml, r.wellbore AS mapped, r.ddr_wellbore, count(*) AS n_reports,
|
||||
round(median(abs(h.md - r.ddr_md)), 3) AS median_abs_diff_m,
|
||||
sum((abs(h.md - r.ddr_md) <= 5)::INT) AS n_within_5m
|
||||
FROM r ASOF JOIN hole_uid h ON h.uidWellbore = r.uidWellbore AND r.end_utc >= h.time
|
||||
WHERE r.end_utc - h.time <= INTERVAL {MAX_AGE}
|
||||
GROUP BY ALL ORDER BY r.wellbore_witsml, r.uidWellbore, r.ddr_wellbore""").df()
|
||||
best = df.sort_values(["n_within_5m", "n_reports"], ascending=False).groupby("uidWellbore").head(1)
|
||||
mapped = df[df["mapped"] == df["ddr_wellbore"]].set_index("uidWellbore")["n_within_5m"]
|
||||
wrong = [f"{r.uidWellbore} ({r.wellbore_witsml}) is mapped to {r.mapped} but agrees best with {r.ddr_wellbore}"
|
||||
for r in best.itertuples() if r.n_within_5m > mapped.get(r.uidWellbore, 0)]
|
||||
return df, wrong
|
||||
|
||||
|
||||
def check_depth(con) -> tuple[pd.DataFrame, dict]:
|
||||
"""WITSML hole depth and bit depth at the end of every DDR report period against `md` of the DDR."""
|
||||
con.execute("CREATE TEMP TABLE dd AS SELECT * FROM drill_depth")
|
||||
df = con.execute(f"""
|
||||
WITH r AS (SELECT report_id, wellbore, end_utc, md AS ddr_md,
|
||||
md - lag(md) OVER (PARTITION BY wellbore ORDER BY end_utc) AS ddr_md_change
|
||||
FROM ddr.reports),
|
||||
h AS (SELECT r.report_id, d.md AS hole_md, d.time AS hole_time, d.log_id AS hole_log_id
|
||||
FROM r ASOF JOIN (SELECT * FROM dd WHERE depth = 'hole') d
|
||||
ON d.wellbore = r.wellbore AND r.end_utc >= d.time
|
||||
WHERE r.end_utc - d.time <= INTERVAL {MAX_AGE}),
|
||||
b AS (SELECT r.report_id, d.md AS bit_md, d.time AS bit_time
|
||||
FROM r ASOF JOIN (SELECT * FROM dd WHERE depth = 'bit') d
|
||||
ON d.wellbore = r.wellbore AND r.end_utc >= d.time
|
||||
WHERE r.end_utc - d.time <= INTERVAL {MAX_AGE})
|
||||
SELECT r.*, h.hole_md, h.hole_time, h.hole_log_id, c.serviceCompany, b.bit_md, b.bit_time,
|
||||
h.hole_md - r.ddr_md AS hole_diff, b.bit_md - r.ddr_md AS bit_diff
|
||||
FROM r LEFT JOIN h USING (report_id) LEFT JOIN b USING (report_id)
|
||||
LEFT JOIN log_catalog c ON c.log_id = h.hole_log_id
|
||||
ORDER BY r.wellbore, r.end_utc""").df()
|
||||
both = df[df["ddr_md"].notna() & df["hole_md"].notna()]
|
||||
d = both["hole_diff"]
|
||||
|
||||
def share(s: pd.Series) -> dict:
|
||||
return {"n": int(len(s)), "within_1m": int((s.abs() <= 1).sum()), "within_5m": int((s.abs() <= 5).sum()),
|
||||
"within_50m": int((s.abs() <= 50).sum()), "beyond_50m": int((s.abs() > 50).sum()),
|
||||
**{k: v for k, v in _quantiles(s).items() if k != "n"}}
|
||||
|
||||
far = both[d.abs() > 50]
|
||||
summary = {
|
||||
"max_age": MAX_AGE,
|
||||
"ddr_reports": int(len(df)), "ddr_reports_with_md": int(df["ddr_md"].notna().sum()),
|
||||
"reports_with_witsml_hole_depth": int(df["hole_md"].notna().sum()),
|
||||
"reports_with_both": int(len(both)),
|
||||
"hole_minus_ddr_m": share(d),
|
||||
"hole_minus_ddr_m_by_company": {k: share(g["hole_diff"]) for k, g in both.groupby("serviceCompany")},
|
||||
"hole_minus_ddr_m_when_ddr_md_increased": share(both.loc[both["ddr_md_change"] > 0, "hole_diff"]),
|
||||
"hole_minus_ddr_m_when_ddr_md_did_not_increase": share(both.loc[~(both["ddr_md_change"] > 0), "hole_diff"]),
|
||||
"beyond_50m": {"witsml_deeper": int((far["hole_diff"] > 0).sum()),
|
||||
"witsml_shallower": int((far["hole_diff"] < 0).sum()),
|
||||
"witsml_hole_depth_is_0": int((far["hole_md"] == 0).sum()),
|
||||
"per_wellbore": {k: int(v) for k, v in far.groupby("wellbore").size().items()}},
|
||||
"bit_minus_ddr_m": share(df.loc[df["ddr_md"].notna() & df["bit_md"].notna(), "bit_diff"]),
|
||||
"reports_per_wellbore": {k: int(v) for k, v in both.groupby("wellbore").size().items()},
|
||||
}
|
||||
return df, summary
|
||||
|
||||
|
||||
def check_coverage(con) -> tuple[pd.DataFrame, dict]:
|
||||
"""Hours with time-log data inside every DDR report period, and the WITSML time range against the DDR's."""
|
||||
df = con.execute("""
|
||||
SELECT r.report_id, r.wellbore, r.start_utc, r.end_utc,
|
||||
date_diff('hour', r.start_utc, r.end_utc) AS period_h, count(h.hour) AS hours_with_data
|
||||
FROM ddr.reports r LEFT JOIN log_hours h
|
||||
ON h.wellbore = r.wellbore AND h.hour >= r.start_utc AND h.hour < r.end_utc
|
||||
GROUP BY ALL ORDER BY r.wellbore, r.end_utc""").df()
|
||||
per = con.execute("""
|
||||
WITH w AS (SELECT wellbore, min(hour) AS witsml_first, max(hour) AS witsml_last, count(*) AS witsml_hours
|
||||
FROM log_hours GROUP BY ALL),
|
||||
d AS (SELECT wellbore, min(start_utc) AS ddr_first, max(end_utc) AS ddr_last, count(*) AS ddr_reports
|
||||
FROM ddr.reports WHERE start_utc >= TIMESTAMPTZ '1990-01-01' GROUP BY ALL),
|
||||
inside AS (SELECT h.wellbore, count(DISTINCT h.hour) AS witsml_hours_in_ddr_periods
|
||||
FROM log_hours h JOIN ddr.reports r
|
||||
ON r.wellbore = h.wellbore AND h.hour >= r.start_utc AND h.hour < r.end_utc
|
||||
GROUP BY ALL)
|
||||
SELECT * FROM d FULL JOIN w USING (wellbore) LEFT JOIN inside USING (wellbore) ORDER BY wellbore""").df()
|
||||
agg = df.groupby("wellbore").agg(reports=("report_id", "count"),
|
||||
with_data=("hours_with_data", lambda s: (s > 0).sum()),
|
||||
full=("hours_with_data", lambda s: (s >= 23).sum()))
|
||||
per = per.merge(agg.reset_index(), on="wellbore", how="left")
|
||||
has = per[per["witsml_hours"].notna()]
|
||||
summary = {
|
||||
"ddr_wellbores": int(per["ddr_reports"].notna().sum()),
|
||||
"ddr_wellbores_with_time_logs": int((per["ddr_reports"].notna() & per["witsml_hours"].notna()).sum()),
|
||||
"ddr_wellbores_without_time_logs": sorted(per.loc[per["witsml_hours"].isna(), "wellbore"]),
|
||||
"witsml_wellbores_without_ddr": sorted(per.loc[per["ddr_reports"].isna(), "wellbore"]),
|
||||
"ddr_reports_on_wellbores_with_time_logs": int(has["reports"].sum()),
|
||||
"ddr_reports_with_any_hour_of_data": int((df["hours_with_data"] > 0).sum()),
|
||||
"ddr_reports_with_23h_or_more": int((df["hours_with_data"] >= 23).sum()),
|
||||
"witsml_hours_with_data": int(has["witsml_hours"].sum()),
|
||||
"witsml_hours_inside_a_ddr_period_of_the_wellbore": int(has["witsml_hours_in_ddr_periods"].fillna(0).sum()),
|
||||
"per_wellbore": json.loads(per.assign(
|
||||
**{c: per[c].dt.strftime("%Y-%m-%dT%H:%MZ") for c in
|
||||
("ddr_first", "ddr_last", "witsml_first", "witsml_last")}).to_json(orient="records")),
|
||||
}
|
||||
return df, summary
|
||||
|
||||
|
||||
def check_surveys(con) -> tuple[pd.DataFrame, dict]:
|
||||
"""DDR survey stations against the nearest WITSML trajectory station (actual trajectories) of the wellbore."""
|
||||
df = con.execute(f"""
|
||||
WITH s AS (SELECT DISTINCT wellbore, md, tvd, incl, azi FROM ddr.surveys WHERE md IS NOT NULL),
|
||||
t AS (SELECT t.wellbore, t.md, t.tvd, t.incl, t.azi, t.path, t.seq, c.aziRef, c.serviceCompany
|
||||
FROM trajectory t JOIN trajectory_catalog c USING (path) WHERE c.kind = 'actual'),
|
||||
m AS (SELECT s.*, t.md AS w_md, t.tvd AS w_tvd, t.incl AS w_incl, t.azi AS w_azi, t.path, t.aziRef,
|
||||
row_number() OVER (PARTITION BY s.wellbore, s.md, s.tvd, s.incl, s.azi
|
||||
ORDER BY abs(t.md - s.md), abs(t.incl - s.incl), t.path, t.seq) AS k
|
||||
FROM s JOIN t ON t.wellbore = s.wellbore AND abs(t.md - s.md) <= {SURVEY_MD_TOLERANCE})
|
||||
SELECT s.*, s.wellbore IN (SELECT wellbore FROM t) AS has_trajectory, m.w_md, m.w_tvd, m.w_incl, m.w_azi,
|
||||
m.path, m.aziRef, m.w_md - s.md AS md_diff, m.w_tvd - s.tvd AS tvd_diff, m.w_incl - s.incl AS incl_diff,
|
||||
((m.w_azi - s.azi + 540) % 360) - 180 AS azi_diff
|
||||
FROM s LEFT JOIN (SELECT * FROM m WHERE k = 1) m
|
||||
ON m.wellbore = s.wellbore AND m.md = s.md AND m.tvd IS NOT DISTINCT FROM s.tvd
|
||||
AND m.incl IS NOT DISTINCT FROM s.incl AND m.azi IS NOT DISTINCT FROM s.azi
|
||||
ORDER BY s.wellbore, s.md""").df()
|
||||
hit = df[df["w_md"].notna()]
|
||||
steep = hit[hit["incl"] >= 5] # azimuth is ill-defined in a near-vertical hole
|
||||
summary = {
|
||||
"md_tolerance_m": SURVEY_MD_TOLERANCE,
|
||||
"ddr_survey_stations_distinct": int(len(df)),
|
||||
"on_wellbores_with_witsml_trajectory": int(df["has_trajectory"].sum()),
|
||||
"matched": int(len(hit)),
|
||||
"matched_per_wellbore": {k: int(v) for k, v in hit.groupby("wellbore").size().items()},
|
||||
"incl_diff_deg": {**_quantiles(hit["incl_diff"]), "within_0.1": int((hit["incl_diff"].abs() <= 0.1).sum())},
|
||||
"tvd_diff_m": {**_quantiles(hit["tvd_diff"].dropna()), "within_1m": int((hit["tvd_diff"].abs() <= 1).sum())},
|
||||
"azi_diff_deg_incl_ge_5": {**_quantiles(steep["azi_diff"].dropna()),
|
||||
"within_0.5": int((steep["azi_diff"].abs() <= 0.5).sum())},
|
||||
"azi_diff_deg_incl_ge_5_by_aziRef": {str(k): _quantiles(g["azi_diff"].dropna())
|
||||
for k, g in steep.groupby("aziRef", dropna=False)},
|
||||
}
|
||||
return df, summary
|
||||
|
||||
|
||||
def check_tops(con) -> dict:
|
||||
per = con.execute("""
|
||||
WITH d AS (SELECT wellbore, max(md) AS ddr_md_max FROM ddr.reports GROUP BY ALL),
|
||||
p AS (SELECT wellbore, count(*) FILTER (inherited_from IS NULL) AS picks,
|
||||
count(*) FILTER (inherited_from IS NOT NULL) AS picks_shared, max(md) AS pick_md_max
|
||||
FROM formation_tops_all WHERE wellbore IS NOT NULL GROUP BY ALL)
|
||||
SELECT d.wellbore, coalesce(p.picks, 0) AS picks, coalesce(p.picks_shared, 0) AS picks_shared,
|
||||
p.pick_md_max, d.ddr_md_max
|
||||
FROM d LEFT JOIN p USING (wellbore) ORDER BY 1""").df()
|
||||
# DDR `stratInfo` tops against the picks of the same formation ("Hugin Fm" ~ "Hugin Fm. VOLVE Top")
|
||||
strat = con.execute(r"""
|
||||
SELECT s.wellbore, s.description, s.mdTop AS ddr_md, p.surface, p.md AS pick_md, p.md - s.mdTop AS diff
|
||||
FROM (SELECT DISTINCT wellbore, description, mdTop FROM ddr.strat WHERE mdTop IS NOT NULL) s
|
||||
JOIN formation_tops p ON p.wellbore = s.wellbore AND p.track = 'main' AND p.boundary = 'Top' AND p.obs = 1
|
||||
AND p.unit NOT LIKE '%Sand%'
|
||||
AND lower(regexp_replace(p.unit, '\s+(Fm|GP)\b.*$', ''))
|
||||
= lower(regexp_replace(s.description, '\s+(Fm|Gp)\b.*$', ''))""").df()
|
||||
return {
|
||||
"ddr_wellbores_with_own_picks": int((per["picks"] > 0).sum()),
|
||||
"ddr_wellbores_with_shared_picks_only": sorted(
|
||||
per.loc[(per["picks"] == 0) & (per["picks_shared"] > 0), "wellbore"]),
|
||||
"ddr_wellbores_without_picks": sorted(per.loc[(per["picks"] == 0) & (per["picks_shared"] == 0), "wellbore"]),
|
||||
"picks_below_ddr_md_max": json.loads(per[per["pick_md_max"] > per["ddr_md_max"]].to_json(orient="records")),
|
||||
"ddr_strat_tops_matched_by_name": int(len(strat)),
|
||||
"pick_minus_ddr_strat_m": {**_quantiles(strat["diff"]), "within_5m": int((strat["diff"].abs() <= 5).sum())},
|
||||
"per_wellbore": json.loads(per.to_json(orient="records")),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def du(path: Path) -> int:
|
||||
return sum(f.stat().st_size for f in path.rglob("*") if f.is_file())
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--workers", type=int, default=8)
|
||||
ap.add_argument("--match", default=None, help="only logs whose path contains this text (for testing)")
|
||||
args = ap.parse_args()
|
||||
|
||||
t_start = time.time()
|
||||
root = paths.witsml_dir()
|
||||
out = paths.outputs_dir() / ("witsml_subset" if args.match else "witsml")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
ddr_db = paths.outputs_dir() / "ddr" / "volve_ddr.duckdb"
|
||||
if not ddr_db.is_file():
|
||||
print(f"missing {ddr_db}: run scripts/02_parse_ddr.py first")
|
||||
return 1
|
||||
with duckdb.connect(str(ddr_db), read_only=True) as con:
|
||||
ddr_wellbores = {w for (w,) in con.execute("SELECT DISTINCT wellbore FROM reports").fetchall()}
|
||||
for stale in ("time_log", "depth_log", "log_time", "log_depth"):
|
||||
shutil.rmtree(out / stale, ignore_errors=True)
|
||||
|
||||
# logs
|
||||
tasks = log_tasks(root, out, args.match)
|
||||
results = []
|
||||
with ProcessPoolExecutor(max_workers=args.workers, initializer=one_thread) as ex:
|
||||
for r in ex.map(process_wellbore, tasks, chunksize=1):
|
||||
results.append(r)
|
||||
print(f"[{time.time() - t_start:6.0f} s] {r['wellbore']}: {len(r['catalog'])} logs, " + ", ".join(
|
||||
f"{k} {v['rows']:,} values {v['bytes'] / 1e6:.0f} MB" for k, v in r["written"].items()), flush=True)
|
||||
tables = log_tables(results)
|
||||
# trajectory, message, bhaRun, mudLog
|
||||
objects, flat = witsml.parse_objects(root)
|
||||
tc = objects["trajectory_catalog"]
|
||||
tc["kind"] = np.where(tc["name"].str.contains("Plan Traj"), "plan", "actual")
|
||||
tables.update(objects)
|
||||
tables["sentinels"] = pd.concat([witsml.sentinels_table(flat), tables.pop("_sentinels")], ignore_index=True)
|
||||
tables["units"] = pd.concat([witsml.units_table(flat), tables.pop("_units")], ignore_index=True)
|
||||
tables["units"]["n_logs"] = tables["units"]["n_logs"].astype("Int64") # empty for the object tables
|
||||
tables["wellbores"] = wellbores_table(tables, ddr_wellbores)
|
||||
# formation tops
|
||||
picks = tops.parse_picks(paths.well_picks_file(), ddr_wellbores)
|
||||
tables["formation_tops"], tables["formation_tops_shared"] = picks, tops.shared_trunk_picks(picks)
|
||||
tops_dir = paths.outputs_dir() / ("tops_subset" if args.match else "tops")
|
||||
tops_dir.mkdir(parents=True, exist_ok=True)
|
||||
picks.to_parquet(tops_dir / "well_picks.parquet", index=False)
|
||||
tables["formation_tops_shared"].to_parquet(tops_dir / "shared_trunk_picks.parquet", index=False)
|
||||
for name, df in tables.items():
|
||||
df.to_parquet(out / f"{name}.parquet", index=False, compression="zstd")
|
||||
print(f"[{time.time() - t_start:6.0f} s] tables written", flush=True)
|
||||
|
||||
con = build_db(out, tables, ddr_db, args.workers)
|
||||
checks: dict = {}
|
||||
wrong: list[str] = []
|
||||
if not args.match:
|
||||
identity, wrong = check_identity(con)
|
||||
depth, checks["depth_vs_ddr"] = check_depth(con)
|
||||
coverage, checks["time_coverage_vs_ddr"] = check_coverage(con)
|
||||
surveys, checks["trajectory_vs_ddr_surveys"] = check_surveys(con)
|
||||
checks["formation_tops_vs_ddr"] = check_tops(con)
|
||||
for name, df in (("check_wellbore_identity", identity), ("check_depth", depth),
|
||||
("check_coverage", coverage), ("check_surveys", surveys)):
|
||||
df.to_parquet(out / f"{name}.parquet", index=False, compression="zstd")
|
||||
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
|
||||
tables[name] = df
|
||||
checks["wellbore_identity"] = json.loads(identity.to_json(orient="records"))
|
||||
checks["wellbore_identity_wrong"] = wrong
|
||||
con.execute("DETACH ddr")
|
||||
con.close()
|
||||
os.replace(out / "volve_witsml.duckdb.tmp", out / "volve_witsml.duckdb")
|
||||
|
||||
cat, cur, ov, wb = tables["log_catalog"], tables["log_curves"], tables["log_overlaps"], tables["wellbores"]
|
||||
data = cat[cat["log_class"] == "data"]
|
||||
by_kind = {k: g for k, g in cat.groupby("kind")}
|
||||
gen = data[data["name"] == "GenTime"]
|
||||
slb = data[(data["kind"] == "time") & (data["serviceCompany"] == "Schlumberger")]
|
||||
time_data = data[data["kind"] == "time"]
|
||||
got = {
|
||||
"log_files": int(cat["n_files"].sum()),
|
||||
"logs": {k: int(len(g)) for k, g in by_kind.items()},
|
||||
"log_rows": {k: int(g["n_rows"].sum()) for k, g in by_kind.items()},
|
||||
"log_values": {k: int(g["n_values"].sum()) for k, g in by_kind.items()},
|
||||
"log_values_dropped_in_log": {k: int(g["n_dup_same"].sum() + g["n_dup_conflict"].sum())
|
||||
for k, g in by_kind.items()},
|
||||
"log_values_ranked": {k: int(g["n_ranked"].sum()) for k, g in by_kind.items()},
|
||||
"log_bad_rows": int(cat["n_bad_rows"].sum()),
|
||||
"wellbores_with_logs": int(cat["wellbore"].nunique()),
|
||||
"trajectories": len(tables["trajectory_catalog"]), "trajectory_stations": len(tables["trajectory"]),
|
||||
"messages": len(tables["messages"]), "bha_runs": len(tables["bha_runs"]),
|
||||
"mudlogs": len(tables["mudlog_catalog"]), "mudlog_intervals": len(tables["mudlog_intervals"]),
|
||||
"mudlog_lithology": len(tables["mudlog_lithology"]), "mudlog_qualifiers": len(tables["mudlog_qualifiers"]),
|
||||
"sentinels_replaced": int(tables["sentinels"]["n"].sum()),
|
||||
"formation_tops": len(picks), "formation_tops_wellbores": int(picks["wellbore_picks"].nunique()),
|
||||
"formation_tops_ddr_wellbores": int(picks["wellbore"].nunique()),
|
||||
"formation_tops_shared": len(tables["formation_tops_shared"]),
|
||||
}
|
||||
summary = {
|
||||
"counts": got,
|
||||
"tables": {name: {"rows": len(df), "columns": df.shape[1], "bytes": (out / f"{name}.parquet").stat().st_size}
|
||||
for name, df in tables.items()},
|
||||
"log_data_files": {r["wellbore"]: r["written"] for r in sorted(results, key=lambda r: r["wellbore"])},
|
||||
"disk_bytes": {"time_log": du(out / "time_log"), "depth_log": du(out / "depth_log"),
|
||||
"witsml_total": du(out), "tops": du(tops_dir)},
|
||||
"wellbores": {
|
||||
"witsml_well_folders": sum(p.is_dir() for p in root.iterdir()),
|
||||
"witsml_well_folders_with_objects": int(wb["folder"].nunique()),
|
||||
"witsml_wellbore_folders": int(len(wb)),
|
||||
"witsml_wellbore_names_as_published": int(wb["wellbore_witsml"].nunique()),
|
||||
"wellbores": int(wb["wellbore"].nunique()),
|
||||
"ddr_wellbores_with_any_object": sorted(set(wb.loc[wb["in_ddr"], "wellbore"])),
|
||||
"ddr_wellbores_with_time_logs": sorted(set(time_data["wellbore"]) & ddr_wellbores),
|
||||
"ddr_wellbores_without_any_object": sorted(ddr_wellbores - set(wb["wellbore"])),
|
||||
"not_in_ddr": sorted(set(wb.loc[~wb["in_ddr"], "wellbore"])),
|
||||
"renamed": json.loads(wb.loc[wb["wellbore_source"] == "uidWellbore", [
|
||||
"uidWellbore", "nameWellbore", "wellbore_witsml", "wellbore"]].to_json(orient="records")),
|
||||
"named_from_nameWell": json.loads(wb.loc[wb["wellbore_source"] == "nameWell", [
|
||||
"folder", "nameWellbore", "wellbore"]].to_json(orient="records")),
|
||||
},
|
||||
"channels": {
|
||||
"distinct_mnemonics": {k: int(g["mnemonic"].nunique())
|
||||
for k, g in cur[cur["n_values"] > 0].groupby("kind")},
|
||||
"time_logs_by_service_company": {str(k): int(v) for k, v in
|
||||
time_data.groupby("serviceCompany", dropna=False).size().items()},
|
||||
"GenTime": {"logs": int(len(gen)), "wellbores": int(gen["wellbore"].nunique()),
|
||||
"curves_with_data": sorted({int(v) for v in gen["n_curves_with_data"]}),
|
||||
"curves_declared_incl_index": sorted({int(v) for v in gen["n_curves_declared"]}),
|
||||
"step_median_s": sorted({float(v) for v in gen["step_median"].dropna()}),
|
||||
"values": int(gen["n_values"].sum())},
|
||||
"Schlumberger_time_logs": {"logs": int(len(slb)), "wellbores": int(slb["wellbore"].nunique()),
|
||||
"curves_with_data": _quantiles(slb["n_curves_with_data"], 0),
|
||||
"step_median_s": _quantiles(slb["step_median"].dropna()),
|
||||
"values": int(slb["n_values"].sum())},
|
||||
"time_log_step_median_s_weighted_by_rows": {
|
||||
str(k): int(v) for k, v in time_data.assign(step=time_data["step_median"].round())
|
||||
.groupby("step")["n_rows"].sum().sort_values(ascending=False).head(8).items()},
|
||||
},
|
||||
"values": {
|
||||
"empty_cells_are_not_counted": True,
|
||||
"null_value_replaced": int(cur["n_null_value"].sum()),
|
||||
"sentinels_by_table": {k: int(v) for k, v in tables["sentinels"].groupby("table")["n"].sum().items()},
|
||||
"text_values": {k: int(g["n_text"].sum()) for k, g in cur.groupby("kind")},
|
||||
"not_a_number_in_numeric_curves": {k: int(g["n_not_number"].sum()) for k, g in cur.groupby("kind")},
|
||||
"suspect_values_kept": {str(k): int(v) for k, v in
|
||||
tables["log_suspects"].groupby("value")["n"].sum().items()},
|
||||
"mudlog_intervals_tadi_implausible": int(tables["mudlog_intervals"]["tadi_implausible"].sum()),
|
||||
"unit_conversions": int(tables["units"].loc[tables["units"]["factor"] != 1.0, "n"].sum()),
|
||||
},
|
||||
"trajectories": {
|
||||
"by_kind": {k: {"trajectories": int(len(g)), "stations": int(g["n_stations"].sum())}
|
||||
for k, g in tables["trajectory_catalog"].groupby("kind")},
|
||||
"by_azi_ref": {str(k): int(v) for k, v in
|
||||
tables["trajectory_catalog"].groupby("aziRef", dropna=False).size().items()},
|
||||
"distinct_actual_stations": int(len(
|
||||
tables["trajectory"].merge(tables["trajectory_catalog"].loc[
|
||||
tables["trajectory_catalog"]["kind"] == "actual", ["path"]], on="path")
|
||||
.round({"md": 2, "incl": 2, "azi": 2}).drop_duplicates(["wellbore", "md", "incl", "azi"]))),
|
||||
},
|
||||
"duplicates": {
|
||||
"in_log_same_value": {k: int(g["n_dup_same"].sum()) for k, g in by_kind.items()},
|
||||
"in_log_conflict": {k: int(g["n_dup_conflict"].sum()) for k, g in by_kind.items()},
|
||||
"in_log_logs_affected": int(((cat["n_dup_same"] + cat["n_dup_conflict"]) > 0).sum()),
|
||||
"in_log_values_out_of_order": {k: int(g["n_out_of_order"].sum()) for k, g in by_kind.items()},
|
||||
"between_logs": {k: {"ranked_rows": int(g["n"].sum()), "same": int(g["n_same"].sum()),
|
||||
"rounding": int(g["n_rounding"].sum()), "conflict": int(g["n_conflict"].sum()),
|
||||
"log_pairs": int(len(g.drop_duplicates(["log_id", "other_log_id"]))),
|
||||
"wellbore_mnemonics": int(len(g.drop_duplicates(["wellbore", "mnemonic"])))}
|
||||
for k, g in ov.groupby("kind")},
|
||||
"between_logs_top_mnemonics": json.loads(
|
||||
ov.groupby(["kind", "mnemonic"])[["n", "n_same", "n_rounding", "n_conflict"]].sum()
|
||||
.sort_values("n", ascending=False).head(12).reset_index().to_json(orient="records")),
|
||||
},
|
||||
"checks": checks,
|
||||
"seconds": round(time.time() - t_start, 1),
|
||||
}
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
short = {k: v for k, v in summary.items() if k not in ("tables", "log_data_files", "checks")}
|
||||
short["checks"] = {k: v for k, v in checks.items() if k != "wellbore_identity"}
|
||||
for part in ("time_coverage_vs_ddr", "formation_tops_vs_ddr"):
|
||||
if part in short["checks"]:
|
||||
short["checks"][part] = {k: v for k, v in short["checks"][part].items() if k != "per_wellbore"}
|
||||
print(json.dumps(short, indent=1, ensure_ascii=False))
|
||||
if args.match:
|
||||
return 0
|
||||
if wrong:
|
||||
print("wellbore identity:", *wrong, sep="\n ")
|
||||
return 1
|
||||
diff = {k: (EXPECTED.get(k), got[k]) for k in got if EXPECTED.get(k) != got[k]}
|
||||
if diff:
|
||||
print("counts differ from EXPECTED (expected, got):", diff)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
489
scripts/07_labels.py
Normal file
489
scripts/07_labels.py
Normal file
@@ -0,0 +1,489 @@
|
||||
"""Build the deterministic labels T1-T3 from the DDR tables: outputs/labels/*.parquet, volve_labels.duckdb,
|
||||
summary.json and analysis.md.
|
||||
|
||||
python scripts/07_labels.py # needs outputs/ddr/*.parquet (scripts/02_parse_ddr.py)
|
||||
|
||||
Rules and mapping: configs/labels.yaml and volve_dia/labels.py. The script fails if a count written in labels.yaml
|
||||
differs from the data, or if a label count differs from EXPECTED, so neither the mapping nor the code can change a
|
||||
label unnoticed. Undecided protocol choices are produced side by side (NPT definitions a and b, operation and cause
|
||||
at two levels); summary.json holds what the protocol needs to choose: distributions per wellbore and per well, the
|
||||
number of wellbores and wells that contain each class, rare classes, the fill-rule evaluation, the depth coverage
|
||||
that limits T3 and the rate at which the free text names the label.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import duckdb
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import labels as L
|
||||
from volve_dia import paths
|
||||
|
||||
#: Label counts locked on 17/11/2026 (labels.yaml version 1). A change here is a change of the benchmark labels.
|
||||
EXPECTED = {
|
||||
"report_status": {"no_activities": 8, "ok": 1750, "placeholder_date": 1},
|
||||
"t1_scope": {"drilling_day": 932, "excluded": 1, "no_activities": 8, "other_day": 818},
|
||||
"t1_filled_by": {"bfill_leading": 17, "diaHole": 769, "ffill": 972},
|
||||
"t1_section": {"12.25": 261, "17.5": 154, "26": 105, "36": 67, "6": 49, "8.5": 1111, "9.875": 11},
|
||||
"t1_section_drilling_day": {"12.25": 196, "17.5": 151, "26": 93, "36": 57, "6": 27, "8.5": 404, "9.875": 4},
|
||||
"t1_phase": {"conductor": 67, "intermediate": 154, "pilot": 29, "production": 261, "reservoir": 1142,
|
||||
"surface": 105},
|
||||
"t1_op_class": {"bop_wellhead": 2512, "casing_cement": 3204, "circulate": 1185, "completion": 657,
|
||||
"drill_ream": 1925, "formation_evaluation": 520, "interruption": 3577, "other": 3538,
|
||||
"perforate": 929, "plug_abandon": 1629, "rig_move": 241, "rig_up_down": 572, "trip": 1946,
|
||||
"wait": 79, "wireline": 933},
|
||||
"t2_npt_a": 3577,
|
||||
"t2_cause_a": {"equipment": 1985, "lost_circulation": 78, "operation_failed": 101, "sidetrack": 202,
|
||||
"stuck_fishing": 246, "unspecified": 262, "waiting": 229, "weather": 445, "well_control": 29},
|
||||
"t2_npt_b": 4286,
|
||||
"t2_cause_b": {"equipment": 2425, "hse": 1, "lost_circulation": 86, "operation_failed": 322, "sidetrack": 202,
|
||||
"stuck_fishing": 248, "unspecified": 299, "waiting": 229, "weather": 445, "well_control": 29},
|
||||
"t3_depth_class": {"above_mudline": 2923, "in_hole": 11408, "zero": 9116},
|
||||
"t3_cells": 8757,
|
||||
"t3_npt_in_hole_a": 1799, "t3_positive_cells_a": 844, "t3_intervals_a": 656, "t3_episodes_a": 1097,
|
||||
"t3_npt_in_hole_b": 2165, "t3_positive_cells_b": 979, "t3_intervals_b": 728, "t3_episodes_b": 1193,
|
||||
}
|
||||
|
||||
RARE = 20 # a class with fewer instances is flagged (plan, gate G1)
|
||||
COVERAGE_BY_WELLBORE = ("ffill", "bfill", "ffill_bfill", "nearest", "hole_start")
|
||||
|
||||
|
||||
def _counts(s: pd.Series) -> dict:
|
||||
return {str(k): int(v) for k, v in s.value_counts().sort_index().items()}
|
||||
|
||||
|
||||
def _records(df: pd.DataFrame) -> list[dict]:
|
||||
return json.loads(df.to_json(orient="records"))
|
||||
|
||||
|
||||
def _quantiles(s: pd.Series) -> dict:
|
||||
q = s.quantile([0, 0.25, 0.5, 0.75, 0.9, 1.0])
|
||||
return {"n": int(s.notna().sum()), **{f"q{int(k * 100)}": round(float(v), 2) for k, v in q.items()}}
|
||||
|
||||
|
||||
def t1_summary(t1r: pd.DataFrame, t1a: pd.DataFrame, feat: pd.DataFrame, ev: pd.DataFrame, cfg: dict) -> dict:
|
||||
live = t1r[t1r["status"].ne("placeholder_date")]
|
||||
drilling = live[live["scope"].eq("drilling_day")]
|
||||
missing = live[live["diaHole"].isna()]
|
||||
f = feat[feat["status"].ne("placeholder_date")]
|
||||
prev = f.groupby("wellbore")["dia"].ffill()
|
||||
nxt = f.groupby("wellbore")["dia"].bfill()
|
||||
where = np.select([prev.isna(), nxt.isna(), prev == nxt], ["leading", "trailing", "between_same_size"],
|
||||
"between_different_sizes")
|
||||
position = pd.Series(where, index=f.index)[f["dia"].isna()]
|
||||
position_drilling = position[f.loc[position.index, "n_drilling_activities"] > 0]
|
||||
known = f[f["dia"].notna()]
|
||||
named = known[known["text_dia"].notna()]
|
||||
overall = L.summarise_fill_eval(ev)
|
||||
by_wellbore = L.summarise_fill_eval(ev[ev["rule"].isin(COVERAGE_BY_WELLBORE)], by_wellbore=True)
|
||||
filled_drilling = drilling[drilling["filled_by"].isin(["ffill", "bfill_leading"])]
|
||||
return {
|
||||
"report_status": _counts(t1r["status"]),
|
||||
"hole_sizes_published": _counts(live["diaHole"].dropna()),
|
||||
"reports_without_diaHole": int(len(missing)),
|
||||
"reports_without_diaHole_with_drilling_activities": int((missing["scope"] == "drilling_day").sum()),
|
||||
"drilling_activities_on_those_reports": int(missing["n_drilling_activities"].sum()),
|
||||
"wellbores_with_those_reports": int(missing.loc[missing["scope"] == "drilling_day", "wellbore"].nunique()),
|
||||
"missing_position": {"all": _counts(position), "drilling_day": _counts(position_drilling)},
|
||||
"filled_by": {"all": _counts(live["filled_by"]), "drilling_day": _counts(drilling["filled_by"])},
|
||||
"fill_gap_days_filled_drilling_days": _quantiles(filled_drilling["fill_gap_days"]),
|
||||
"fill_gap_reports_filled_drilling_days": _quantiles(filled_drilling["fill_gap_reports"]),
|
||||
"section": {"all": _counts(live["section"]), "drilling_day": _counts(drilling["section"]),
|
||||
"published_only": _counts(live.loc[live["filled_by"].eq("diaHole"), "section"])},
|
||||
"phase": {"all": _counts(live["phase"]), "drilling_day": _counts(drilling["phase"])},
|
||||
"pilot_reports": int(live["is_pilot"].sum()),
|
||||
"scope": _counts(t1r["scope"]),
|
||||
"day_op_group": _counts(live["day_op_group"].dropna()),
|
||||
"day_op_class": _counts(live["day_op_class"].dropna()),
|
||||
"op_group": _counts(t1a["op_group"]),
|
||||
"op_class": _counts(t1a["op_class"]),
|
||||
"op_sub_values": int(t1a["op_sub"].nunique()),
|
||||
"fill_rule": cfg["t1"]["fill"],
|
||||
"fill_evaluation": {
|
||||
"note": "known diaHole masked and recovered; recovered = correct / masked, coverage = answered / masked",
|
||||
"overall": _records(overall),
|
||||
"by_wellbore": _records(by_wellbore),
|
||||
"on_reports_without_diaHole": _records(L.fill_on_missing(feat)),
|
||||
},
|
||||
"hole_size_named_in_text": {
|
||||
"note": "sum24Hr + drilling-group comments name a hole size as "
|
||||
"'<size>\" hole|section|pilot hole|open hole'",
|
||||
"reports_with_diaHole": int(len(known)), "of_which_text_names_a_size": int(len(named)),
|
||||
"text_equals_diaHole": int((named["text_dia"] == named["dia"]).sum()),
|
||||
"reports_without_diaHole_where_text_names_a_size": int(f.loc[f["dia"].isna(), "text_dia"].notna().sum()),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def t2_summary(t2: pd.DataFrame, activities: pd.DataFrame, tables: dict[str, pd.DataFrame]) -> dict:
|
||||
out: dict = {"activities": int(len(t2)), "hours": round(float(t2["duration_h"].sum()), 2)}
|
||||
out["candidates"] = {"interruption": int(t2["is_interruption"].sum()), "state_fail": int(t2["is_state_fail"].sum()),
|
||||
"detail_nonsuccess": int(t2["is_detail_nonsuccess"].sum())}
|
||||
for d in L.NPT_DEFINITIONS:
|
||||
npt = t2[t2[f"npt_{d}"]]
|
||||
hours = npt.groupby(f"cause_{d}")["duration_h"].sum().round(2)
|
||||
out[f"npt_{d}"] = {"n": int(len(npt)), "share": round(len(npt) / len(t2), 4),
|
||||
"hours": round(float(npt["duration_h"].sum()), 2),
|
||||
"hours_share": round(float(npt["duration_h"].sum() / t2["duration_h"].sum()), 4),
|
||||
"cause": _counts(npt[f"cause_{d}"]),
|
||||
"cause_hours": {str(k): float(v) for k, v in hours.items()},
|
||||
"cause_fine": _counts(npt["cause_fine"]),
|
||||
"cause_rule": _counts(npt["cause_rule"]),
|
||||
"cause_conflict": int(npt["cause_conflict"].sum())}
|
||||
only_b = t2[t2["npt_b"] & ~t2["npt_a"]]
|
||||
out["npt_b_not_a"] = {"n": int(len(only_b)), "op_group": _counts(activities.loc[only_b.index, "code_main"]),
|
||||
"cause": _counts(only_b["cause_group"])}
|
||||
conflicts = t2[t2["cause_conflict"]]
|
||||
out["cause_conflicts"] = _counts(conflicts["cause_from_code"] + " | " + conflicts["cause_from_detail"])
|
||||
wait = t2["wait_code_outside_interruption"]
|
||||
out["wait_code_outside_interruption"] = {"n": int(wait.sum()), "of_which_npt_b": int((wait & t2["npt_b"]).sum())}
|
||||
rig = activities["phase"].to_numpy()
|
||||
out["npt_rate_by_rig_phase"] = {str(p): {"n": int((rig == p).sum()),
|
||||
"npt_a": round(float(t2.loc[rig == p, "npt_a"].mean()), 4),
|
||||
"npt_b": round(float(t2.loc[rig == p, "npt_b"].mean()), 4)}
|
||||
for p in sorted(set(rig))}
|
||||
# The equip_failures table is a structured near-label that the masked view leaves out: how much would it tell?
|
||||
with_failure = set(tables["equip_failures"]["report_id"])
|
||||
by_report = t2.assign(equipment=t2["cause_b"].eq("equipment")).groupby("report_id")["equipment"].any()
|
||||
has = by_report.index.isin(with_failure)
|
||||
out["equip_failures_table"] = {
|
||||
"reports_with_rows": int(len(with_failure)),
|
||||
"reports_with_equipment_npt_b": int(by_report.sum()),
|
||||
"reports_with_both": int((by_report & has).sum()),
|
||||
"share_of_equipment_npt_reports_with_rows": round(float((by_report & has).sum() / by_report.sum()), 4),
|
||||
"share_of_reports_with_rows_that_have_equipment_npt": round(float((by_report & has).sum() / has.sum()), 4)}
|
||||
for by in ("wellbore", "well"):
|
||||
per = t2.groupby(by).agg(n=("act_id", "size"), npt_a=("npt_a", "mean"), npt_b=("npt_b", "mean"))
|
||||
out[f"npt_rate_by_{by}"] = {w: {"n": int(r.n), "npt_a": round(float(r.npt_a), 4),
|
||||
"npt_b": round(float(r.npt_b), 4)} for w, r in per.iterrows()}
|
||||
return out
|
||||
|
||||
|
||||
def t3_summary(t3a: pd.DataFrame, cells: pd.DataFrame, intervals: dict, episodes: dict, activities: pd.DataFrame,
|
||||
reports: pd.DataFrame, t1r: pd.DataFrame, cfg: dict) -> dict:
|
||||
grid = float(cfg["t3"]["grid_m"])
|
||||
out: dict = {"grid_m": grid, "merge_gap_cells": cfg["t3"]["merge_gap_cells"],
|
||||
"mudline_md": {w: round(float(v), 1) for w, v in L.mudline(reports).items()},
|
||||
"own_hole_top_md": {w: round(float(v), 1) for w, v in L.own_hole_top(reports).items()}}
|
||||
out["depth_class"] = {"all": _counts(t3a["depth_class"])}
|
||||
hours = t3a.groupby("depth_class")["duration_h"].sum().round(2)
|
||||
out["depth_class"]["all_hours"] = {str(k): float(v) for k, v in hours.items()}
|
||||
code_main = activities.set_index("act_id")["code_main"].reindex(t3a["act_id"]).to_numpy()
|
||||
table = pd.crosstab(code_main, t3a["depth_class"].to_numpy())
|
||||
out["depth_class"]["by_op_group"] = {str(g): {str(k): int(v) for k, v in row.items()}
|
||||
for g, row in table.iterrows()}
|
||||
for d in L.NPT_DEFINITIONS:
|
||||
npt = t3a[t3a[f"npt_{d}"]]
|
||||
located = npt["depth_class"].eq("in_hole")
|
||||
cause = pd.crosstab(npt["cause_group"], located)
|
||||
out["depth_class"][f"npt_{d}"] = {
|
||||
"n": _counts(npt["depth_class"]),
|
||||
"hours": {str(k): float(v) for k, v in npt.groupby("depth_class")["duration_h"].sum().round(2).items()},
|
||||
"located_share": round(float(located.mean()), 4),
|
||||
"located_hours_share": round(float(npt.loc[located, "duration_h"].sum() / npt["duration_h"].sum()), 4),
|
||||
"located_by_cause": {str(c): {"in_hole": int(row.get(True, 0)), "not_located": int(row.get(False, 0))}
|
||||
for c, row in cause.iterrows()}}
|
||||
# What the single depth value does and does not say.
|
||||
hole = t3a[t3a["depth_class"].eq("in_hole")]
|
||||
drill = hole[code_main[hole.index] == "drilling"]
|
||||
code = activities.set_index("act_id")["proprietaryCode"].reindex(hole["act_id"])
|
||||
is_drill = code.eq("drilling -- drill").to_numpy()
|
||||
d = hole[is_drill]
|
||||
back = d["md"] < d.groupby("wellbore")["md"].cummax() - grid
|
||||
report_md = t3a["report_id"].map(reports.set_index("report_id")["md"])
|
||||
deepest_report = t3a["wellbore"].map(reports.groupby("wellbore")["md"].max())
|
||||
no_drilling_day = t3a["report_id"].map(t1r.set_index("report_id")["scope"]).ne("drilling_day")
|
||||
out["md_checks"] = {
|
||||
"activities_md_missing": int(t3a["md"].isna().sum()),
|
||||
"activities_md_zero": int((t3a["md"] == 0).sum()),
|
||||
"activities_above_mudline": int(t3a["depth_class"].eq("above_mudline").sum()),
|
||||
"activities_in_hole": int(len(hole)),
|
||||
"in_hole_in_drilling_group": int(len(drill)),
|
||||
"in_hole_on_days_without_drilling_activities": int((t3a["depth_class"].eq("in_hole") & no_drilling_day).sum()),
|
||||
"drill_rows_in_hole": int(len(d)),
|
||||
"drill_rows_more_than_one_cell_above_deepest_so_far": int(back.sum()),
|
||||
"activities_deeper_than_report_md_by_more_than_one_cell": int((t3a["md"] > report_md + grid).sum()),
|
||||
"activities_on_reports_without_md": int(report_md.isna().sum()),
|
||||
"activities_deeper_than_deepest_report_md_of_wellbore": int((t3a["md"] > deepest_report + grid).sum()),
|
||||
}
|
||||
out["cells"] = {"n": int(len(cells)), "without_activity": int((cells["n_activities"] == 0).sum()),
|
||||
"in_own_hole": int(cells["in_own_hole"].sum()),
|
||||
"by_wellbore": {w: int(n) for w, n in cells.groupby("wellbore").size().items()}}
|
||||
for d in L.NPT_DEFINITIONS:
|
||||
pos = cells[cells[f"label_{d}"]]
|
||||
iv = intervals[d]
|
||||
top = iv["wellbore"].map(L.own_hole_top(reports))
|
||||
out["cells"][f"positive_{d}"] = int(len(pos))
|
||||
out["cells"][f"positive_{d}_in_own_hole"] = int(pos["in_own_hole"].sum())
|
||||
out["cells"][f"positive_{d}_by_wellbore"] = {w: int(n) for w, n in pos.groupby("wellbore").size().items()}
|
||||
out[f"intervals_{d}"] = {
|
||||
"n": int(len(iv)), "wellbores": int(iv["wellbore"].nunique()), "wells": int(iv["well"].nunique()),
|
||||
"length_m_total": float(iv["length_m"].sum()), "length_m": _quantiles(iv["length_m"]),
|
||||
"one_cell": int((iv["n_positive_cells"] == 1).sum()),
|
||||
"one_activity": int((iv["n_activities"] == 1).sum()),
|
||||
"activities": int(iv["n_activities"].sum()), "hours": round(float(iv["hours"].sum()), 2),
|
||||
"entirely_above_own_hole_top": int((iv["md_bottom"] <= top).sum()),
|
||||
"by_wellbore": {w: int(n) for w, n in iv.groupby("wellbore").size().items()},
|
||||
"by_merge_gap_cells": {str(g): int(len(L.t3_intervals(cells, t3a, d, cfg, merge_gap_cells=g)))
|
||||
for g in (0, 1, 2)}}
|
||||
ep = episodes[d]
|
||||
out[f"episodes_{d}"] = {"n": int(len(ep)), "with_in_hole_depth": int((ep["n_in_hole"] > 0).sum()),
|
||||
"hours": _quantiles(ep["hours"]), "activities": _quantiles(ep["n_activities"]),
|
||||
"spanning_reports": int((ep["n_reports"] > 1).sum())}
|
||||
return out
|
||||
|
||||
|
||||
def coverage_summary(t1r: pd.DataFrame, t1a: pd.DataFrame, t2: pd.DataFrame, cells: pd.DataFrame,
|
||||
intervals: dict, activities: pd.DataFrame, reports: pd.DataFrame) -> dict:
|
||||
live = t1r[t1r["status"].ne("placeholder_date")]
|
||||
drilling = live[live["scope"].eq("drilling_day")]
|
||||
frames = {
|
||||
"t1_section_drilling_day": (drilling, "section"), "t1_section_all_days": (live, "section"),
|
||||
"t1_phase_drilling_day": (drilling, "phase"), "t1_phase_all_days": (live, "phase"),
|
||||
"t1_op_class": (t1a, "op_class"), "t1_op_group": (t1a, "op_group"), "t1_op_sub": (t1a, "op_sub"),
|
||||
"t1_day_op_class": (live, "day_op_class"),
|
||||
}
|
||||
for d in L.NPT_DEFINITIONS:
|
||||
npt = t2[t2[f"npt_{d}"]]
|
||||
frames[f"t2_npt_{d}"] = (t2.assign(**{f"npt_{d}": t2[f"npt_{d}"].map({True: "npt", False: "not_npt"})}),
|
||||
f"npt_{d}")
|
||||
frames[f"t2_cause_{d}"] = (npt, f"cause_{d}")
|
||||
frames[f"t2_cause_fine_{d}"] = (npt, "cause_fine")
|
||||
frames[f"t3_cell_{d}"] = (cells.assign(**{f"label_{d}": cells[f"label_{d}"].map({True: "trouble",
|
||||
False: "no_trouble"})}),
|
||||
f"label_{d}")
|
||||
frames[f"t3_interval_{d}"] = (intervals[d].assign(interval="interval"), "interval")
|
||||
coverage, distributions, rare = {}, {}, []
|
||||
for name, (frame, column) in frames.items():
|
||||
cov = L.class_coverage(frame, column, rare=RARE)
|
||||
coverage[name] = _records(cov.drop(columns="label"))
|
||||
if name != "t1_op_sub":
|
||||
distributions[name] = {"by_wellbore": L.distribution(frame, column, "wellbore"),
|
||||
"by_well": L.distribution(frame, column, "well")}
|
||||
flagged = cov[cov["rare"] | cov["single_wellbore"] | cov["single_well"]]
|
||||
rare += [{"label": name, "class": r["class"], "n": int(r["n"]), "n_wellbores": int(r["n_wellbores"]),
|
||||
"n_wells": int(r["n_wells"]), "rare": bool(r["rare"])} for _, r in flagged.iterrows()]
|
||||
wells = t1r.groupby("well")["wellbore"].agg(lambda s: sorted(set(s))).to_dict()
|
||||
return {
|
||||
"note": "n_wellbores / n_wells = groups that contain the class; a class in one group cannot be in both the "
|
||||
"training and the test side of a grouped split. top_*_share = largest share held by one group.",
|
||||
"wells": wells, "n_wells": len(wells), "n_wellbores": int(t1r["wellbore"].nunique()),
|
||||
"reports_by_wellbore": {w: int(n) for w, n in t1r.groupby("wellbore").size().items()},
|
||||
"activities_by_wellbore": {w: int(n) for w, n in t1a.groupby("wellbore").size().items()},
|
||||
"activities_by_well": {w: int(n) for w, n in t1a.groupby("well").size().items()},
|
||||
"split_facts": split_facts(activities, reports, t1r, cells),
|
||||
"classes": coverage, "flagged_classes": rare, "distributions": distributions,
|
||||
}
|
||||
|
||||
|
||||
def split_facts(activities: pd.DataFrame, reports: pd.DataFrame, t1r: pd.DataFrame, cells: pd.DataFrame) -> dict:
|
||||
"""What wellbores of one well share, for the choice between a split by wellbore and a split by well:
|
||||
report days that two wellbores of a well both report, activity comments that occur verbatim in another wellbore
|
||||
of the same well (against the same in another well), and trouble cells in the hole shared with the parent."""
|
||||
live = t1r[t1r["status"].ne("placeholder_date")].merge(reports[["report_id", "sum24Hr"]], on="report_id")
|
||||
days = live.groupby(["well", "file_date"]).agg(n=("wellbore", "nunique"), texts=("sum24Hr", "nunique"))
|
||||
shared = days[days["n"] > 1]
|
||||
text = activities["comments"].fillna("").str.lower().str.replace(r"\s+", " ", regex=True).str.strip()
|
||||
g = pd.DataFrame({"text": text, "wellbore": activities["wellbore"], "well": activities["wellbore"].map(L.well_of)})
|
||||
out = {"report_days_shared_by_two_wellbores_of_a_well": int(len(shared)),
|
||||
"of_which_same_sum24Hr": int((shared["texts"] == 1).sum()),
|
||||
"wells_with_shared_days": sorted(shared.index.get_level_values(0).unique())}
|
||||
for name, sel in (("all_comments", g), ("comments_of_40_chars_or_more", g[g["text"].str.len() >= 40])):
|
||||
in_well = sel.groupby(["text", "well"])["wellbore"].nunique()
|
||||
wells = sel.groupby("text")["well"].nunique()
|
||||
twin_same_well = pd.MultiIndex.from_frame(sel[["text", "well"]]).map(in_well).to_numpy() > 1
|
||||
twin_other_well = sel["text"].map(wells).to_numpy() > 1
|
||||
multi = sel["well"].map(sel.groupby("well")["wellbore"].nunique()).to_numpy() > 1
|
||||
out[name] = {"n": int(len(sel)),
|
||||
"verbatim_in_another_wellbore_of_the_same_well": int(twin_same_well.sum()),
|
||||
"verbatim_in_another_well": int(twin_other_well.sum()),
|
||||
"n_in_wells_with_several_wellbores": int(multi.sum()),
|
||||
"share_same_well_among_those": round(float(twin_same_well[multi].mean()), 4),
|
||||
"share_other_well": round(float(twin_other_well.mean()), 4)}
|
||||
for d in L.NPT_DEFINITIONS:
|
||||
pos = cells[cells[f"label_{d}"]]
|
||||
out[f"t3_positive_cells_{d}_above_own_hole_top"] = int((~pos["in_own_hole"]).sum())
|
||||
return out
|
||||
|
||||
|
||||
def expected_counts(t1r, t1a, t2, t3a, cells, intervals, episodes) -> dict:
|
||||
live = t1r[t1r["status"].ne("placeholder_date")]
|
||||
got = {
|
||||
"report_status": _counts(t1r["status"]),
|
||||
"t1_scope": _counts(t1r["scope"]),
|
||||
"t1_filled_by": _counts(live["filled_by"]),
|
||||
"t1_section": _counts(live["section"]),
|
||||
"t1_section_drilling_day": _counts(live.loc[live["scope"].eq("drilling_day"), "section"]),
|
||||
"t1_phase": _counts(live["phase"]),
|
||||
"t1_op_class": _counts(t1a["op_class"]),
|
||||
"t3_depth_class": _counts(t3a["depth_class"]),
|
||||
"t3_cells": int(len(cells)),
|
||||
}
|
||||
for d in L.NPT_DEFINITIONS:
|
||||
got[f"t2_npt_{d}"] = int(t2[f"npt_{d}"].sum())
|
||||
got[f"t2_cause_{d}"] = _counts(t2.loc[t2[f"npt_{d}"], f"cause_{d}"])
|
||||
got[f"t3_npt_in_hole_{d}"] = int((t3a[f"npt_{d}"] & t3a["depth_class"].eq("in_hole")).sum())
|
||||
got[f"t3_positive_cells_{d}"] = int(cells[f"label_{d}"].sum())
|
||||
got[f"t3_intervals_{d}"] = int(len(intervals[d]))
|
||||
got[f"t3_episodes_{d}"] = int(len(episodes[d]))
|
||||
return got
|
||||
|
||||
|
||||
def analysis_md(summary: dict) -> str:
|
||||
"""The short analysis for the protocol author, written from summary.json (same numbers, readable form)."""
|
||||
t1, t2, t3, cov = summary["t1"], summary["t2"], summary["t3"], summary["coverage"]
|
||||
lines = ["# Volve-DIA labels T1-T3: analysis for the evaluation protocol", "",
|
||||
"Generated by scripts/07_labels.py from outputs/ddr and configs/labels.yaml "
|
||||
f"(sha256 {summary['labels_yaml']['sha256'][:12]}). Every number is in summary.json.", ""]
|
||||
lines += ["## T1 fill rule: recovery of masked diaHole", "",
|
||||
"| rule | " + " | ".join(f"{s} recovered / coverage" for s in L.MASK_SCHEMES) + " |",
|
||||
"| --- |" + " ---: |" * len(L.MASK_SCHEMES)]
|
||||
rows = {(r["rule"], r["scheme"]): r for r in t1["fill_evaluation"]["overall"]}
|
||||
for rule in L.FILL_RULES:
|
||||
cells = [f"{rows[(rule, s)]['recovered']:.4f} / {rows[(rule, s)]['coverage']:.4f}" for s in L.MASK_SCHEMES]
|
||||
lines.append(f"| {rule} | " + " | ".join(cells) + " |")
|
||||
masked = {s: rows[("ffill", s)]["n_masked"] for s in L.MASK_SCHEMES}
|
||||
lines += ["", f"Masked reports per scheme: {masked}.", "",
|
||||
"On the reports that really lack diaHole (nothing masked):", "",
|
||||
"| rule | subset | n | answered | text names a size | both | agree with text | bit record | both | "
|
||||
"agree with bit |", "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |"]
|
||||
for r in t1["fill_evaluation"]["on_reports_without_diaHole"]:
|
||||
lines.append(f"| {r['rule']} | {r['subset']} | {r['n']} | {r['n_answered']} | {r['n_text']} | {r['n_both']} | "
|
||||
f"{r['n_agree_text']} | {r['n_bit']} | {r['n_both_bit']} | {r['n_agree_bit']} |")
|
||||
lines += ["", f"Position of the reports without diaHole: {t1['missing_position']}.",
|
||||
f"Sections after filling (all days): {t1['section']['all']}; "
|
||||
f"drilling days: {t1['section']['drilling_day']}.",
|
||||
f"Filled by: {t1['filled_by']}.", ""]
|
||||
lines += ["## T2: NPT and cause groups", "", "| cause group | (a) interruption only | (b) union |",
|
||||
"| --- | ---: | ---: |"]
|
||||
causes = sorted(set(t2["npt_a"]["cause"]) | set(t2["npt_b"]["cause"]))
|
||||
for c in causes:
|
||||
lines.append(f"| {c} | {t2['npt_a']['cause'].get(c, 0)} | {t2['npt_b']['cause'].get(c, 0)} |")
|
||||
lines += [f"| **total** | {t2['npt_a']['n']} | {t2['npt_b']['n']} |", "",
|
||||
f"NPT hours: (a) {t2['npt_a']['hours']} h ({t2['npt_a']['hours_share']:.2%} of the reported hours), "
|
||||
f"(b) {t2['npt_b']['hours']} h ({t2['npt_b']['hours_share']:.2%}).", ""]
|
||||
lines += ["## T3: trouble intervals and what activities.md allows", "",
|
||||
f"Depth class of all activities: {t3['depth_class']['all']}.",
|
||||
f"NPT rows located in the hole: (a) {t3['depth_class']['npt_a']['located_share']:.2%} of rows, "
|
||||
f"{t3['depth_class']['npt_a']['located_hours_share']:.2%} of hours; "
|
||||
f"(b) {t3['depth_class']['npt_b']['located_share']:.2%} of rows, "
|
||||
f"{t3['depth_class']['npt_b']['located_hours_share']:.2%} of hours.",
|
||||
f"Cells: {t3['cells']['n']} ({t3['cells']['without_activity']} without any activity); positive "
|
||||
f"(a) {t3['cells']['positive_a']}, (b) {t3['cells']['positive_b']}.",
|
||||
f"Intervals: (a) {t3['intervals_a']['n']} in {t3['intervals_a']['wellbores']} wellbores, "
|
||||
f"(b) {t3['intervals_b']['n']} in {t3['intervals_b']['wellbores']} wellbores; by merge gap "
|
||||
f"(a) {t3['intervals_a']['by_merge_gap_cells']}, (b) {t3['intervals_b']['by_merge_gap_cells']}.",
|
||||
f"Checks: {t3['md_checks']}.", ""]
|
||||
lines += ["## Classes that a grouped split cannot evaluate, or that are rare", "",
|
||||
"| label | class | n | wellbores | wells | fewer than 20 |", "| --- | --- | ---: | ---: | ---: | --- |"]
|
||||
for r in cov["flagged_classes"]:
|
||||
if r["label"] != "t1_op_sub":
|
||||
lines.append(f"| {r['label']} | {r['class']} | {r['n']} | {r['n_wellbores']} | {r['n_wells']} | "
|
||||
f"{'yes' if r['rare'] else ''} |")
|
||||
lines += ["", f"What wellbores of one well share: {cov['split_facts']}."]
|
||||
lines += ["", "## Number of wellbores and wells per class (T2 cause, T1 section and operation)", "",
|
||||
"| label | class | n | wellbores (of 26) | wells (of 11) | top wellbore (share) | top well (share) |",
|
||||
"| --- | --- | ---: | ---: | ---: | --- | --- |"]
|
||||
for name in ("t2_cause_a", "t2_cause_b", "t1_section_drilling_day", "t1_phase_drilling_day", "t1_op_class"):
|
||||
for r in cov["classes"][name]:
|
||||
lines.append(f"| {name} | {r['class']} | {r['n']} | {r['n_wellbores']} | {r['n_wells']} | "
|
||||
f"{r['top_wellbore']} ({r['top_wellbore_share']:.2f}) | {r['top_well']} "
|
||||
f"({r['top_well_share']:.2f}) |")
|
||||
lines += ["", "## Free text naming the label (comment only)", "",
|
||||
"| target | definition | positives | recall | false-positive rate | precision |",
|
||||
"| --- | --- | ---: | ---: | ---: | ---: |"]
|
||||
for r in summary["text"]["lexicon"]:
|
||||
if r["scope"] == "comment":
|
||||
lines.append(f"| {r['target']} | {r['definition']} | {r['n_pos']} | {r['recall']} | {r['fpr']} | "
|
||||
f"{r['precision']} |")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ddr = paths.outputs_dir() / "ddr"
|
||||
out = paths.outputs_dir() / "labels"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
names = ("reports", "activities", "bits", "casings", "equip_failures")
|
||||
missing = [n for n in names if not (ddr / f"{n}.parquet").is_file()]
|
||||
if missing:
|
||||
print(f"missing {ddr}/{{{','.join(missing)}}}.parquet: run scripts/02_parse_ddr.py first")
|
||||
return 1
|
||||
src = {n: pd.read_parquet(ddr / f"{n}.parquet") for n in names}
|
||||
reports, activities = src["reports"], src["activities"]
|
||||
config_path = paths.REPO_ROOT / "configs" / "labels.yaml"
|
||||
cfg = L.load_config(config_path)
|
||||
diff = L.check_code_counts(activities, cfg)
|
||||
if diff:
|
||||
print("configs/labels.yaml differs from the data (written, found):", diff)
|
||||
return 1
|
||||
|
||||
tl = L.timeline(reports, activities, cfg)
|
||||
feat = L.fill_features(tl, activities, src["bits"], src["casings"], cfg)
|
||||
ev = L.evaluate_fill_rules(feat)
|
||||
ops = L.operation_classes(activities, cfg)
|
||||
t1r = L.attach_witsml_section(L.t1_reports(feat, ops, activities, cfg), None)
|
||||
t1a = L.t1_activities(ops, t1r)
|
||||
t2 = L.t2_labels(activities, cfg)
|
||||
t2in = L.t2_inputs(activities, reports, cfg)
|
||||
lexicon = L.text_rates(activities, reports, t2, cfg)
|
||||
literal = L.code_sub_literal(activities)
|
||||
t3a = L.t3_activities(activities, t2, reports, cfg)
|
||||
episodes = {d: L.t3_episodes(t3a, d) for d in L.NPT_DEFINITIONS}
|
||||
cells = L.t3_cells(t3a, reports, cfg)
|
||||
intervals = {d: L.t3_intervals(cells, t3a, d, cfg) for d in L.NPT_DEFINITIONS}
|
||||
cells = L.attach_intervals(cells, intervals)
|
||||
code_map = pd.DataFrame([{"proprietaryCode": c, "n": r["n"], "op_group": c.split(" -- ")[0],
|
||||
"op_sub": c.split(" -- ")[1], "op_class": r["op_class"], "cause": r["cause"]}
|
||||
for c, r in cfg["codes"].items()])
|
||||
|
||||
tables = {
|
||||
"code_map": code_map, "t1_reports": t1r, "t1_activities": t1a, "t2_labels": t2, "t2_inputs": t2in,
|
||||
"t3_activities": t3a, "t3_episodes": pd.concat(episodes.values(), ignore_index=True), "t3_cells": cells,
|
||||
"t3_intervals": pd.concat(intervals.values(), ignore_index=True), "fill_eval": ev,
|
||||
"text_lexicon_rates": lexicon, "text_code_sub_literal": literal,
|
||||
}
|
||||
for name, df in tables.items():
|
||||
df.to_parquet(out / f"{name}.parquet", index=False)
|
||||
db, tmp = out / "volve_labels.duckdb", out / "volve_labels.duckdb.tmp"
|
||||
tmp.unlink(missing_ok=True)
|
||||
with duckdb.connect(str(tmp)) as con:
|
||||
for name in tables:
|
||||
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
|
||||
os.replace(tmp, db)
|
||||
|
||||
got = expected_counts(t1r, t1a, t2, t3a, cells, intervals, episodes)
|
||||
summary = {
|
||||
"labels_yaml": {"version": cfg["version"], "sha256": hashlib.sha256(config_path.read_bytes()).hexdigest()},
|
||||
"counts": got,
|
||||
"tables": {name: {"rows": len(df), "columns": df.shape[1]} for name, df in tables.items()},
|
||||
"decisions": {
|
||||
"placeholder_report": t1r.loc[t1r["status"].eq("placeholder_date"), "report_id"].tolist(),
|
||||
"reports_without_activities": t1r.loc[t1r["status"].eq("no_activities"), "report_id"].tolist(),
|
||||
"note": "placeholder: no section, no row in T2/T3, outside the timeline; no_activities: section label "
|
||||
"kept (T1 report-day), no operation label, no row in T2/T3",
|
||||
},
|
||||
"t1": t1_summary(t1r, t1a, feat, ev, cfg),
|
||||
"t2": t2_summary(t2, activities, src),
|
||||
"t3": t3_summary(t3a, cells, intervals, episodes, activities, reports, t1r, cfg),
|
||||
"text": {"note": "analysis only: how often the free text names the label; never a label source",
|
||||
"lexicon": _records(lexicon), "code_sub_literal": _records(literal)},
|
||||
"coverage": coverage_summary(t1r, t1a, t2, cells, intervals, activities, reports),
|
||||
}
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
(out / "analysis.md").write_text(analysis_md(summary), encoding="utf-8")
|
||||
print(json.dumps({"counts": got, "tables": summary["tables"]}, indent=1, ensure_ascii=False))
|
||||
diff = {k: (EXPECTED.get(k), got.get(k)) for k in sorted(set(EXPECTED) | set(got)) if EXPECTED.get(k) != got.get(k)}
|
||||
if diff:
|
||||
print("counts differ from EXPECTED (expected, got):", diff)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
136
scripts/08_t4_questions.py
Normal file
136
scripts/08_t4_questions.py
Normal file
@@ -0,0 +1,136 @@
|
||||
"""Build the T4 questions (evidence-grounded question answering) from the DDR tables: outputs/t4/.
|
||||
|
||||
python scripts/08_t4_questions.py
|
||||
|
||||
Reads `configs/t4_templates.yaml` and `outputs/ddr/` (scripts/02_parse_ddr.py). Writes
|
||||
|
||||
questions.jsonl, questions.parquet one question per row: id, template, family, wellbore(s) and well(s), text,
|
||||
gold answer with unit and tolerance, answer SQL, evidence rows, caveats
|
||||
dropped.jsonl every candidate instance that was dropped, with its reason
|
||||
summary.json counts per template, family and wellbore; drops by reason; the agreement of
|
||||
the SQL answers with the pandas implementation; the self-score check
|
||||
|
||||
Three checks, each of which fails the run:
|
||||
* the SQL answers and evidence rows must agree with the independent pandas implementation
|
||||
(`volve_dia/t4_pandas.py`) on every candidate instance;
|
||||
* every gold answer, scored against itself by `t4.score` with its own evidence rows as citations, must be correct
|
||||
with citation precision and recall of 1;
|
||||
* the counts must equal EXPECTED, so a change of a template, of the parser or of the data that adds or loses
|
||||
questions is caught.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
from volve_dia import paths, t4, t4_pandas
|
||||
|
||||
CONFIG = paths.REPO_ROOT / "configs" / "t4_templates.yaml"
|
||||
|
||||
EXPECTED = {
|
||||
"templates": 39,
|
||||
"candidates": 3915,
|
||||
"questions": 1662,
|
||||
"answerable": 1638,
|
||||
"unanswerable": 24,
|
||||
"dropped": {"ambiguous_multiple_values": 311, "implausible_value": 4, "inconsistent_source": 18,
|
||||
"null_answer": 28, "tie": 10},
|
||||
"not_sampled": {"answerable": 1763, "unanswerable": 119},
|
||||
"per_family": {"aggregation": 513, "comparison": 102, "lookup": 825, "multi_hop": 88, "temporal_event": 134},
|
||||
"per_template_questions": {
|
||||
"L01_spud_date": 26, "L02_drill_complete_date": 26, "L03_deepest_md": 26, "L04_deepest_md_date": 26,
|
||||
"L05_casing_bottom_md": 66, "L06_casing_sizes": 21, "L07_hole_sizes": 26, "L08_hole_section_start_md": 58,
|
||||
"L09_hole_section_max_md": 72, "L10_max_inclination": 26, "L11_max_inclination_md": 24,
|
||||
"L12_mud_density_on_date": 146, "L13_mud_density_at_depth": 102, "L14_formation_top_md": 147,
|
||||
"L15_rig_name": 25, "L16_kickoff_md": 8, "A01_reports_per_hole_size": 72, "A02_metres_drilled": 26,
|
||||
"A03_metres_drilled_section": 71, "A04_rop_section": 61, "A05_bit_run_rop_max": 62,
|
||||
"A06_hours_per_code": 151, "A07_equip_failure_count": 21, "A08_top_interruption_code": 26,
|
||||
"A09_wow_days": 23, "E01_first_event_date": 29, "E02_first_event_md": 20,
|
||||
"E03_activity_before_first_event": 20, "E04_first_episode_hours": 26, "E05_max_wow_day": 15,
|
||||
"E06_code_present": 24, "C01_more_hours_pair": 66, "C02_faster_rop_pair": 26, "C03_field_most_hours": 10,
|
||||
"M01_mud_density_at_first_event": 15, "M02_hole_size_at_first_event": 15, "M03_formation_at_first_event": 13,
|
||||
"M04_last_casing_at_first_event": 19, "M05_days_spud_to_deepest_md": 26,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def self_score(questions: list[dict]) -> dict:
|
||||
"""Each gold answer as a prediction (the answer text with its unit, and every evidence row as a citation)."""
|
||||
wrong = []
|
||||
for q in questions:
|
||||
cites = [t4.evidence_id(e["table"], e["report_id"], e["seq"]) for e in q["evidence"]]
|
||||
s = t4.score({"answer": q["answer_text"], "citations": cites}, q)
|
||||
ok = s["correct"] and not s["fabricated"]
|
||||
if q["evidence"]:
|
||||
ok = ok and s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0
|
||||
if not ok:
|
||||
wrong.append(q["id"])
|
||||
return {"questions": len(questions), "correct": len(questions) - len(wrong), "wrong": wrong[:20]}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
t_start = time.time()
|
||||
ddr, out = paths.outputs_dir() / "ddr", paths.outputs_dir() / "t4"
|
||||
cfg = t4.load_config(CONFIG)
|
||||
with t4.connect(ddr / "volve_ddr.duckdb") as con:
|
||||
questions, outcomes, summary = t4.build(con, cfg)
|
||||
t_build = time.time()
|
||||
check = t4_pandas.crosscheck(cfg, outcomes, t4_pandas.Tables(ddr))
|
||||
t_check = time.time()
|
||||
scored = self_score(questions)
|
||||
|
||||
t4.write(questions, out)
|
||||
dropped = [{"template_id": o.template_id, "slots": o.slots, "reason": o.reason}
|
||||
for outs in outcomes.values() for o in outs if o.status == "drop"]
|
||||
with (out / "dropped.jsonl").open("w", encoding="utf-8") as f:
|
||||
for d in dropped:
|
||||
f.write(json.dumps(d, ensure_ascii=False) + "\n")
|
||||
|
||||
summary = {
|
||||
"config": {"path": str(CONFIG.relative_to(paths.REPO_ROOT)), "version": cfg.get("version"),
|
||||
"seed": cfg.get("seed"), "sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(),
|
||||
"planned_templates": [t["id"] for t in cfg["disabled"]]},
|
||||
**summary,
|
||||
"crosscheck_pandas": check,
|
||||
"self_score": scored,
|
||||
"seconds": {"build_sql": round(t_build - t_start, 1), "crosscheck_pandas": round(t_check - t_build, 1)},
|
||||
}
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
|
||||
brief = {k: summary[k] for k in ("questions", "answerable", "unanswerable", "templates", "candidates", "dropped",
|
||||
"not_sampled", "per_family", "per_answer_type", "per_scope", "evidence_rows",
|
||||
"self_score", "seconds")}
|
||||
brief["crosscheck_pandas"] = check["total"]
|
||||
print(json.dumps(brief, indent=1, ensure_ascii=False))
|
||||
print(f"{'template':34s} {'cand':>5s} {'drop':>5s} {'unsampled':>9s} {'quest':>5s} {'neg':>4s} pandas")
|
||||
for tid, t in summary["per_template"].items():
|
||||
c = check["per_template"][tid]
|
||||
print(f"{tid:34s} {t['candidates']:5d} {sum(t['dropped'].values()):5d} "
|
||||
f"{sum(t['not_sampled'].values()):9d} {t['questions']:5d} {t['unanswerable']:4d} "
|
||||
f"{c['agree']}/{c['instances']}")
|
||||
|
||||
failed = False
|
||||
total = check["total"]
|
||||
if total["agree"] != total["instances"] or total["slot_differences"]:
|
||||
failed = True
|
||||
print("SQL and pandas disagree:")
|
||||
for tid, c in check["per_template"].items():
|
||||
if c["agree"] != c["instances"] or c["slots_only_sql"] or c["slots_only_pandas"]:
|
||||
print(" ", tid, json.dumps({k: v for k, v in c.items()}, ensure_ascii=False, default=str))
|
||||
if scored["correct"] != scored["questions"]:
|
||||
failed = True
|
||||
print("gold answers that do not score as correct against themselves:", scored["wrong"])
|
||||
got = {k: summary[k] for k in EXPECTED if k != "per_template_questions"}
|
||||
got["per_template_questions"] = {tid: t["questions"] for tid, t in summary["per_template"].items()}
|
||||
diff = {k: (EXPECTED[k], got[k]) for k in EXPECTED if EXPECTED[k] != got[k]}
|
||||
if diff:
|
||||
failed = True
|
||||
print("counts differ from EXPECTED (expected, got):", diff)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
351
scripts/08_t4_xml_check.py
Normal file
351
scripts/08_t4_xml_check.py
Normal file
@@ -0,0 +1,351 @@
|
||||
"""Third path for the T4 questions: recompute every answer and its evidence ids straight from the raw DDR XML files.
|
||||
|
||||
python scripts/08_t4_xml_check.py # after scripts/08_t4_questions.py; writes outputs/t4/xml_check.json
|
||||
|
||||
Uses xml.etree only: no volve_dia parser, no DuckDB, no parquet, so it also checks the DDR parser (scripts/02), which
|
||||
the SQL and pandas paths of 08_t4_questions.py share. Exit 1 if any answer or evidence set differs.
|
||||
"""
|
||||
import datetime as dt
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import defaultdict
|
||||
|
||||
from volve_dia import paths
|
||||
|
||||
XML_DIR = str(paths.ddr_xml_dir())
|
||||
NS = "{http://www.witsml.org/schemas/1series}"
|
||||
SENT = {-999.99, -999.25, -9999.0}
|
||||
TAGS = {"activity": "activities", "fluid": "fluids", "stratInfo": "strat", "casing_liner_tubing": "casings",
|
||||
"surveyStation": "surveys", "bitRecord": "bits", "equipFailureInfo": "equip_failures"}
|
||||
|
||||
|
||||
def num(e, tag):
|
||||
x = e.find(NS + tag) if e is not None else None
|
||||
if x is None or not (x.text or "").strip():
|
||||
return None
|
||||
v = float(x.text)
|
||||
return None if v in SENT else v
|
||||
|
||||
|
||||
def txt(e, tag):
|
||||
x = e.find(NS + tag) if e is not None else None
|
||||
return x.text.strip() if x is not None and x.text else None
|
||||
|
||||
|
||||
def ts(s):
|
||||
return dt.datetime.fromisoformat(s)
|
||||
|
||||
|
||||
_CACHE = {}
|
||||
|
||||
|
||||
def load(stem):
|
||||
"""All reports of the wellbore whose files are <stem>_YYYY_MM_DD.xml, in date order."""
|
||||
if stem in _CACHE:
|
||||
return _CACHE[stem]
|
||||
out = _CACHE.setdefault(stem, [])
|
||||
for p in sorted(glob.glob(os.path.join(XML_DIR, stem + "_*.xml"))):
|
||||
rid = os.path.basename(p)[:-4]
|
||||
if not re.fullmatch(re.escape(stem) + r"_\d{4}_\d{2}_\d{2}", rid):
|
||||
continue # 15_9_F_1 must not pick up 15_9_F_1_A
|
||||
rep = ET.parse(p).getroot().find(NS + "drillReport")
|
||||
wi, si = rep.find(NS + "wellboreInfo"), rep.find(NS + "statusInfo")
|
||||
r = {"rid": rid, "date": rid[-10:].replace("_", "-"), "spud": txt(wi, "dTimSpud"),
|
||||
"done": txt(wi, "dateDrillComplete"), "md": num(si, "md"), "diaHole": num(si, "diaHole"),
|
||||
"distDrill": num(si, "distDrill"), "mdCsgLast": num(si, "mdCsgLast"),
|
||||
"mdKickoff": num(si, "mdKickoff"), "mdDiaHoleStart": num(si, "mdDiaHoleStart"),
|
||||
"rig": next((txt(x, "name") for x in wi.findall(NS + "rigAlias")
|
||||
if txt(x, "namingSystem") == "NPD Name"), None) if wi is not None else None}
|
||||
for tag, name in TAGS.items():
|
||||
r[name] = rep.findall(NS + tag)
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def unstem(st):
|
||||
m = re.fullmatch(r"(\d+)_(\d+)_(?:(F)_)?(\d+)(?:_([A-Z]+\d*))?", st)
|
||||
a, b, f, n, suffix = m.groups()
|
||||
return f"{a}/{b}-{'F-' if f else ''}{n}" + (f" {suffix}" if suffix else "")
|
||||
|
||||
|
||||
def stem(wb):
|
||||
return re.sub(r"[/\- ]", "_", wb)
|
||||
|
||||
|
||||
def acts(reports):
|
||||
"""(report_id, seq, element) of every activity, in start-time order."""
|
||||
rows = [(r["rid"], i, a) for r in reports for i, a in enumerate(r["activities"])]
|
||||
return sorted(rows, key=lambda x: ts(txt(x[2], "dTimStart")))
|
||||
|
||||
|
||||
def dur(a):
|
||||
return (ts(txt(a, "dTimEnd")) - ts(txt(a, "dTimStart"))).total_seconds() / 3600
|
||||
|
||||
|
||||
def aid(rid, i):
|
||||
return f"activities:{rid}:{i}"
|
||||
|
||||
|
||||
def code_rows(reports, code):
|
||||
return [(rid, i, a) for rid, i, a in acts(reports) if txt(a, "proprietaryCode") == code]
|
||||
|
||||
|
||||
def first_event(reports, detail):
|
||||
rows = [x for x in acts(reports) if txt(x[2], "stateDetailActivity") == detail]
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
def check(q):
|
||||
s, tid = q["slots"], q["template_id"]
|
||||
R = load(stem(s["wellbore"])) if "wellbore" in s else None
|
||||
by = {r["rid"]: r for r in R} if R else {}
|
||||
if tid == "A01_reports_per_hole_size":
|
||||
rows = [r for r in R if r["diaHole"] == s["hole"]]
|
||||
return len(rows), {f"reports:{r['rid']}" for r in rows}
|
||||
if tid == "A02_metres_drilled":
|
||||
rows = [r for r in R if (r["distDrill"] or 0) > 0]
|
||||
return sum(r["distDrill"] for r in rows), {f"reports:{r['rid']}" for r in rows}
|
||||
if tid == "A04_rop_section":
|
||||
rows = [r for r in R if r["diaHole"] == s["hole"] and (r["distDrill"] or 0) > 0]
|
||||
ev, hours = {f"reports:{r['rid']}" for r in rows}, 0.0
|
||||
for r in rows:
|
||||
d = [(i, a) for i, a in enumerate(r["activities"]) if txt(a, "proprietaryCode") == "drilling -- drill"]
|
||||
assert d, "report with metres but no drill hours"
|
||||
hours += sum(dur(a) for _, a in d)
|
||||
ev |= {aid(r["rid"], i) for i, _ in d}
|
||||
return round(sum(r["distDrill"] for r in rows) / hours, 2), ev
|
||||
if tid == "C01_more_hours_pair":
|
||||
tot, ev = {}, set()
|
||||
for w in (s["wellbore_a"], s["wellbore_b"]):
|
||||
rows = code_rows(load(stem(w)), s["code"])
|
||||
tot[w] = sum(dur(a) for _, _, a in rows)
|
||||
ev |= {aid(rid, i) for rid, i, _ in rows}
|
||||
return max(tot, key=tot.get), ev
|
||||
if tid == "C03_field_most_hours":
|
||||
stems = sorted({re.sub(r"_\d{4}_\d{2}_\d{2}\.xml$", "", os.path.basename(p))
|
||||
for p in glob.glob(os.path.join(XML_DIR, "*.xml"))})
|
||||
tot, evs = {}, {}
|
||||
for st in stems:
|
||||
rows = code_rows(load(st), s["code"])
|
||||
tot[st] = sum(dur(a) for _, _, a in rows)
|
||||
evs[st] = {aid(rid, i) for rid, i, _ in rows}
|
||||
best = max(tot, key=tot.get)
|
||||
return unstem(best), evs[best]
|
||||
if tid in ("E01_first_event_date", "E02_first_event_md"):
|
||||
rid, i, a = first_event(R, s["detail"])
|
||||
val = txt(a, "dTimStart")[:10] if tid.startswith("E01") else num(a, "md")
|
||||
return val, {aid(rid, i)}
|
||||
if tid == "E03_activity_before_first_event":
|
||||
A = acts(R)
|
||||
k = next(j for j, x in enumerate(A) if txt(x[2], "stateDetailActivity") == s["detail"])
|
||||
assert txt(A[k - 1][2], "dTimEnd") and ts(txt(A[k - 1][2], "dTimEnd")) == ts(txt(A[k][2], "dTimStart"))
|
||||
return txt(A[k - 1][2], "proprietaryCode"), {aid(A[k][0], A[k][1]), aid(A[k - 1][0], A[k - 1][1])}
|
||||
if tid == "E04_first_episode_hours":
|
||||
A = acts(R)
|
||||
k = next(j for j, x in enumerate(A) if txt(x[2], "stateDetailActivity") == s["detail"])
|
||||
e = k
|
||||
while e < len(A) and txt(A[e][2], "stateDetailActivity") == s["detail"]:
|
||||
e += 1
|
||||
return sum(dur(x[2]) for x in A[k:e]), {aid(x[0], x[1]) for x in A[k:e]}
|
||||
if tid == "E05_max_wow_day":
|
||||
per = defaultdict(float)
|
||||
rows = code_rows(R, "interruption -- waiting on weather")
|
||||
for rid, i, a in rows:
|
||||
per[rid] += dur(a)
|
||||
best = max(per, key=per.get)
|
||||
assert sum(v == per[best] for v in per.values()) == 1
|
||||
return by[best]["date"], {aid(rid, i) for rid, i, _ in rows if rid == best}
|
||||
if tid == "L02_drill_complete_date":
|
||||
vals = {r["done"] for r in R if r["done"]}
|
||||
return (vals.pop() if vals else "not reported"), {f"reports:{r['rid']}" for r in R if r["done"]}
|
||||
if tid == "L04_deepest_md_date":
|
||||
mx = max(r["md"] for r in R if r["md"] is not None)
|
||||
first = next(r for r in R if r["md"] == mx)
|
||||
return first["date"], {f"reports:{first['rid']}"}
|
||||
if tid == "L06_casing_sizes":
|
||||
rows = [(r["rid"], i, num(c, "od")) for r in R for i, c in enumerate(r["casings"])]
|
||||
return sorted({od for _, _, od in rows}, reverse=True), {f"casings:{rid}:{i}" for rid, i, _ in rows}
|
||||
if tid == "L07_hole_sizes":
|
||||
rows = [r for r in R if r["diaHole"] is not None]
|
||||
return sorted({r["diaHole"] for r in rows}, reverse=True), {f"reports:{r['rid']}" for r in rows}
|
||||
if tid == "L13_mud_density_at_depth":
|
||||
rows = [(r["rid"], i, num(f, "density")) for r in R for i, f in enumerate(r["fluids"])
|
||||
if num(f, "md") == s["md"] and num(f, "density") is not None]
|
||||
assert len({d for _, _, d in rows}) == 1
|
||||
return rows[0][2], {f"fluids:{rid}:{i}" for rid, i, _ in rows}
|
||||
if tid.startswith("M0") and tid != "M05_days_spud_to_deepest_md":
|
||||
rid, i, a = first_event(R, s["detail"])
|
||||
rep = by[rid]
|
||||
if tid == "M01_mud_density_at_first_event":
|
||||
rows = [(j, num(f, "density")) for j, f in enumerate(rep["fluids"]) if num(f, "density") is not None]
|
||||
assert len({d for _, d in rows}) == 1
|
||||
return rows[0][1], {aid(rid, i)} | {f"fluids:{rid}:{j}" for j, _ in rows}
|
||||
if tid == "M02_hole_size_at_first_event":
|
||||
return rep["diaHole"], {aid(rid, i), f"reports:{rid}"}
|
||||
if tid == "M04_last_casing_at_first_event":
|
||||
return rep["mdCsgLast"], {aid(rid, i), f"reports:{rid}"}
|
||||
if tid == "M03_formation_at_first_event":
|
||||
tops = [(r["rid"], j, num(x, "mdTop"), txt(x, "description").rstrip(" .")) for r in R
|
||||
for j, x in enumerate(r["strat"])]
|
||||
above = [x for x in tops if x[2] <= num(a, "md")]
|
||||
mx = max(x[2] for x in above)
|
||||
best = [x for x in above if x[2] == mx]
|
||||
return best[0][3], {aid(rid, i)} | {f"strat:{x[0]}:{x[1]}" for x in best}
|
||||
if tid == "M05_days_spud_to_deepest_md":
|
||||
spud = {r["spud"][:10] for r in R if r["spud"]}
|
||||
assert len(spud) == 1
|
||||
mx = max(r["md"] for r in R if r["md"] is not None)
|
||||
first = next(r for r in R if r["md"] == mx)
|
||||
days = (dt.date.fromisoformat(first["date"]) - dt.date.fromisoformat(spud.pop())).days
|
||||
return days, {f"reports:{first['rid']}"} | {f"reports:{r['rid']}" for r in R if r["spud"]}
|
||||
raise NotImplementedError(tid)
|
||||
|
||||
|
||||
def rop(R, hole):
|
||||
rows = [r for r in R if r["diaHole"] == hole and (r["distDrill"] or 0) > 0]
|
||||
ev, hours = {f"reports:{r['rid']}" for r in rows}, 0.0
|
||||
for r in rows:
|
||||
d = [(i, a) for i, a in enumerate(r["activities"]) if txt(a, "proprietaryCode") == "drilling -- drill"]
|
||||
assert d, "report with metres but no drill hours"
|
||||
hours += sum(dur(a) for _, a in d)
|
||||
ev |= {aid(r["rid"], i) for i, _ in d}
|
||||
return sum(r["distDrill"] for r in rows) / hours, ev
|
||||
|
||||
|
||||
def one(values):
|
||||
values = set(values)
|
||||
assert len(values) == 1, values
|
||||
return values.pop()
|
||||
|
||||
|
||||
def check2(q):
|
||||
s, tid = q["slots"], q["template_id"]
|
||||
R = load(stem(s["wellbore"])) if "wellbore" in s else None
|
||||
rep = lambda rows: {f"reports:{r['rid']}" for r in rows}
|
||||
if tid == "L01_spud_date":
|
||||
rows = [r for r in R if r["spud"]]
|
||||
return one(r["spud"][:10] for r in rows), rep(rows)
|
||||
if tid == "L03_deepest_md":
|
||||
mx = max(r["md"] for r in R if r["md"] is not None)
|
||||
return mx, rep(r for r in R if r["md"] == mx)
|
||||
if tid == "L05_casing_bottom_md":
|
||||
rows = [(r["rid"], i, num(c, "mdBottom")) for r in R for i, c in enumerate(r["casings"])
|
||||
if num(c, "od") == s["od"]]
|
||||
mx = max(x[2] for x in rows)
|
||||
return mx, {f"casings:{rid}:{i}" for rid, i, v in rows if v == mx}
|
||||
if tid == "L08_hole_section_start_md":
|
||||
rows = [r for r in R if r["diaHole"] == s["hole"] and r["mdDiaHoleStart"] is not None]
|
||||
return one(r["mdDiaHoleStart"] for r in rows), rep(rows)
|
||||
if tid == "L09_hole_section_max_md":
|
||||
rows = [r for r in R if r["diaHole"] == s["hole"] and r["md"] is not None]
|
||||
mx = max(r["md"] for r in rows)
|
||||
return mx, rep(r for r in rows if r["md"] == mx)
|
||||
if tid in ("L10_max_inclination", "L11_max_inclination_md"):
|
||||
rows = [(r["rid"], i, num(x, "incl"), num(x, "md")) for r in R for i, x in enumerate(r["surveys"])
|
||||
if num(x, "incl") is not None]
|
||||
mx = max(x[2] for x in rows)
|
||||
top = [x for x in rows if x[2] == mx]
|
||||
ev = {f"surveys:{rid}:{i}" for rid, i, _, _ in top}
|
||||
return (mx if tid.startswith("L10") else one(x[3] for x in top)), ev
|
||||
if tid == "L12_mud_density_on_date":
|
||||
r = next(r for r in R if r["date"] == s["date"])
|
||||
rows = [(i, num(f, "density")) for i, f in enumerate(r["fluids"]) if num(f, "density") is not None]
|
||||
return one(d for _, d in rows), {f"fluids:{r['rid']}:{i}" for i, _ in rows}
|
||||
if tid == "L14_formation_top_md":
|
||||
rows = [(r["rid"], i, num(x, "mdTop")) for r in R for i, x in enumerate(r["strat"])
|
||||
if txt(x, "description").rstrip(" .") == s["formation"]]
|
||||
return one(v for _, _, v in rows), {f"strat:{rid}:{i}" for rid, i, _ in rows}
|
||||
if tid == "L15_rig_name":
|
||||
rows = [r for r in R if r["rig"]]
|
||||
return one(r["rig"] for r in rows), rep(rows)
|
||||
if tid == "L16_kickoff_md":
|
||||
rows = [r for r in R if r["mdKickoff"] is not None]
|
||||
return (one(r["mdKickoff"] for r in rows) if rows else "not reported"), rep(rows)
|
||||
if tid == "A03_metres_drilled_section":
|
||||
rows = [r for r in R if r["diaHole"] == s["hole"] and (r["distDrill"] or 0) > 0]
|
||||
return sum(r["distDrill"] for r in rows), rep(rows)
|
||||
if tid == "A05_bit_run_rop_max":
|
||||
rows = [(r["rid"], i, num(b.find(NS + "bitRun"), "ropAv")) for r in R for i, b in enumerate(r["bits"])
|
||||
if num(b, "diaBit") == s["bit"]]
|
||||
rows = [x for x in rows if x[2] is not None]
|
||||
mx = max(x[2] for x in rows)
|
||||
return mx, {f"bits:{rid}:{i}" for rid, i, v in rows if v == mx}
|
||||
if tid == "A06_hours_per_code":
|
||||
rows = code_rows(R, s["code"])
|
||||
return sum(dur(a) for _, _, a in rows), {aid(rid, i) for rid, i, _ in rows}
|
||||
if tid == "A07_equip_failure_count":
|
||||
rows = [(r["rid"], i) for r in R for i, _ in enumerate(r["equip_failures"])]
|
||||
return len(rows), {f"equip_failures:{rid}:{i}" for rid, i in rows}
|
||||
if tid == "A08_top_interruption_code":
|
||||
tot, evs = defaultdict(float), defaultdict(set)
|
||||
for rid, i, a in acts(R):
|
||||
c = txt(a, "proprietaryCode")
|
||||
if c.startswith("interruption -- "):
|
||||
tot[c] += dur(a)
|
||||
evs[c].add(aid(rid, i))
|
||||
best = max(tot, key=tot.get)
|
||||
assert sum(abs(v - tot[best]) < 1e-6 for v in tot.values()) == 1
|
||||
return best, evs[best]
|
||||
if tid == "A09_wow_days":
|
||||
rows = code_rows(R, "interruption -- waiting on weather")
|
||||
return len({rid for rid, _, _ in rows}), {aid(rid, i) for rid, i, _ in rows}
|
||||
if tid == "E06_code_present":
|
||||
rows = code_rows(R, s["code"])
|
||||
return bool(rows), {aid(rid, i) for rid, i, _ in rows}
|
||||
if tid == "C02_faster_rop_pair":
|
||||
(ra, ea), (rb, eb) = rop(load(stem(s["wellbore_a"])), s["hole"]), rop(load(stem(s["wellbore_b"])), s["hole"])
|
||||
assert abs(ra - rb) > 0.02 * max(ra, rb)
|
||||
return (s["wellbore_a"] if ra > rb else s["wellbore_b"]), ea | eb
|
||||
return check(q)
|
||||
|
||||
|
||||
def same(gold, got):
|
||||
if isinstance(gold, list):
|
||||
return list(gold) == list(got)
|
||||
if isinstance(gold, (int, float)) and not isinstance(gold, bool):
|
||||
return abs(gold - got) < 0.006
|
||||
return gold == got
|
||||
|
||||
|
||||
def main() -> int:
|
||||
stats = defaultdict(lambda: [0, 0, 0])
|
||||
diffs = []
|
||||
qfile = paths.outputs_dir() / "t4" / "questions.jsonl"
|
||||
questions = [json.loads(line) for line in qfile.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
for q in questions:
|
||||
if not q["answerable"] and q["template_id"] not in ("L02_drill_complete_date", "L16_kickoff_md"):
|
||||
try:
|
||||
first = first_event(load(stem(q["slots"]["wellbore"])), q["slots"]["detail"])
|
||||
except Exception as exc:
|
||||
first = exc
|
||||
ans, ev = ("not reported" if first is None else first), set()
|
||||
else:
|
||||
ans, ev = check2(q)
|
||||
gold_ev = {f"{e['table']}:{e['report_id']}" + ("" if e["seq"] is None else f":{e['seq']}")
|
||||
for e in q["evidence"]}
|
||||
a_ok, e_ok = same(q["answer"], ans), gold_ev == ev
|
||||
st = stats[q["template_id"]]
|
||||
st[0] += 1
|
||||
st[1] += a_ok
|
||||
st[2] += e_ok
|
||||
if not (a_ok and e_ok):
|
||||
diffs.append({"id": q["id"], "slots": q["slots"], "gold": q["answer"], "raw": str(ans),
|
||||
"gold_evidence": len(gold_ev), "raw_evidence": len(ev)})
|
||||
print("DIFF", diffs[-1])
|
||||
for t, (n, a, e) in sorted(stats.items()):
|
||||
print(f"{t:34s} n={n:4d} answer_ok={a:4d} evidence_ok={e:4d}")
|
||||
total = [sum(v[i] for v in stats.values()) for i in range(3)]
|
||||
print("TOTAL questions, answers ok, evidence ok:", total)
|
||||
out = {"questions": total[0], "answers_ok": total[1], "evidence_ok": total[2], "templates": len(stats),
|
||||
"per_template": {t: dict(zip(("n", "answer_ok", "evidence_ok"), v)) for t, v in sorted(stats.items())},
|
||||
"diffs": diffs}
|
||||
(paths.outputs_dir() / "t4" / "xml_check.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
|
||||
return 0 if not diffs else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
214
scripts/09_audit.py
Normal file
214
scripts/09_audit.py
Normal file
@@ -0,0 +1,214 @@
|
||||
"""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 load() -> pd.DataFrame:
|
||||
d = paths.outputs_dir() / "labels"
|
||||
x = pd.read_parquet(d / "t2_inputs.parquet")
|
||||
lab = pd.read_parquet(d / "t2_labels.parquet")[["act_id", "npt_a", "npt_b", "cause_a", "cause_b"]]
|
||||
ops = pd.read_parquet(d / "t1_activities.parquet")[["act_id", "op_class"]]
|
||||
x = x.sort_values(["report_id", "seq"])
|
||||
g = x.groupby("report_id")["comments"]
|
||||
x["prev_comment"], x["next_comment"] = g.shift(1), g.shift(-1)
|
||||
return x.merge(lab, on="act_id", validate="1:1").merge(ops, on="act_id", validate="1:1")
|
||||
|
||||
|
||||
def sample() -> int:
|
||||
x = load()
|
||||
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 & 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())
|
||||
79
scripts/09_rater_agreement.py
Normal file
79
scripts/09_rater_agreement.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""Agreement of several blind raters with the code labels and with each other (trial audit, plan section 4.4).
|
||||
|
||||
python scripts/09_rater_agreement.py [DIR] # DIR defaults to outputs/audit/trial_100
|
||||
|
||||
Reads DIR/key.csv and every DIR/RATINGS_<name>.csv (the sheet of scripts/09_audit.py with the r_* columns filled).
|
||||
Writes DIR/raters.json: per rater Cohen's kappa against the code labels (NPT definitions a and b, cause group,
|
||||
operation class), kappa between every pair of raters, Fleiss' kappa over the raters, and the median over raters.
|
||||
The raters are LLMs, not people: the output is never an author or expert audit (plan section 12 item 20).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import audit, paths
|
||||
|
||||
|
||||
def fleiss(labels: pd.DataFrame) -> float | None:
|
||||
"""Fleiss' kappa for a frame with one column per rater (rows with a missing label are dropped)."""
|
||||
x = labels.dropna()
|
||||
n, m = x.shape[1], len(x)
|
||||
cats = sorted(set(x.to_numpy().ravel()))
|
||||
if m == 0 or len(cats) < 2:
|
||||
return None
|
||||
c = np.array([[int((x.iloc[i] == k).sum()) for k in cats] for i in range(m)], dtype=float)
|
||||
pi = ((c ** 2).sum(axis=1) - n) / (n * (n - 1))
|
||||
pj = c.sum(axis=0) / (n * m)
|
||||
pe = (pj ** 2).sum()
|
||||
return None if pe >= 1 else round(float((pi.mean() - pe) / (1 - pe)), 4)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
d = Path(sys.argv[1]) if len(sys.argv) > 1 else paths.outputs_dir() / "audit" / "trial_100"
|
||||
key = pd.read_csv(d / "key.csv").set_index("item")
|
||||
files = sorted(d.glob("RATINGS_*.csv"))
|
||||
if len(files) < 2:
|
||||
print("[raters] need at least two RATINGS_*.csv files")
|
||||
return 1
|
||||
r = {f.stem.removeprefix("RATINGS_"): pd.read_csv(f, dtype=str, encoding="utf-8-sig").set_index("item")
|
||||
.reindex(key.index) for f in files}
|
||||
out: dict = {"raters": list(r), "items": len(key), "vs_code": {}, "pairwise": {}, "fleiss": {}}
|
||||
for name, x in r.items():
|
||||
npt = x["r_npt"].map({"y": True, "n": False})
|
||||
cause = x["r_cause"].where(npt, "none").where(npt.notna())
|
||||
ops = key["op_class"] != "interruption"
|
||||
res = {"unsure": int(npt.isna().sum())}
|
||||
for df in ("a", "b"):
|
||||
res[f"npt_{df}"] = audit.agreement(npt, key[f"npt_{df}"].astype(bool), key["weight"])
|
||||
res[f"cause_{df}"] = audit.agreement(cause.fillna("unspecified").where(npt.notna()),
|
||||
key[f"cause_{df}"].fillna("none"), key["weight"])
|
||||
res["op_class"] = audit.agreement(x.loc[ops, "r_op_class"], key.loc[ops, "op_class"], key.loc[ops, "weight"])
|
||||
out["vs_code"][name] = res
|
||||
for a, b in itertools.combinations(r, 2):
|
||||
na, nb = (r[k]["r_npt"].map({"y": True, "n": False}) for k in (a, b))
|
||||
out["pairwise"][f"{a}-{b}"] = {
|
||||
"npt": audit.agreement(na, nb), "npt_weighted": audit.agreement(na, nb, key["weight"]),
|
||||
"cause": audit.agreement(r[a]["r_cause"].fillna("none"), r[b]["r_cause"].fillna("none")),
|
||||
"op_class": audit.agreement(r[a]["r_op_class"], r[b]["r_op_class"])}
|
||||
out["fleiss"] = {"npt": fleiss(pd.DataFrame({k: v["r_npt"].map({"y": "y", "n": "n"}) for k, v in r.items()})),
|
||||
"cause": fleiss(pd.DataFrame({k: v["r_cause"].fillna("none") for k, v in r.items()})),
|
||||
"op_class": fleiss(pd.DataFrame({k: v["r_op_class"] for k, v in r.items()}))}
|
||||
med = {}
|
||||
for t in ("npt_a", "npt_b", "cause_a", "cause_b", "op_class"):
|
||||
ks = [out["vs_code"][n][t]["kappa"] for n in r if out["vs_code"][n][t]["kappa"] is not None]
|
||||
med[t] = round(float(np.median(ks)), 4) if ks else None
|
||||
out["median_kappa_vs_code_weighted"] = med
|
||||
(d / "raters.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
|
||||
print(json.dumps(out, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
25
scripts/run_m1.sh
Executable file
25
scripts/run_m1.sh
Executable file
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run the M1 pipeline on top of P0 (scripts/run_p0.sh must have built outputs/ddr/):
|
||||
# OCR hub import -> OCR QC on the hub pages -> WITSML parse -> labels T1-T3 -> T4 questions -> T4 raw-XML check
|
||||
# -> trial audit sample -> unit tests.
|
||||
# The hub import needs the Dataset Hub export under data/ocr_hub/ (configs/ocr_hub.yaml; download it as in README);
|
||||
# without it that step and the QC on the hub pages are skipped. WITSML parsing reads about 20 GB and takes the longest.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
# Unconditional: the machine default is OMP/MKL/OPENBLAS_NUM_THREADS=40, and "${VAR:-4}" would keep that 40.
|
||||
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4
|
||||
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m volve_dia.runlog -n m1 -- bash "scripts/$(basename "$0")" "$@"
|
||||
step() { "$PY" -m volve_dia.runlog -- "$@"; }
|
||||
if compgen -G "data/ocr_hub/*" > /dev/null; then
|
||||
step "$PY" scripts/04_ocr_hub.py
|
||||
step "$PY" scripts/05_ocr_qc.py --source hub
|
||||
else
|
||||
echo "[m1] data/ocr_hub/ is empty: OCR hub import and its QC skipped"
|
||||
fi
|
||||
step "$PY" scripts/06_parse_witsml.py --workers 4
|
||||
step "$PY" scripts/07_labels.py
|
||||
step "$PY" scripts/08_t4_questions.py
|
||||
step "$PY" scripts/08_t4_xml_check.py
|
||||
step "$PY" scripts/09_audit.py sample
|
||||
step "$PY" -m pytest -q
|
||||
Reference in New Issue
Block a user