Files
Volve-DIA/scripts/02_parse_ddr.py
lamlvh a3c175638f Add P0 infrastructure for the Volve-DIA benchmark
Set up the data, parsing and quality-control layer for a public benchmark
on the Volve daily drilling reports (DDR) and WITSML real-time data.

- Data manifest with SHA-256 hashes of the three Volve subtrees in use.
- DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447
  activities, 17 tables) with locked expected counts.
- Render QC of the publisher HTML against the XML (272,544 items).
- OCR client for the shared chandra vLLM service, with a page cache keyed
  on model, prompt hash, dpi, max_tokens and temperature, and OCR QC
  against the HTML on a 26-report pilot.
- Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and
  40 tests.
- Research plan, technical overview and progress page (in Vietnamese).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:52:22 +00:00

103 lines
4.8 KiB
Python

"""Parse the DDR XML files into tables: outputs/ddr/<table>.parquet and outputs/ddr/volve_ddr.duckdb.
python scripts/02_parse_ddr.py
Fails if a count differs from EXPECTED (the counts the plan quotes), so a parser change that loses or adds rows is
caught. summary.json also holds the consistency checks of the source that the benchmark relies on.
"""
from __future__ import annotations
import json
import os
import sys
import duckdb
import pandas as pd
from volve_dia import paths
from volve_dia.ddr.xml import parse_dir
EXPECTED = {
"reports": 1759,
"wellbores": 26,
"activities": 23447,
"state": {"ok": 22967, "fail": 480},
"stateDetailActivity": {"success": 20802, "equipment failure": 1975, "operation failed": 456,
"stuck equipment": 109, "circulation loss": 92, "mud loss": 12, "injury": 1},
}
def checks(t: dict[str, pd.DataFrame]) -> dict:
r, a = t["reports"], t["activities"]
period_h = (r["end_utc"] - r["start_utc"]).dt.total_seconds() / 3600
span = a.merge(r[["report_id", "start_utc", "end_utc"]], on="report_id", suffixes=("", "_report"))
outside = (span["start_utc"] < span["start_utc_report"]) | (span["end_utc"] > span["end_utc_report"])
by_report = a.sort_values(["report_id", "seq"]).groupby("report_id")
gaps = (a.sort_values(["report_id", "seq"])["start_utc"]
- by_report["end_utc"].shift()).dt.total_seconds().div(3600).dropna()
covered = (by_report["duration_h"].sum() - period_h.set_axis(r["report_id"]).reindex(by_report.groups)).round(4)
return {
"file_date_is_period_end_date": int((r["file_date"] == r["dTimEnd"].str[:10]).sum()),
"duplicate_wellbore_dates": int(r.duplicated(["wellbore", "file_date"]).sum()),
"report_period_hours": {str(k): int(v) for k, v in period_h.round(2).value_counts().sort_index().items()},
"reports_without_activities": sorted(set(r["report_id"]) - set(a["report_id"])),
"reports_before_1990": r.loc[r["start_utc"].dt.year < 1990, "report_id"].tolist(),
"reports_sum24Hr_None": int((r["sum24Hr"].fillna("None") == "None").sum()), # published as "None"
"reports_forecast24Hr_None": int((r["forecast24Hr"].fillna("None") == "None").sum()),
"activities_missing_comments": int(a["comments"].isna().sum()),
"activities_missing_code": int(a["proprietaryCode"].isna().sum()),
"activities_nonpositive_duration": int((a["duration_h"] <= 0).sum()),
"activities_outside_report_period": int(outside.sum()),
"activity_gaps_hours": {"negative": int((gaps < 0).sum()), "zero": int((gaps == 0).sum()),
"positive": int((gaps > 0).sum())},
"activity_hours_vs_report_period": {"equal": int((covered == 0).sum()), "less": int((covered < 0).sum()),
"more": int((covered > 0).sum()),
"hours_uncovered": round(float(-covered[covered < 0].sum()), 2)},
"comment_chars_mean": round(float(a["comments"].str.len().mean()), 1),
"sum24Hr_chars_mean": round(float(r["sum24Hr"].str.len().mean()), 1),
"code_main": {k: int(v) for k, v in a["code_main"].value_counts().items()},
"codes": int(a["proprietaryCode"].nunique()),
}
def main() -> int:
out = paths.outputs_dir() / "ddr"
out.mkdir(parents=True, exist_ok=True)
tables = parse_dir(paths.ddr_xml_dir())
for name, df in tables.items():
df.to_parquet(out / f"{name}.parquet", index=False)
db, tmp = out / "volve_ddr.duckdb", out / "volve_ddr.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)
r, a = tables["reports"], tables["activities"]
got = {
"reports": len(r),
"wellbores": int(r["wellbore"].nunique()),
"activities": len(a),
"state": {k: int(v) for k, v in a["state"].value_counts().items()},
"stateDetailActivity": {k: int(v) for k, v in a["stateDetailActivity"].value_counts().items()},
}
summary = {
"counts": got,
"tables": {name: {"rows": len(df), "columns": df.shape[1]} for name, df in tables.items()},
"sentinels_replaced": int(tables["sentinels"]["n"].sum()),
"checks": checks(tables),
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(json.dumps({k: v for k, v in summary.items() if k != "tables"}, indent=1, ensure_ascii=False))
diff = {k: (EXPECTED[k], got[k]) for k in EXPECTED if EXPECTED[k] != got[k]}
if diff:
print("counts differ from EXPECTED (expected, got):", diff)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())