Compare commits

...

2 Commits

Author SHA1 Message Date
18d1ce5407 Update .gitignore comment: data/Volve is now a local copy
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 08:53:20 +00:00
17916650a5 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>
2026-11-17 08:34:35 +00:00
38 changed files with 11101 additions and 417 deletions

View File

@@ -5,3 +5,7 @@ VOLVE_DIA_OCR_URL=
# VOLVE_DIA_VOLVE_ROOT=/path/to/Volve
# VOLVE_DIA_OUTPUTS=/path/to/outputs
# VOLVE_DIA_LOGS=/path/to/logs
# Dataset Hub export of the OCR run outside this repository (configs/ocr_hub.yaml). Used only to download it.
# DATASET_HUB_URL=
# DATASET_HUB_API_KEY=
# VOLVE_DIA_OCR_HUB_DATASET=

5
.gitignore vendored
View File

@@ -10,8 +10,9 @@ __pycache__/
# Machine-local settings: the OCR service URL lives here (template: .env.example)
.env
# Volve (Equinor, CC BY-NC-SA 4.0): data/Volve is a symlink to ML-Porosity/data/Volve, never pushed;
# hashes of the subtrees this project reads are in data_manifest/volve_dia.json
# Volve (Equinor, CC BY-NC-SA 4.0): data/Volve is a local copy (a symlink until 17/11/2026), never pushed; the OCR hub
# export and third-party repos also live under data/. Hashes of what this project reads are in
# data_manifest/volve_dia.json
data/
# Parsed tables, OCR pages and QC of every run: regenerate with scripts/run_p0.sh (OCR pages are cached by hash)

View File

@@ -4,40 +4,38 @@ Volve-DIA: a public benchmark and baselines for drilling-context recognition, NP
Read first: `docs/plan.md` (plan, gates, decisions; §1 data facts, §6 roadmap, §10 forbidden claims, §12 decision log), `README.md` (setup, scripts, logging), `docs/danh-gia-huong-NCKH-2026-10-29.md` (why this direction, competitors, references; local only, not in git), `docs/technical_overview.md` (a lecture for newcomers: drilling, DDR, leakage, tasks, labels, OCR, evaluation, code map). Progress page: `report.html`. These docs are in Vietnamese.
## Status (29/10/2026)
## Status (17/11/2026)
- **P0 (infrastructure) done and committed** (first commit on `main`, 29/10/2026). The project folder is `/home/jovyan/lamlvh/Volve-DIA` (renamed from `Scientific` on 29/10/2026); pushed to remote `origin` `https://gitea.vts-ai.space/lamlvh/Volve-DIA`, which is **public**. `scripts/run_p0.sh` runs scripts 00–05 and the tests in about 3.3 min (run 20261029-105934_p0: all ok, 40 tests pass).
- **Data:** `data/Volve` is a symlink to `ML-Porosity/data/Volve`. The three subtrees read here (`Well_technical_data`, `Reports`, `WITSML Realtime drilling data`, about 20 GB) are hashed in `data_manifest/volve_dia.json`.
- **DDR XML parsed** (`02`): 1,759 reports, 26 wellbores, 23,447 activities (480 `fail`), 17 tables in `outputs/ddr/volve_ddr.duckdb`. The counts are locked in `EXPECTED` and the source checks are in `outputs/ddr/summary.json` (plan §1.2).
- Gaps found while writing the technical overview (plan §1.2, §12 item 9): `diaHole` is NULL in 990 reports, 260 of them with drilling activities (2,618 rows, 24 wellbores); `ropCurrent` is a sentinel everywhere, so ROP comes from `distDrill`, `bits.bitRun_ropAv` (88 values, 80 reports) or WITSML.
- **Three versions of every report:** each DDR exists as XML (the source), publisher HTML and a PDF rendered from the HTML (3,066 pages, born-digital).
- Render QC (`03`, 272,544 items): the HTML prints exactly what the XML holds, except two flags. *Tight well* and *HPHT* are 0 in every XML but "Y" in all 1,759 HTML reports, a publisher render bug. Take them from the XML only.
- **OCR parser:** chandra on the shared vLLM service (`configs/ocr.yaml`). The request and prompt are a byte copy of vopec-chatbot's (prompt hash-checked).
- Pilot done: one report per wellbore, 26 reports, 47 pages, all ok; 6.2 s/page wall with 4 workers.
- OCR QC (`05`) against the HTML: content CER 2.50%, WER 5.57%, exact rate 0.923 over 5,835 items. Operations cells: exact 0.859, CER 3.12%.
- Error types (hallucinated units, autocorrected source typos, merged or split columns, shifted depth values) are in plan §1.3. The parser repairs and QC rules that produced these numbers are in plan §12 item 6.
- **Full OCR not started.** All 1,759 reports (3,066 pages, about 5.3 h) are waiting because the OCR service has returned 503 since the pilot. The platform page says the environment is not running (pod does not exist). The service is shared and its pod is not ours, so ask the user to restart it.
- **P0 (infrastructure) done and committed** (first commit on `main`, 29/10/2026). The project folder is `/home/jovyan/lamlvh/Volve-DIA`; remote `origin` `https://gitea.vts-ai.space/lamlvh/Volve-DIA` is **public**. `scripts/run_p0.sh` runs scripts 00–05 and the tests.
- **M1 machine work done on 17/11/2026, not committed** (git shows many untracked and modified files; commit only when the user asks). `scripts/run_m1.sh` chains the M1 steps but has not been run end to end. Last pytest run by the WITSML agent: 141 passed.
- **Data:** `data/Volve` is now a real directory (no longer a symlink); `/home` has about 75 GB free (98%). The manifest holds 25,571 files (formation tops added), `--check` ok. Third-party material is in `data/third_party/` (untracked).
- **DDR XML:** 1,759 reports, 26 wellbores (11 wells), 23,447 activities; counts locked in `EXPECTED`. Render bugs: *Tight well* and *HPHT* ("Y" in every HTML), and the Bit Record "End mMD" column (prints `bitRun_mdHoleStart`). `03` covers only the header, 31 fields, summaries and Operations.
- **OCR:** a colleague ran the full OCR and exported it through Dataset Hub (credentials only in `.env`, never in committed files or runlog commands). `scripts/04_ocr_hub.py` matches pages to DDRs by content (3,059 of 3,066 pages, 1,752 of 1,759 reports complete; 7 pages unmatched, 16 pages with a date disagreement not yet inspected). QC on the hub pages (`scripts/05_ocr_qc.py --source hub`, 1,752 reports): content CER 2.40%, WER 5.56%, exact 0.9181; depth fields and rig name are the weakest. The shared vLLM service is not used any more; `04_ocr.py` and its page cache stay for the pilot.
- **WITSML** (`06_parse_witsml.py`, written by a subagent; its figures are locked in `EXPECTED` and 30 tests): 21 DDR wellbores have time logs (not 14), 1,384 reports (not 964); WITSML `15/9-F-15 S` is DDR `15/9-F-15` and two more names are shifted by one. Formation tops: 409 picks, 24 DDR wellbores with own picks, 2 with shared picks. Tables in `outputs/witsml/` (2.2 GB, gitignored).
- **Labels T1–T3** (`07_labels.py`, `configs/labels.yaml`): T1 section with forward fill (672 published + 260 filled drilling days), T2 NPT (a) 3,577 rows / (b) 4,286 rows, T3 844 / 979 positive cells (only 50% of NPT rows can be located in depth).
- **T4** (`08_t4_questions.py`, `configs/t4_templates.yaml`): 1,662 questions from 39 templates; SQL, independent pandas and raw-XML answers agree 100%.
- **Protocol:** `configs/protocol_v1.yaml` is a **draft, not locked** (split by well with leave-one-well-out; development wells F-7 and F-9; class evaluability rule: at least 3 wells with at least 5 items; NPT definition a unless audit 1 says otherwise). Locked by SHA-256 at G1, before any model run.
- **Trial audit:** 100 masked items drawn (`09_audit.py sample`, `outputs/audit/trial_100/`) and rated blind by three LLM raters (Sonnet, Opus, Haiku; `RATINGS_llm_*.csv`, `scripts/09_rater_agreement.py` -> `raters.json`). They are **LLM raters, not an author audit**: never describe them as the author's, a human or an expert audit. Median weighted kappa against the code labels: NPT a 0.553, NPT b 0.574, cause a 0.456, operation class 0.434; Fleiss between raters about 0.66. No human rated; there is no human time per row.
- **Literature:** `docs/literature_notes.md`, `docs/references.bib`. No public NPT label set on Volve is independent of the DDR codes; the plan's "three independent label sets" was dropped. PetroAgents full text read (`docs/lit_petroagents.pdf`): well-day unit, 60-example samples, leakage ablation on 30 examples, split by wellbore.
- Nothing is running.
- **Agents:** delegate to Sonnet; to Opus only for very complex work; do not use Fable (user decision 17/11/2026).
## Next
Roadmap and gates: `docs/plan.md` §6. Month 1 (M1) = data, labels, protocol.
Roadmap and gates: `docs/plan.md` §6, §12 item 1.
1. **Full DDR OCR once the service answers:**
`setsid nohup scripts/runlog.sh -n ocr_full -- scripts/04_ocr.py --all > /dev/null 2>&1 &`
While the service is down, the script stops before sending any page ("OCR service not available: HTTP 503", exit 1), so starting it is also the check. It resumes from the page cache, keeps 4 workers, and stops by itself if 8 pages in a row fail. Then run `scripts/runlog.sh scripts/05_ocr_qc.py` on all 1,759 reports and update plan §1.3 and `report.html`.
2. **WITSML parser** (time logs, 68 channels at about 3 s; bhaRun, message, trajectory, mudLog) into DuckDB with the TADI sentinels and filters (plan §4.1). Check whether WITSML `15/9-F-15 S` is DDR `15/9-F-15`, and find the source folder of the formation tops (both [XM], plan §1.1, §4.1).
3. **Code → label mapping** (`configs/labels.yaml`, public): T1 phase from hole size, T2 NPT and cause group from `stateDetailActivity` + `proprietaryCode` + `state`, T3 MD intervals on a 10 m grid. T1 needs a fill rule for the 260 drilling days without `diaHole` (plan §4.3). Check `15_9_19_A_1980_01_01` (a 1980 date; no activities).
4. **T4 question templates** with SQL answers on DuckDB and cited row ids.
5. **Trial blind self-audit** of 100 activity rows (codes masked; estimates label agreement and time per row) and a draft of the evaluation protocol (`configs/protocol_v1.yaml`), which must decide whether GroupKFold groups by wellbore or by well (26 wellbores in 11 wells; sidetracks share the upper hole; plan §4.5 [XM]). Blind audit 1 (about 300 rows, stratified by wellbore and class) follows in M2, and the protocol is locked by SHA-256 at gate G1, **before any model run** (plan §4.4, §6, §12 item 1).
6. Read PetroAgents, Bassey 2026 and EAGE 2026101276 in full; download DrillScribe, the Anatoly5ms repo and the OMAE 2024 stuck-pipe set (plan §12 item 1).
1. M2 label validation is by blind LLM raters (at least 3 model families, 300 rows, second pass), not an author audit: no human rater is available (decision 17/11/2026, plan §12 item 20). Never call it an author, expert or manual audit.
2. C4 reports results with and without the 16 date-disagreement pages; the 7 unmatched reports are dropped.
3. Decided 17/11 (plan §12 item 21): WITSML suspect values (-999, -99999, 99999, 9999, |v| > 1e15) are missing at feature stage; formation picks file is the label source; 7 unmatched OCR reports are dropped from C4; NPT definition a vs b decided at M2 (trial favours b by 0.021, not conclusive).
4. M2: blind LLM-rater validation (about 300 rows, strata zone, cause group, well), cross-checks against DrillScribe and a re-implementation of the Anatoly5ms text rules, then lock `protocol_v1` at G1.
5. Read in full: EAGE 2026101276, SPE-236554-MS, SPE-235330-MS, IPTC-25191-MS.
## Conventions
- **Ground truth:** every label and every T4 answer comes from the XML (and WITSML), by code, with provenance. HTML and PDF are renders: never take a label from them. People only *validate* labels (blind audit, independent label sets, calibrated judge); they never create them.
- **Ground truth:** every label and every T4 answer comes from the XML (and WITSML), by code, with provenance. HTML and PDF are renders: never take a label from them. Labels are only *validated* (blind LLM raters, cross-checks with third-party sets, calibrated judge), never created by raters. No human rater is available, so no result may be called a human, author or expert audit.
- **No leakage:** activity codes (`proprietaryCode`, `stateDetailActivity`, `state`) are masked in model inputs for T2 and T3. T3 uses only features from before the event. Splits are by wellbore (GroupKFold); nothing is chosen on test wellbores. Report results with and without the masked codes.
- **Locked protocols:** the evaluation protocol is locked by SHA-256 before the first model run. Never edit a locked protocol or relax a threshold. New decisions go into a new protocol with a recorded deviation. Report results as they come out, including failures.
- **OCR service:** the URL lives only in the untracked `.env` (`VOLVE_DIA_OCR_URL`; template `.env.example`). Read it only through `volve_dia.ocr.service_url()`. Never put it on a command line (`runlog` records the command in `logs/index.csv`), in a committed file, or in output shown to the user. The service is shared with vopec-chatbot: keep `workers: 4`. The model, prompt hash, dpi, max_tokens and temperature form the page-cache key, so changing one re-reads every page.
- **OCR service and Dataset Hub:** the Hub URL, dataset id and API key live only in the untracked `.env` (`DATASET_HUB_URL`, `DATASET_HUB_API_KEY`, `VOLVE_DIA_OCR_HUB_DATASET`); never put them on a command line, in a committed file or in output shown to the user. The OCR service URL lives only in the untracked `.env` (`VOLVE_DIA_OCR_URL`; template `.env.example`). Read it only through `volve_dia.ocr.service_url()`. Never put it on a command line (`runlog` records the command in `logs/index.csv`), in a committed file, or in output shown to the user. The service is shared with vopec-chatbot: keep `workers: 4`. The model, prompt hash, dpi, max_tokens and temperature form the page-cache key, so changing one re-reads every page.
- **Git:** work on `main`. Do not create branches unless the user explicitly asks. Commit only when the user asks. End commit messages with a co-author line for the agent.
- **Language:** code, figures, paper text and commit messages in academic English. `README.md`, `docs/plan.md`, `docs/technical_overview.md`, `report.html` and explanations to the user in Vietnamese.
- **Decisions:** decide from evidence and proceed.
@@ -49,7 +47,7 @@ Roadmap and gates: `docs/plan.md` §6. Month 1 (M1) = data, labels, protocol.
## Not in git (other machines)
`data/` (the Volve symlink), `outputs/`, `logs/runs/`, `.env`, `docs/*.DOCX`, `docs/*.pdf`, `docs/danh-gia-huong-NCKH-2026-10-29.md` and the `.venv` are gitignored. Check the data with `scripts/00_data_manifest.py --check` and regenerate `outputs/` with `scripts/run_p0.sh`, except the OCR page cache `outputs/ocr/pages/`: it holds hours of GPU time, so copy it rather than reading the pages again.
`data/` (the Volve copy, OCR hub export, third-party repos), `outputs/`, `logs/runs/`, `.env`, `docs/*.DOCX`, `docs/*.pdf`, `docs/danh-gia-huong-NCKH-2026-10-29.md` and the `.venv` are gitignored. Check the data with `scripts/00_data_manifest.py --check` and regenerate `outputs/` with `scripts/run_p0.sh`, except the OCR page cache `outputs/ocr/pages/`: it holds hours of GPU time, so copy it rather than reading the pages again.
## Skills

View File

@@ -9,13 +9,14 @@ git clone https://gitea.vts-ai.space/lamlvh/Volve-DIA && cd Volve-DIA
python -m venv .venv # Python 3.13
.venv/bin/pip install -r requirements-lock.txt
.venv/bin/pip install --no-deps -e .
cp -n .env.example .env # rồi điền VOLVE_DIA_OCR_URL
cp -n .env.example .env # rồi điền các biến cần dùng (xem .env.example); không commit .env
```
`data/Volve` là symlink tới `ML-Porosity/data/Volve` (Volve Data Village của Equinor). Project chỉ đọc ba thư mục con, khoảng 20 GB, hash nằm trong `data_manifest/volve_dia.json`:
`data/Volve` là bản sao thật của Volve Data Village của Equinor (trước 17/11/2026 là symlink tới `ML-Porosity/data/Volve`). Project đọc ba thư mục con, khoảng 20 GB, và một file formation tops; hash của 25.571 file nằm trong `data_manifest/volve_dia.json`:
- `Well_technical_data/`: DDR ở ba dạng XML, HTML, PDF;
- `WITSML Realtime drilling data/`;
- `Reports/`: Discovery report và PUD, dành cho giai đoạn sau.
- `Reports/`: Discovery report và PUD, dành cho giai đoạn sau;
- `Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat`: formation tops.
Trỏ tới chỗ khác bằng `VOLVE_DIA_VOLVE_ROOT`. Kết quả ghi vào `outputs/` (đổi bằng `VOLVE_DIA_OUTPUTS`), log ghi vào `logs/` (đổi bằng `VOLVE_DIA_LOGS`). Các biến này đặt được trong `.env`; biến môi trường thật được ưu tiên.
@@ -23,11 +24,14 @@ Trỏ tới chỗ khác bằng `VOLVE_DIA_VOLVE_ROOT`. Kết quả ghi vào `out
```bash
scripts/run_p0.sh # toàn bộ P0 và test, khoảng 3,3 phút khi các trang của OCR pilot đã có trong cache
# OCR toàn bộ 1.759 DDR (3.066 trang, khoảng 5,3 giờ với 4 worker); chạy lại lệnh này để resume:
# (dự phòng) tự OCR toàn bộ trên dịch vụ chung, khoảng 5,3 giờ với 4 worker, resume bằng cùng lệnh; hiện dùng bản của hub, xem dưới:
setsid nohup scripts/runlog.sh -n ocr_full -- scripts/04_ocr.py --all > /dev/null 2>&1 &
scripts/runlog.sh scripts/05_ocr_qc.py # sau đó: QC OCR trên mọi báo cáo đã đọc đủ trang
scripts/run_m1.sh # pipeline M1: OCR hub, QC, WITSML, nhãn, T4, mẫu audit, test (WITSML mất vài phút, đọc 20 GB)
```
**OCR toàn tập không chạy lại trên dịch vụ chung** mà lấy bản đã chạy, xuất qua Dataset Hub (một đồng nghiệp chạy). Tải về `data/ocr_hub/` bằng công cụ `dataset-hub` với URL, dataset id và khóa API lấy từ người quản lý, đặt trong `.env` (`DATASET_HUB_URL`, `DATASET_HUB_API_KEY`, `VOLVE_DIA_OCR_HUB_DATASET`); không ghi các giá trị này lên dòng lệnh hay vào file commit. Sau đó `scripts/runlog.sh scripts/04_ocr_hub.py` ghép trang về DDR và `scripts/runlog.sh scripts/05_ocr_qc.py --source hub` chạy QC (kết quả `outputs/ocr_qc_hub/`).
Log và runtime: mỗi lần chạy `run_p0.sh` tạo `logs/runs/<YYYYmmdd-HHMMSS>_p0/`, mỗi bước một thư mục con gồm hai file:
- `log.txt`: stdout và stderr, đầu dòng có thời gian đã trôi;
- `meta.json`: lệnh, git commit và hash mã nguồn, biến luồng, wall/CPU time, RSS đỉnh, mã thoát.
@@ -78,7 +82,15 @@ Dịch vụ OCR:
| `scripts/03_render_qc.py` | QC bản in: HTML có in đúng XML không (dòng header, các trường đầu báo cáo, hai đoạn tóm tắt 24 h, bảng Operations) → `outputs/render_qc/` |
| `scripts/04_ocr.py --pilot\|--all\|--docs A,B [--limit N]` | OCR PDF bằng chandra vào cache `outputs/ocr/pages/`; `--pilot` đọc 1 báo cáo mỗi wellbore (26 báo cáo, 47 trang) → `outputs/ocr/ddr_docs.csv` |
| `scripts/05_ocr_qc.py` | QC OCR: chandra đọc PDF có khớp HTML không; CER, WER, tỉ lệ khớp theo phần, bảng, trường; các lỗi ký tự hay gặp → `outputs/ocr_qc/` |
| `scripts/04_ocr_hub.py` | Ghép từng trang của export Dataset Hub (`data/ocr_hub/`) về DDR bằng nội dung và ảnh; ghi trang vào cache và `outputs/ocr/hub/` (match.csv, summary.json) |
| `scripts/06_parse_witsml.py [--workers N]` | WITSML (log thời gian và độ sâu, trajectory, message, bhaRun, mudLog) và formation tops → `outputs/witsml/`, `outputs/tops/`; dừng nếu số lượng lệch `EXPECTED` hay một wellbore khớp DDR khác tốt hơn |
| `scripts/07_labels.py` | Nhãn T1–T3 từ `configs/labels.yaml` → `outputs/labels/` và `analysis.md` cho protocol |
| `scripts/08_t4_questions.py` | Câu hỏi T4 từ `configs/t4_templates.yaml`, đáp án SQL, đối chiếu pandas → `outputs/t4/` |
| `scripts/08_t4_xml_check.py` | Tính lại đáp án T4 từ XML thô, độc lập với DuckDB |
| `scripts/09_audit.py sample\|score RATINGS.csv` | Mẫu 100 dòng chấm mù thử (che mã), rồi chấm điểm bài chấm của tác giả → `outputs/audit/trial_100/` |
| `scripts/09_rater_agreement.py [DIR]` | κ của từng `RATINGS_*.csv` (LLM rater) với nhãn code, κ giữa các rater, Fleiss → `raters.json` |
| `scripts/runlog.sh` | Bọc một lệnh để ghi log và runtime |
| `scripts/run_m1.sh` | Chạy pipeline M1 trên nền P0: 04_ocr_hub, 05 `--source hub`, 06–09, pytest |
| `scripts/run_p0.sh` | Chạy toàn bộ P0: 00 `--check`, 01–05 (04 ở chế độ `--pilot`), pytest |
Mã nguồn trong `volve_dia/`:
@@ -88,6 +100,11 @@ Mã nguồn trong `volve_dia/`:
- `ddr/rendered.py`: đọc HTML và các khối OCR về cùng một cấu trúc, kèm các sửa cấu trúc bảng ghi trong `notes`;
- `ddr/qc.py`: so sánh, căn hàng và căn cột;
- `ocr.py`: client chandra và page cache;
- `ocr_hub.py`: ghép trang export Dataset Hub về DDR;
- `witsml.py`, `tops.py`: WITSML và formation tops;
- `labels.py`: nhãn T1–T3;
- `t4.py`, `t4_pandas.py`: câu hỏi T4 và cài đặt độc lập để đối chiếu;
- `audit.py`: mẫu và điểm audit mù;
- `runlog.py`: log và runtime.
Test: `.venv/bin/python -m pytest -q`. Các test cần dữ liệu Volve mang marker `data` và tự bỏ qua khi thiếu dữ liệu.

325
configs/labels.yaml Normal file
View File

@@ -0,0 +1,325 @@
# Volve-DIA deterministic labels T1-T3: the public mapping from the DDR XML tables to labels.
#
# Every label is produced by code (volve_dia/labels.py, scripts/07_labels.py) from the tables that
# scripts/02_parse_ddr.py builds from the WITSML drillReport XML files. No person and no language model creates a
# label; HTML, PDF and OCR text are never a label source. People only validate (blind audit).
#
# Counts ("n") are activity rows in the 1,759 reports. scripts/07_labels.py fails if a count here differs from the
# data, so this file cannot drift from the source. Lines marked "judgement:" are choices that the data do not
# force; each carries its rationale. Choices that belong to the evaluation protocol (locked at gate G1) are NOT
# made here: the candidates are produced side by side (see `t2.npt_definitions`, `op_class` vs `op_group`,
# `cause_group` vs `cause_fine`).
version: 1
# ----------------------------------------------------------------------------------------------------------------
# Reports that carry no label
# ----------------------------------------------------------------------------------------------------------------
reports:
# A report is a placeholder when it has no activity and its period ends more than `placeholder_days_before_spud`
# days before the spud date (dTimSpud) of its own wellbore. One report qualifies: 15_9_19_A_1980_01_01 (period
# 1979-12-31 to 1980-01-01, spud 1997-07-25, sum24Hr and forecast24Hr "None", five survey stations dated
# 1980-01-01, created 2018-05-03). It is a container for tie-in survey stations with a default date, not a
# drilling day: status `placeholder_date`, excluded from the wellbore timeline and from T1-T3.
placeholder_days_before_spud: 365
# Eight further reports have no activity but a real date. They keep their report-day section label (T1) because
# the report header is present; they have no operation label and contribute no row to T2 and T3. Status
# `no_activities`. They stay in the timeline so that forward fill passes through them.
keep_reports_without_activities: true
# ----------------------------------------------------------------------------------------------------------------
# T1: hole section and phase (report-day), operation class (activity)
# ----------------------------------------------------------------------------------------------------------------
t1:
# Source column: reports.diaHole (inches). The `phase` column of activities is the rig type ("fixed",
# "wire line"), not a drilling phase, and is not used.
# All hole sizes that occur in the data (n = reports with that diaHole; 990 reports have none):
# 36 -> 60, 26 -> 99, 17.5 -> 154, 12.25 -> 185, 9.875 -> 1, 8.5 -> 239, 6 -> 31.
# `section` is the label string; `phase` is the nominal name of the casing string that the hole is drilled for.
# judgement: phase names follow the size only. Four wells (F-4, F-5, F-7, F-9) have no 26" hole and drill 17.5"
# directly below the 30" conductor, so "intermediate" is a nominal name there.
hole_sizes:
36.0: {n: 60, section: "36", phase: conductor} # 36" hole, 30" conductor
26.0: {n: 99, section: "26", phase: surface} # 26" hole, 20" casing
17.5: {n: 154, section: "17.5", phase: intermediate} # 17 1/2" hole, 13 3/8" or 14" casing
12.25: {n: 185, section: "12.25", phase: production} # 12 1/4" hole, 9 5/8" or 10 3/4" casing
9.875: {n: 1, section: "9.875", phase: pilot} # 9 7/8" pilot hole of 15/9-19 S, later opened to 36"/26"
8.5: {n: 239, section: "8.5", phase: reservoir} # 8 1/2" hole, 7" liner or open hole
6.0: {n: 31, section: "6", phase: reservoir} # 6" hole of 15/9-19 BT2 below the 7" liner
# judgement: 6" keeps its own `section` but shares `phase: reservoir` with 8.5": it occurs in one wellbore, so a
# separate phase could never be both trained and tested under a split by wellbore.
# A report with reports.diaPilot set (19 reports: 18 of 15/9-F-12 at 8.5", 1 of 15/9-19 S at 9.875") drills a
# pilot hole that is opened up afterwards. Its `section` is the pilot size as published; its `phase` is `pilot`,
# whatever the size. judgement: an 8.5" pilot at 258-1353 m is not the reservoir section.
pilot_phase: pilot
# Fill rule for reports without diaHole (990 reports: the placeholder and 989 others, 260 of them with
# drilling-group activities). Candidates are evaluated by scripts/07_labels.py on the 769 reports with a known
# diaHole: the value is masked and each rule tries to recover it (outputs/labels/fill_eval.parquet, summary.json
# -> t1.fill_evaluation). Masking schemes: `single` (one report at a time), `tail_half` / `head_half` (the last /
# first half of a run of equal diaHole), `whole_run` (a complete run).
# Where the real gaps lie (all 989 / the 260 drilling days): after the last known section of the wellbore 936 /
# 228, between two runs of the same size 21 / 16, between runs of different sizes 15 / 11 (casing and riser days
# of 15/9-F-15 C after its 12.25" section), before the first known section 17 / 5. The gaps are tails of
# sections: the header stops carrying diaHole once the last section reaches TD.
fill:
# judgement: forward fill = the hole section most recently opened in this wellbore. It is the convention the
# source follows for intermediate sections (casing and cementing days after section TD keep the diaHole of that
# section) and it needs only diaHole and the report order. Evidence (summary.json -> t1.fill_evaluation):
# - `tail_half`, the scheme shaped like the real gaps: ffill 1.0000 (by construction: the head of the run stays
# visible), hole_start 0.8489, bit_ffill 0.6291, csg_last 0.4615, depth_range 0.4533, casing_program 0.3599;
# - `single`: ffill 0.9051 (every miss is the first report of a new section); hole_start is higher (0.9558)
# but answers only 25 of the 989 real gaps, because the header opens a new record at section TD;
# - on the real gaps ffill agrees with the hole size named in the text on 7 of 8 reports and with the bit
# record of the report on 23 of 30 (the bit record agrees with a known diaHole on 65 of 75 reports).
# Known limit: on the last reports of a wellbore the kick-off of the next sidetrack may already be under way in
# a larger hole (4 of the 7 bit disagreements); the label stays the last section of the reporting wellbore.
rule: ffill
# Reports before the first known diaHole of a wellbore (rig move, pre-spud preparation; 17 reports, 5 with
# drilling-group activities; 10 of them in 15/9-19 S) cannot be forward filled. judgement: they take the first
# section of the wellbore (the section being prepared; the text names that size on 3 of 3 reports that name
# one) and are marked `filled_by: bfill_leading`, so the protocol can drop them.
leading: bfill
# Rules that were evaluated (volve_dia.labels.FILL_RULES). `text` reads the hole size from sum24Hr and the
# drilling-group comments; it is a cross-check only and never a label source, because that text is model input.
candidates: [ffill, bfill, nearest, hole_start, csg_last, depth_range, bit_report, bit_ffill, casing_program, text]
# casing_program: outer diameter of the last casing (casings.od at the shoe nearest to reports.mdCsgLast,
# within `casing_shoe_tolerance_m`, same well) -> size of the next hole. Standard bit/casing pairs.
casing_shoe_tolerance_m: 15.0
casing_od_to_next_hole: {30.0: 26.0, 20.0: 17.5, 14.0: 12.25, 13.375: 12.25, 10.75: 8.5, 9.625: 8.5,
7.625: 6.0, 7.0: 6.0, 6.625: 6.0}
# Provenance columns of every filled report: filled_by, fill_source_report_id, fill_gap_reports, fill_gap_days.
# A report-day is in scope `drilling_day` when it has at least one drilling-group activity, else `other_day`
# (completion, workover, plug and abandonment, rig move): on those days the section is the last one drilled, far
# in the past for a 2016 abandonment. Whether `other_day` reports are scored is a protocol choice. The eight
# reports without activities have scope `no_activities`, the placeholder `excluded`.
# Hook for a section label from WITSML (not built here; another parser fills outputs/witsml/). When a table
# with the columns (wellbore, start_utc, end_utc, section_in) is passed to labels.attach_witsml_section, the
# report-day table gains `section_witsml` and `section_agree`; without it both columns are NULL.
witsml_section: {enabled: false, table: null}
# Day-level operation: the op_group and the op_class with the most activity hours in the report (ties: the
# alphabetically first), with their share of the reported hours.
# Operation class of an activity = `op_class` of its proprietaryCode in `codes` below.
# judgement: the sub-code decides the class wherever it names an operation, across main groups
# ("drilling -- trip", "plug abandon -- trip" and "formation evaluation -- trip" are all `trip`). The main group
# is kept as the coarser label `op_group` (7 classes), the raw sub-code as `op_sub` (41 values), so the protocol
# can choose the level and merge rare classes.
op_classes:
drill_ream: "making or enlarging hole: drill, ream, hole open (ream 97 and hole open 6 are too few
to stand alone and are the same bit-on-bottom work)"
trip: "tripping, in any main group"
casing_cement: "running and cementing casing or liner (the single code `drilling -- casing`)"
circulate: "circulating and conditioning, including circulating for geological samples (11)"
bop_wellhead: "BOP and wellhead work: `bop/wellhead equipment` and `bop activities`"
formation_evaluation: "measurements of the well and the formation: log, rft/fit, core, drill stem test, survey,
pressure detection (flow checks, 24)"
completion: "completion string, sand control, SCSSSV test, stimulate (1 row)"
perforate: "perforating, in completion, workover and plug-and-abandon"
wireline: "wire line work"
plug_abandon: "plug-and-abandon operations: cement plug, mechanical plug, squeeze, cut, mill, equipment
recovery"
rig_move: "skid, anchor, transit, position"
rig_up_down: "rig up/down outside interruptions"
wait: "`wait` sub-code outside the interruption group (79 rows: waiting on cement, on the
production department, industrial action, muster)"
other: "`other` sub-code of every non-interruption group. judgement: the comments of
`plug abandon -- other` (2,332) and `drilling -- other` (572) are the same auxiliary rig
work (handling equipment, cleaning, pressure tests), so one class is learnable from text;
`op_group` still separates them"
interruption: "all ten interruption codes. The code does not say which operation was interrupted, so
this class repeats NPT definition (a) of T2; the protocol may leave it out of T1"
# ----------------------------------------------------------------------------------------------------------------
# The 64 proprietaryCodes: n, T1 operation class, T2 cause group
# ----------------------------------------------------------------------------------------------------------------
# `cause` is used only on NPT rows. `detail` means: the code names no cause, take it from stateDetailActivity
# (t2.cause_from_detail). Non-interruption codes are NPT only under definition (b) and always use `detail`.
codes:
# drilling: 9137 rows, 12 codes
"drilling -- casing": {n: 3204, op_class: casing_cement, cause: detail}
"drilling -- drill": {n: 1822, op_class: drill_ream, cause: detail}
"drilling -- trip": {n: 1430, op_class: trip, cause: detail}
"drilling -- bop/wellhead equipment": {n: 1252, op_class: bop_wellhead, cause: detail}
"drilling -- other": {n: 572, op_class: other, cause: detail}
"drilling -- circulating conditioning": {n: 357, op_class: circulate, cause: detail}
"drilling -- bop activities": {n: 226, op_class: bop_wellhead, cause: detail}
"drilling -- survey": {n: 115, op_class: formation_evaluation, cause: detail}
"drilling -- ream": {n: 97, op_class: drill_ream, cause: detail}
"drilling -- wait": {n: 32, op_class: wait, cause: detail}
"drilling -- pressure detection": {n: 24, op_class: formation_evaluation, cause: detail}
"drilling -- hole open": {n: 6, op_class: drill_ream, cause: detail}
# formation evaluation: 732 rows, 10 codes
"formation evaluation -- log": {n: 206, op_class: formation_evaluation, cause: detail}
"formation evaluation -- rig up/down": {n: 143, op_class: rig_up_down, cause: detail}
"formation evaluation -- trip": {n: 109, op_class: trip, cause: detail}
"formation evaluation -- drill stem test": {n: 86, op_class: formation_evaluation, cause: detail}
"formation evaluation -- circulating conditioning": {n: 73, op_class: circulate, cause: detail}
"formation evaluation -- rft/fit": {n: 69, op_class: formation_evaluation, cause: detail}
"formation evaluation -- core": {n: 20, op_class: formation_evaluation, cause: detail}
"formation evaluation -- circulation samples": {n: 11, op_class: circulate, cause: detail}
"formation evaluation -- other": {n: 10, op_class: other, cause: detail}
"formation evaluation -- wait": {n: 5, op_class: wait, cause: detail}
# completion: 2944 rows, 9 codes
"completion -- bop/wellhead equipment": {n: 930, op_class: bop_wellhead, cause: detail}
"completion -- circulating conditioning": {n: 647, op_class: circulate, cause: detail}
"completion -- perforate": {n: 469, op_class: perforate, cause: detail}
"completion -- completion string": {n: 406, op_class: completion, cause: detail}
"completion -- other": {n: 298, op_class: other, cause: detail}
"completion -- test scsssv": {n: 71, op_class: completion, cause: detail}
"completion -- wire line": {n: 65, op_class: wireline, cause: detail}
"completion -- sand control": {n: 57, op_class: completion, cause: detail}
"completion -- stimulate": {n: 1, op_class: completion, cause: detail}
# workover: 2221 rows, 8 codes
"workover -- wire line": {n: 868, op_class: wireline, cause: detail}
"workover -- rig up/down": {n: 429, op_class: rig_up_down, cause: detail}
"workover -- perforate": {n: 347, op_class: perforate, cause: detail}
"workover -- other": {n: 326, op_class: other, cause: detail}
"workover -- bop/wellhead equipment": {n: 104, op_class: bop_wellhead, cause: detail}
"workover -- completion string": {n: 94, op_class: completion, cause: detail}
"workover -- test scsssv": {n: 28, op_class: completion, cause: detail}
"workover -- wait": {n: 25, op_class: wait, cause: detail}
# plug abandon: 4595 rows, 11 codes
"plug abandon -- other": {n: 2332, op_class: other, cause: detail}
"plug abandon -- cement plug": {n: 558, op_class: plug_abandon, cause: detail}
"plug abandon -- cut": {n: 421, op_class: plug_abandon, cause: detail}
"plug abandon -- trip": {n: 407, op_class: trip, cause: detail}
"plug abandon -- equipment recovery": {n: 248, op_class: plug_abandon, cause: detail}
"plug abandon -- mill": {n: 238, op_class: plug_abandon, cause: detail}
"plug abandon -- mechanical plug": {n: 156, op_class: plug_abandon, cause: detail}
"plug abandon -- perforate": {n: 113, op_class: perforate, cause: detail}
"plug abandon -- circulating conditioning": {n: 97, op_class: circulate, cause: detail}
"plug abandon -- wait": {n: 17, op_class: wait, cause: detail}
"plug abandon -- squeeze": {n: 8, op_class: plug_abandon, cause: detail}
# moving: 241 rows, 4 codes
"moving -- skid": {n: 166, op_class: rig_move, cause: detail}
"moving -- anchor": {n: 32, op_class: rig_move, cause: detail}
"moving -- transit": {n: 27, op_class: rig_move, cause: detail}
"moving -- position": {n: 16, op_class: rig_move, cause: detail}
# interruption: 3577 rows, 10 codes
"interruption -- other": {n: 1202, op_class: interruption, cause: detail}
"interruption -- repair": {n: 806, op_class: interruption, cause: equipment}
"interruption -- waiting on weather": {n: 445, op_class: interruption, cause: weather}
"interruption -- maintain": {n: 310, op_class: interruption, cause: equipment}
"interruption -- fish": {n: 246, op_class: interruption, cause: stuck_fishing}
"interruption -- wait": {n: 229, op_class: interruption, cause: waiting}
"interruption -- sidetrack": {n: 202, op_class: interruption, cause: sidetrack}
"interruption -- lost circulation": {n: 75, op_class: interruption, cause: lost_circulation}
"interruption -- rig up/down": {n: 33, op_class: interruption, cause: detail}
"interruption -- well control": {n: 29, op_class: interruption, cause: well_control}
# ----------------------------------------------------------------------------------------------------------------
# T2: NPT (two candidate definitions) and cause group, per activity
# ----------------------------------------------------------------------------------------------------------------
t2:
# Both definitions are produced as columns; the protocol picks one before any model run.
# a interruption_only : code_main == "interruption" (3,577 rows)
# b union : a OR state == "fail" OR stateDetailActivity != "success" (4,286 rows)
npt_definitions:
a: {name: interruption_only, n: 3577}
b: {name: union, n: 4286}
# state: ok 22,967, fail 480. Only `fail` is evidence of NPT.
state: {ok: {n: 22967, npt: false}, fail: {n: 480, npt: true}}
# stateDetailActivity -> cause group (used where the code names no cause).
cause_from_detail:
success: {n: 20802, cause: null} # no cause named -> `default_cause`
equipment failure: {n: 1975, cause: equipment}
operation failed: {n: 456, cause: operation_failed}
stuck equipment: {n: 109, cause: stuck_fishing}
circulation loss: {n: 92, cause: lost_circulation}
mud loss: {n: 12, cause: lost_circulation} # judgement: 12 rows; mud lost downhole or at surface is
# one loss class at this sample size
injury: {n: 1, cause: hse} # one row; reported, never a class of its own
# NPT row with neither a cause in the code nor in stateDetailActivity (interruption -- other with "success",
# state == fail with "success").
default_cause: unspecified
# judgement (precedence): for interruption rows the sub-code wins over stateDetailActivity, because the sub-code
# states what the lost time was booked to, while stateDetailActivity describes the outcome of the single row.
# The two name different groups in 192 rows: in 134 the detail is the generic "operation failed", in 22 it is
# "equipment failure" under a sidetrack, fish or weather code, and in 36 it is a specific downhole cause (well
# control + circulation loss 23, repair + mud loss 6, sidetrack + circulation loss 3 / mud loss 1 / stuck
# equipment 1, waiting on weather + circulation loss 2). Both candidates are kept as `cause_from_code` and
# `cause_from_detail`, with `cause_conflict`, so the protocol can reverse the order.
precedence: [code, detail, default]
cause_groups:
equipment: "rig or downhole equipment failure, repair and maintenance (interruption -- repair, --
maintain; stateDetailActivity equipment failure). judgement: `maintain` rows are mostly
repairs of the top drive and pipe-handling systems (163 of 310 carry equipment failure);
`cause_fine` keeps repair and maintain apart"
weather: "waiting on weather"
waiting: "waiting other than on weather (interruption -- wait)"
stuck_fishing: "stuck pipe or tool and fishing"
lost_circulation: "lost circulation and mud loss"
well_control: "well control (29 rows in 3 wellbores; flagged rare)"
sidetrack: "technical sidetrack booked as interruption (202 rows in 3 wellbores of well 15/9-19; whole
re-drilled intervals, including rows whose text is ordinary drilling)"
operation_failed: "operation failed, no more specific cause"
hse: "injury (1 row)"
unspecified: "NPT without a named cause"
# `cause_fine` = the interruption sub-code where the code names the cause (repair, maintain, fish, ...), else the
# stateDetailActivity value, else `unspecified`.
# Auxiliary flag, not an NPT definition: `wait_code_outside_interruption` marks the 79 rows whose sub-code is
# `wait` in a non-interruption group. The protocol may treat them as a third candidate.
# Masked model-input view (table t2_inputs): what a model may read for T2 and T3. These five columns never
# appear in it; volve_dia.labels.t2_inputs raises if one does.
masked_columns: [proprietaryCode, code_main, code_sub, state, stateDetailActivity]
# Activity columns of the view. `phase` (rig type: fixed / wire line) is not an activity code and is exposed as
# `rig_phase`; its NPT rate is reported in summary.json so the protocol can drop it.
input_activity_columns: [act_id, report_id, wellbore, seq, start_utc, end_utc, duration_h, md, phase, comments]
# Report columns of the view (text and header metadata). For T1 the hole-size columns (diaHole, mdDiaHoleStart)
# and the sizes named in the text are the label and must be masked by the model code as well.
# Left out on purpose, as protocol choices: daysAhead / daysBehind (schedule variance accumulates with NPT) and
# the equip_failures table (a structured near-label; its overlap with equipment NPT is in summary.json ->
# t2.equip_failures_table).
input_report_columns: [file_date, reportNo, sum24Hr, forecast24Hr, md, tvd, distDrill, diaHole, mdDiaHoleStart,
mdCsgLast, rigAlias_NPD_Name, operator, drillContractor]
# ----------------------------------------------------------------------------------------------------------------
# T3: trouble intervals in measured depth, per wellbore
# ----------------------------------------------------------------------------------------------------------------
t3:
# Depth of an activity = activities.md, one value per row: the depth of the string at the end of the activity,
# not a depth range and not necessarily the depth of the problem in the hole.
# Depth classes: `zero` (md == 0: string at surface, or depth not entered), `above_mudline` (0 < md < mud line),
# `in_hole` (md >= mud line). Only `in_hole` rows are located on the grid.
# Mud line of a wellbore = median of (waterDepth + elevKelly) over its reports with elevKelly > 0
# (145.9 m for the F wellbores, 145.0 m for 15/9-F-15 B, 106-110 m for 15/9-19).
grid_m: 10.0 # cell k covers [k * grid_m, (k + 1) * grid_m) m MD
# Cell universe of a wellbore: every cell from the mud line to the deepest in-hole activity depth or report md.
# A cell is positive under definition a (b) when at least one in-hole NPT activity under a (b) lies in it.
# Merge rule: positive cells of one wellbore whose indices differ by at most `merge_gap_cells` + 1 form one
# interval [k_first * grid_m, (k_last + 1) * grid_m). Time is not used: an interval collects every NPT activity
# at that depth, whenever it happened; `first_start_utc` gives the cut-off for pre-event features.
# judgement: gap 0 (touching cells only) adds no assumption about the cells in between; summary.json reports the
# interval counts for gaps 0, 1 and 2.
merge_gap_cells: 0
# Episodes (table t3_episodes) are the time view: maximal runs of NPT activities that follow each other in the
# activity sequence of a wellbore, with at most `episode_max_gap_h` hours between the end of one and the start of
# the next (a longer gap, e.g. a missing report, ends the episode).
episode_max_gap_h: 24.0
# `own_hole_top_md` of a wellbore = the smallest mdDiaHoleStart among its reports with a known diaHole. Cells
# above it belong to the hole shared with the parent wellbore (sidetracks) and are flagged `in_own_hole: false`.
# ----------------------------------------------------------------------------------------------------------------
# Text lexicon: analysis only, never a label source
# ----------------------------------------------------------------------------------------------------------------
# How often the free text names the label (not leakage: the text is the legitimate input; the paper reports the
# rates). Each entry is a list of Python regular expressions (joined with "|", case-insensitive), searched in
# activities.comments and, separately, in comments + sum24Hr of the report. Also computed without a lexicon: how
# often a comment contains its own sub-code literally (summary.json -> text.code_sub_literal).
text_lexicon:
npt: ['\bnpt\b', 'down ?time', 'interrupt', 'trouble ?sho', '\bfail', '\brepair', '\bwait', '\bwow\b',
'stuck', '\bfish', '\bleak', 'malfunction', '\blost\b', '\bloss']
weather: ['\bwow\b', 'wait\w* (on|for|due to) (the )?weather', '\bweather\b', '\bwind\b', '\bwaves?\b',
'\bheave\b']
waiting: ['\bwait', 'stand(ing|-| )?by\b', '\bstandby\b']
equipment: ['\brepair', 'trouble ?sho', '\bfail', '\bleak', 'malfunction', '\bdamage', '\bbroke\b',
'\bbroken\b', '\bfault', '\breplace', 'chang\w* out']
stuck_fishing: ['\bstuck\b', '\bfish', 'free ?point', 'over ?shot', '\bjarr?(ed|ing)?\b', '\bjunk\b']
lost_circulation: ['lost circulation', '\bloss(es)?\b', 'lost returns', 'no returns', '\blcm\b', '\blost \d']
well_control: ['well control', '\bkick\b', '\binflux\b', '\bkill(ed|ing)?\b', 'shut[- ]?in']
sidetrack: ['side ?track', 'kick(ed)? ?off', 'whipstock']
operation_failed: ['\bfail', 'no success', 'unsuccess', 'without success', 'not able', 'unable', '\bneg(ative)?\b',
'\battempt']

13
configs/ocr_hub.yaml Normal file
View File

@@ -0,0 +1,13 @@
# OCR of the Volve PDF pages run outside this repository (chandra, by a colleague) and exported from the internal
# Dataset Hub as COCO (one PNG per distinct page image + one annotations json). Download it into `dir` with the
# dataset-hub CLI; the hub URL, dataset id and API key live only in .env (see README). Read by volve_dia/ocr_hub.py.
dir: data/ocr_hub
prefilter: 30 # images re-scored by token F1 after the hashed TF-IDF cosine
top_k: 8 # text candidates per page passed to the image stage
thumb_dpi: 50 # PDF page rendered at 50 DPI ...
thumb_shrink: 2 # ... and the 200-DPI hub PNG shrunk by 2**2, so both are about 414 x 585 px
min_corr: 0.9 # grey-level correlation a page needs with its best candidate image to be matched
tie_eps: 0.01 # candidates within this of the best correlation are ties; the highest text F1 among them wins
fallback_top_k: 8 # a DDR page with no text candidate >= min_corr: best images by coarse correlation, re-scored
min_text_f1: 0.7 # a page with at least f1_min_tokens tokens in its text layer also needs this text F1 ...
f1_min_tokens: 50 # ... (shorter pages: footer-only second pages, where F1 over a few tokens says little)

250
configs/protocol_v1.yaml Normal file
View File

@@ -0,0 +1,250 @@
# Volve-DIA evaluation protocol v1 -- DRAFT, NOT LOCKED.
#
# This file is locked at gate G1 (M2, before the first model run) by writing its SHA-256 to protocol_v1.yaml.sha256.
# After the lock it is never edited and no threshold is relaxed: a change becomes protocol_v2 with a recorded
# deviation. Until the lock every item is a proposal that the label validation (M2) may still change; items under `open:`
# are undecided. docs/plan.md sections 4.2-4.7 and 6 give the reasoning; the label numbers quoted here are from
# outputs/labels/summary.json (configs/labels.yaml sha256 0b1f877f2f9c...) and outputs/t4/summary.json.
protocol: volve-dia
version: 1
status: draft # draft -> locked (G1)
drafted: 2026-11-17
# ----------------------------------------------------------------------------------------------------------------
# What the protocol is about: frozen inputs (hashes are filled in at the lock)
# ----------------------------------------------------------------------------------------------------------------
inputs:
data_manifest: {file: data_manifest/volve_dia.json, sha256: null}
labels_config: {file: configs/labels.yaml, sha256: null}
t4_templates: {file: configs/t4_templates.yaml, sha256: null}
label_tables: {dir: outputs/labels, summary_sha256: null}
t4_questions: {dir: outputs/t4, summary_sha256: null}
ground_truth: "DDR XML (scripts/02_parse_ddr.py) and WITSML (scripts/06_parse_witsml.py) only; HTML, PDF and OCR
text are model inputs at most, never labels or answers"
# ----------------------------------------------------------------------------------------------------------------
# Splits
# ----------------------------------------------------------------------------------------------------------------
splits:
# Evidence (17/11/2026, outputs/labels/analysis.md):
# * the 26 DDR wellbores belong to 11 wells; sidetracks of one well follow each other in time, 16 report days are
# shared by two wellbores of a well;
# * verbatim comments of >= 40 characters recur in a sibling wellbore in 0.30% of cases and in another well in
# 0.96%, so text duplication alone does not force a split by well;
# * but siblings share the slot, the upper hole and the formations at the same depths: 191 of the 844 positive
# T3 cells (definition a) lie above the wellbore's own hole top, i.e. in hole shared with the parent;
# * the two public Volve repositories with grouped splits (Anatoly5ms: 11 wells; DrillScribe: 23 nameWell) both
# keep sidetracks with their parent well.
# Decision: group by WELL; the split by wellbore is a sensitivity analysis for the main baselines only.
group: well # volve_dia.names.well_of
sensitivity_group: wellbore
# Decision (was open): leave-one-well-out. It needs no fold-assignment table (one less researcher choice), every
# well is predicted exactly once, and scores are computed on the pooled out-of-fold predictions, so the unequal
# fold sizes (15/9-19: 375 reports, 15/9-F-7: 39) do not weight the folds. GroupKFold(5) was the alternative; it
# does not help the rare classes either, because their concentration is a property of the wells (see below).
outer: leave_one_group_out # 11 folds on DDR-only tasks; on T3/T5 the wells with WITSML time logs
inner: {method: group_k_fold, n_splits: 5, group: well} # all tuning inside the training wells of a fold
scoring: pooled_out_of_fold # one prediction per item, from the fold that held its well out
rule: "nothing (hyperparameter, prompt, threshold, class merge, few-shot example) is chosen on a test well"
# Systems that are not trained per fold (prompted LLMs, retrieval pipelines) cannot tune inside a fold. Their
# prompts, few-shot examples and thresholds are developed only on two development wells, fixed here by a rule:
# the two wells with the fewest DDR reports. Every system, trained or not, is also scored on the other nine wells,
# which is the table where prompted and trained systems are compared.
development_wells: ["15/9-F-7", "15/9-F-9"] # 39 and 60 reports; T2 NPT (a) 54 + 161 rows; T4 54 + 102 questions
# ----------------------------------------------------------------------------------------------------------------
# Inputs a model may see (leakage control)
# ----------------------------------------------------------------------------------------------------------------
masking:
masked_fields: [proprietaryCode, code_main, code_sub, state, stateDetailActivity]
# Other report content that states the label outright is withheld from T2/T3 inputs as well.
withheld_for_t2_t3:
- equip_failures # names the failure; 67.6% of the 325 reports with rows have equipment NPT (b)
- daysAhead # schedule variance accumulates with NPT
- daysBehind
# rig_phase (fixed / wire line) is not an activity code; NPT (a) rate 15.6% vs 12.9%. Kept as an input.
input_view: "table t2_inputs (volve_dia.labels.t2_inputs raises if a masked column appears) plus the comments of
the previous and next activity of the same report"
modes:
masked: primary # results in the main tables
unmasked: leakage_ablation # same models with the codes in the input; reported side by side
t3_causality: "features only from activities, reports and WITSML samples that end before the start of the
predicted interval (t3_intervals.first_start_utc); checked by hand on a sample of windows"
t1_hole_size: "diaHole, diaPilot, mdDiaHoleStart, bit size and casing size are withheld whenever the section is
the target; sizes named in the text stay (they are the evidence a reader uses)"
# ----------------------------------------------------------------------------------------------------------------
# Class evaluability under the split by well (decided on label distributions only, never on model results)
# ----------------------------------------------------------------------------------------------------------------
class_evaluability:
# A class can be learned and tested across wells only if several wells hold it. Rule: a class is scored on its
# own only if at least `min_wells` wells hold at least `min_items_per_well` items of it in the scored label set.
# Otherwise it is merged as listed in `merges`, or dropped from scoring and its items reported separately.
min_items_per_well: 5
min_wells: 3
# Result of the rule on the current labels (recomputed on the frozen labels at G1; the lock records the final
# table). Concentration: sidetrack 100% in well 15/9-19; lost_circulation 87% in 15/9-19; well_control 79% in
# 15/9-F-15; section 6" and 9.875" only in 15/9-19.
preview:
t2_cause:
fail: [sidetrack, lost_circulation, well_control, hse]
# lost_circulation + well_control together still fail (>= 5 items in 2 wells: 15/9-19 73, 15/9-F-15 24), so
# both join stuck_fishing in the usual "hole problem" group; stuck_fishing (passes on its own) keeps a
# per-class F1 inside the merged class as a secondary number.
merges:
downhole: [stuck_fishing, lost_circulation, well_control]
sidetrack: "dropped from the cause target (202 rows, one well; most comments read as ordinary drilling); kept
as NPT in the binary target; the binary T2 score is also reported without these rows"
hse: "1 row (definition b only); dropped from the cause target"
t1_section:
fail: ["6", "9.875"]
merges: {"8.5_and_smaller": ["8.5", "6"]} # both map to phase `reservoir` in labels.yaml
drop: ["9.875"] # 4 drilling days, one well; reported, not scored
t1_op_class: {fail: [], note: "every non-interruption class holds >= 5 rows in >= 6 wells"}
class_merging:
# G1 rule (plan section 6): a class with kappa < 0.6 against the blind LLM raters (median over raters), or with
# fewer than 20 rated items,
# is not reported as its own class: it is merged into its parent group or dropped, and the merge is recorded here.
# Applied after class_evaluability.
min_kappa: 0.6
min_audit_items: 20
merges: [] # filled at G1
# ----------------------------------------------------------------------------------------------------------------
# Tasks, labels and metrics
# ----------------------------------------------------------------------------------------------------------------
tasks:
t1:
section:
unit: report_day
scope: drilling_day # 932 days; other_day (818: completion, P&A, workover) is not scored, because
# its section is the last one drilled, often years earlier
primary_subset: published # 672 drilling days with diaHole in the XML
secondary_subset: filled # 260 drilling days filled by labels.yaml t1.fill (ffill 255, bfill_leading 5);
# scored and reported separately, never pooled into the headline number
metrics: [macro_f1, per_class_f1]
op_class:
unit: activity
classes: "labels.yaml op_class without `interruption` (that class repeats T2 definition a)"
scope: "all activities that are not interruption rows (19,870)"
metrics: [macro_f1, per_class_f1]
secondary: op_group # 7 coarse groups, reported alongside
t2:
unit: activity
targets: [npt, cause_group]
npt_definition:
candidates: {a: interruption_only, b: union} # 3,577 vs 4,286 rows
# Pre-registered rule, decided on label validation, never on model results: the primary definition is the
# candidate with the higher Cohen's kappa against the blind LLM raters (median over raters); on a tie (|delta kappa| < 0.02) `a`.
choose_by: llm_rater_median_kappa
primary: null # filled at G1
# The 79 `wait` rows outside the interruption group are not NPT under a or b (1 of them is b through
# state=fail); they are not a third candidate, and their rate in the audit is reported.
cause_precedence: "code before stateDetailActivity (labels.yaml t2.precedence); the 192 conflicts are reported
and the cause score is also given with the order reversed"
metrics: [f1_npt, pr_auc_npt, macro_f1_cause, per_class_f1]
reference_baselines: [majority, comment_length_only, text_lexicon] # DrillScribe: length alone F1 0.772;
# lexicon: recall 0.33, precision 0.51
t3:
unit: md_bin # 10 m grid, labels.yaml t3
wellbores: with_witsml # wellbores with DDR and WITSML time logs (outputs/witsml)
# Only half of the NPT rows can be placed in depth (md == 0 in 9,116 of 23,447 rows): (a) 50.3% of NPT rows,
# 44.6% of NPT hours. T3 therefore scores where trouble was recorded in depth, not all trouble.
cell_universe: "own hole: from the wellbore's own hole top (smallest mdDiaHoleStart) to its deepest in-hole
depth; cells above it (shared with the parent) are reported separately, not scored"
metrics: [interval_iou, pr_auc_bin]
t4:
unit: question
answers: sql # outputs/t4; pandas and raw-XML re-implementations agree on 1,662 / 1,662
questions: {total: 1662, answerable: 1638, unanswerable: 24}
metrics: [answer_accuracy_within_tolerance, citation_precision, citation_recall, fabricated_number_rate,
wrong_wellbore_rate, abstention_on_unanswerable]
averaging: "macro over the five families (lookup, aggregation, temporal_event, comparison, multi_hop) as the
headline; micro and per-template numbers alongside"
citation_level: "report level (cited report_id) for every question; row level only for the 1,493 questions
with at most 50 evidence rows (169 have more)"
tolerance: "per template in configs/t4_templates.yaml"
input_modalities: "XML/SQL, HTML text, OCR text. The modality comparison (RQ5) uses only the 1,447 questions
whose answer is printed in the render (printed_in_render); the 215 XML-only questions are
scored for XML/SQL systems and reported apart"
scopes: "pair questions (92) compare wellbores of one well and go with that well; the 10 field questions are
scored on their own line and enter no per-well number"
llm_judge: "only for free-text parts and only if gate G3 passes"
# ----------------------------------------------------------------------------------------------------------------
# Statistics
# ----------------------------------------------------------------------------------------------------------------
statistics:
seeds: [0, 1, 2] # at least 3 for every stochastic model; deterministic models run once
ci: {method: cluster_bootstrap, cluster: well, resamples: 2000, level: 0.95, seed: 20261117}
comparisons: "paired on the same folds; paired cluster bootstrap of the score difference"
report_all: "every run is reported, failures included"
# ----------------------------------------------------------------------------------------------------------------
# Label validation (plan section 4.4)
# ----------------------------------------------------------------------------------------------------------------
validation:
trial_audit:
rows: 100
when: M1
purpose: "pipeline check and a first agreement estimate; not used for G1"
tool: "scripts/09_audit.py (sample: seed 20261117, zones a 35 / b_only 15 / none 50, stratified by class within
the zone, spread over wells; score: kappa unweighted and weighted to the population)"
# Decision of 17/11/2026 (plan section 12 item 20): no human rater is available, so label validation uses blind
# LLM raters, not an author audit. The claim is "validated by blind LLM raters and cross-checks", never "audited
# by the author" or "expert-labelled". Each rater is a different model family (Sonnet, Opus, Haiku in the trial;
# M2 adds at least one open-weight model), sees only the masked view (no code, no label, no key), rates every
# row alone with no keyword rules, and is never shown another rater's output. Reported: kappa of each rater
# against the code labels, kappa between raters (Fleiss and pairwise), and the disagreements. A human rater, if
# one becomes available, is added as a further rater and reported on its own line.
llm_raters:
trial: {rows: 100, when: M1, models: [sonnet, opus, haiku], files: "outputs/audit/trial_100/RATINGS_llm_*.csv"}
audit_1: {rows: 300, when: M2, strata: [zone, cause_group, well], masked: true, min_raters: 3,
second_pass_after_days: 14, note: "second pass = same model rerun, for rater self-consistency"}
decision_statistic: median_over_raters
caveat: "LLM raters share training data and conventions with the LLM baselines of M3-M4; agreement with the
code labels is evidence of consistency with a text reading, not of expert correctness"
# Third-party label sets (docs/literature_notes.md, 17/11/2026): none is an independent drilling-NPT label set.
# DrillScribe episodes are runs of stateDetailActivity (rebuilt 1,758/1,758 from our activities), Bassey 2026
# labels daily production data, the OMAE 2024 stuck-pipe set has no label column. They are used as follows and
# never reported as independent agreement. The blind LLM raters and the cross-checks together carry the
# label-validity claim; the absence of a human rater is stated as a limitation.
cross_checks:
drillscribe: "parser cross-check (episodes rebuilt from the XML) and a T2 reference number; not a label source"
anatoly5ms_text_rules: "comment regex rules re-implemented with attribution; agreement with T3 reported as a
partly code-independent check"
omae_2024_stuck_pipe: "three case-level checks (F-4, F-9 A, F-1) of what the DDR records at the incident"
bassey_2026: "not used for T2/T3 (production events); cited as a precedent for rule-built labels"
kappa: cohen
# ----------------------------------------------------------------------------------------------------------------
# To do before the lock (M2)
# ----------------------------------------------------------------------------------------------------------------
before_lock:
- "run the blind LLM-rater validation (300 rows, >= 3 raters) and its second pass; fill npt_definition.primary and class_merging.merges"
- "recompute class_evaluability on the frozen labels and copy the final table here"
- "fill the sha256 fields of `inputs`"
- "fix the T3/T5 well list from outputs/witsml (wells with time logs) and check that every LOGO fold has
positives in its training wells"
# ----------------------------------------------------------------------------------------------------------------
# Gates (plan section 6); thresholds fixed at the lock, only dates may move
# ----------------------------------------------------------------------------------------------------------------
gates:
g1: "protocol locked (sha256) before any model run; class_evaluability and class_merging applied"
g2: "all baselines and the masked/unmasked ablation on every task, >= 3 seeds, CI by well; results reported
whatever their direction"
g3: {llm_judge_min_kappa: 0.6, else: "T4 reports automatic metrics only"}
g4: "the release package reruns from scratch; third-party label licences checked"
# ----------------------------------------------------------------------------------------------------------------
# WITSML feature rules (decision of 17/11/2026, plan section 12 item 21)
# ----------------------------------------------------------------------------------------------------------------
witsml_features:
# Tables keep the published values (provenance); the feature stage treats these as missing. Evidence:
# outputs/witsml/log_suspects.parquet (-999 on MWD_* channels 224,841 values; 99999 on ANNVEL_MMIN 279,676 of
# 279,866; 9999 on time-counter channels; huge values on RETI, SPPA, TQA).
treat_as_missing: {values: [-999, -99999, 99999, 9999], abs_greater_than: 1.0e15}
depth_source: drill_depth # view over GenTime Depth/BITDEP and Schlumberger DMEA/DBTM; never time_log_dedup Depth
formation_labels: Well_picks_Volve_v1.dat # DDR stratInfo only as a cross-check

1225
configs/t4_templates.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -6,10 +6,17 @@
"Reports",
"WITSML Realtime drilling data"
],
"created_utc": "2026-10-29T09:34:27+00:00",
"n_files": 25570,
"total_bytes": 19935170886,
"files_outside_subtrees": [
"Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat"
],
"created_utc": "2026-11-17T02:25:46+00:00",
"n_files": 25571,
"total_bytes": 19935245434,
"files": {
"Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat": {
"size_bytes": 74548,
"sha256": "1c132bba09555915b62e23dc4475f790a304856d369d9d26cc76466cf7b77d3a"
},
"Reports/Discovery_report.pdf": {
"size_bytes": 182392824,
"sha256": "0b5eea5e71179e955282bce379f8fea977dbe50080addf2a6abc62537ba8942a"

185
docs/literature_notes.md Normal file
View File

@@ -0,0 +1,185 @@
# Ghi chú tài liệu và bộ nhãn bên thứ ba cho Volve-DIA
Ngày lập: **17/11/2026**. Phạm vi: các công trình nêu ở `plan.md` mục 2.2, 4.4, 9, 11 và một lượt quét novelty 2025–2026. BibTeX: [references.bib](references.bib).
Nhãn mức xác minh dùng trong tài liệu này:
- **[TV]** đọc toàn văn (PDF ở `docs/lit_*.pdf`, không đưa lên git), kèm trang hoặc mục.
- **[TT]** chỉ đọc tóm tắt do nhà xuất bản nộp cho Crossref, DataCite hoặc Europe PMC.
- **[DL]** kiểm trực tiếp trên dữ liệu hoặc repo đã tải về `data/third_party/` (không đưa lên git), đối chiếu với `outputs/ddr/*.parquet`.
- **[CXM]** chưa xác minh được.
Mọi dữ liệu tải về chỉ được đọc như dữ liệu; không chạy mã nào của bên thứ ba. Script đối chiếu: `data/third_party/_volve_dia_checks/` (`overlap.py`, `bassey2.py`, `tspp_check.py`).
---
## 1. Tóm tắt các phát hiện chính
1. **Không bộ nào trong ba "bộ nhãn độc lập" của kế hoạch (Bassey 2026, OMAE 2024, DrillScribe) là bộ nhãn NPT khoan độc lập.**
- Bassey 2026 gán nhãn trên **dữ liệu khai thác theo ngày**, không phải WITSML khoan [TV].
- DrillScribe lấy nhãn từ chính trường `stateDetailActivity` của DDR; dựng lại từ bảng activity của ta khớp 1.758/1.758 episode [DL].
- Bộ TSPP (OMAE 2024) chỉ có 3 sự cố kẹt cần trên 3 wellbore, không có cột nhãn, không có giấy phép; DDR không ghi kẹt cần ở cả ba thời điểm [TV, DL].
2. **Số liệu PetroAgents trong kế hoạch khớp với toàn văn** [TV, sau khi người dùng tải PDF `docs/lit_petroagents.pdf` ngày 17/11/2026, 33 trang]. Đơn vị là **well-day** (1.750 ví dụ), mẫu mỗi seed chỉ 60 ví dụ, và phép cắt "lộ mã" 0,355 → 0,431 chỉ trên **30 ví dụ**. Chưa có bản tạp chí (Crossref, 17/11/2026).
3. **"53% → 4%" của repo Anatoly5ms không phải độ chính xác.** Đó là tỷ lệ khoảng dương có đặc trưng dung dịch đo sau khi sự cố bắt đầu, trước và sau khi sửa [DL].
4. **Hai đối thủ mới ở ADIPEC (2/11/2026)** đánh giá định lượng hỏi đáp và agent trên DDR Volve: SPE-236554-MS và SPE-235330-MS [TT]. Cả hai là bài hội nghị; chưa thấy bài tạp chí nào.
5. **Trích dẫn cần sửa trong kế hoạch:** OMAE2024-128386 và arXiv 2503.07440 là hai bài khác nhau; DOI của bài EAGE không phân giải được.
---
## 2. Từng công trình
### 2.1 PetroAgents (Lu, 2026)
- **Thư mục:** Lu R. *PetroAgents: A Multi-Agent, Multi-Modal Large-Language-Model Framework for Integrated Upstream Petroleum Asset Reasoning, Benchmarked on the Equinor Volve Open Dataset.* Preprints.org, đăng 18/6/2026, DOI 10.20944/preprints202606.1385.v1, giấy phép CC BY 4.0 [TT, Crossref].
- **Tình trạng:** đã đọc toàn văn [TV] (người dùng tải bằng trình duyệt vì preprints.org chặn truy cập tự động). Các mục dưới đây đã đối chiếu với toàn văn ở mục 5.1, 5.4, 4.3 và Bảng 7.
- **Điều toàn văn cho biết thêm [TV]:** (i) nhãn là lớp NPT **theo well-day** (bảy lớp: none 683, equipment_failure 646, other_interruption 189, weather 122, stuck 91, circulation_loss 19, instability 0) lấy từ `stateDetailActivity` và `proprietaryCode`; (ii) mỗi seed lấy mẫu phân tầng 60 ví dụ, ba seed 42–44; (iii) split "wellbore-stratified, date-locked", họ F-11 giữ các sub-wellbore **tách riêng**, tức nhóm theo wellbore, ngược với quyết định nhóm theo giếng của Volve-DIA; (iv) so sánh multi-agent với single-LLM trên tập có WITSML: +0,048 (p = 0,22) và +0,037 (p = 0,12), không đạt α = 0,05; trên tập mọi wellbore khác biệt gần 0 (p = 0,96); (v) tác giả tự nói không có RAG, không chạy B2, và các kết luận chỉ là hướng; (vi) bài còn một nhiệm vụ TOPS-PICK dùng đúng file `Well_picks_Volve_v1.dat` (35 wellbore, 409 pick, giữ riêng 7 wellbore) nhưng chưa báo kết quả.
- **Bản tạp chí:** không có. Crossref chỉ có bản v1; cùng tác giả còn TADI (10.20944/preprints202604.1820.v1), UpstreamBench (10.20944/preprints202606.1410.v2) và một bài khảo sát, đều là preprint [TT].
- **Nội dung [TT]:** kiến trúc đa agent theo bảy chức năng nhận thức, bốn chức năng được cài và đánh giá, ba chức năng chỉ là thiết kế. "Volve Bench" gồm sáu nhiệm vụ trên 26 wellbore, 1.759 DDR, 56 triệu dòng WITSML. Bài chỉ báo hai lát kết quả: DRILL-NPT (3 seed, mẫu phân tầng từ 1.750 ví dụ) và 12 câu hỏi DISCOVERY-QA trên ba trang. Toàn bộ LLM là open-weight chạy cục bộ.
- **Đối chiếu số liệu với kế hoạch:**
| Phát biểu trong `plan.md` | Trong tóm tắt | Kết luận |
| --- | --- | --- |
| DRILL-NPT macro-F1 ≈ 0,46 | 0,464 ± 0,012 trên mẫu mọi wellbore; 0,442 ± 0,019 trên tập con có WITSML (vote bốn họ model) | Đúng [TT]. Nên ghi cả hai số |
| Multi-agent hơn single-LLM +0,048, p = 0,22, 3 seed | +0,048 macro-F1 trên **tập con có WITSML**, kiểm định cặp không có ý nghĩa ở 3 seed (p = 0,22) | Đúng [TT] |
| Lộ mã nâng baseline 0,355 → 0,431 | Lộ `state_detail` và `proprietary_code` nâng B1 từ 0,355 lên 0,431 macro-F1, cùng tập con | Đúng [TT] |
| Volve Bench 6 nhiệm vụ | Sáu nhiệm vụ | Đúng [TT] |
| "Nhãn sinh từ chính mã DDR" | Tóm tắt chỉ nói một phần DRILL-NPT là rò rỉ mã nhãn | [CXM]: cần toàn văn |
| Chưa peer review | Preprint | Đúng [TT] |
- **Rò rỉ:** tác giả tự đo bằng ablation che bằng chứng [TT]. Cách chia train/test, số lớp, cỡ mẫu mỗi seed: [CXM].
- **Volve-DIA khác ở đâu:** che mã ở input là chế độ chính, split theo nhóm giếng, nhãn có bảng ánh xạ công khai và audit mù, CI bootstrap theo wellbore. Không đặt số của hai bên vào cùng bảng như cùng protocol (plan mục 10).
### 2.2 Bassey, Bassey và Fakiyesi (2026)
- **Thư mục:** *Grounded Well-Condition Anomaly Detection on the Volve Field: Constructed Labels, a Baseline, and a Dual-Head Model.* arXiv 2608.05685 v2 (12/8/2026), 16 trang. PDF: `docs/lit_bassey2026.pdf` [TV].
- **Dữ liệu [TV, mục 3, tr. 4–5]:** chỉ dùng sheet "Daily Production Data" của `Volve_production_data.xlsx` (15.634 dòng giếng-ngày, 9/2007–12/2016) và bản PUD trong `Volve_Reports.zip`. Giữ 6 giếng khai thác, 9.143 dòng. **Không dùng WITSML, không dùng DDR.**
- **Nhãn [TV, mục 4, tr. 5–7]:** luật ngưỡng đề xuất ứng viên; ứng viên chỉ thành nhãn khi PUD mô tả cơ chế tương ứng. 236 sự kiện: shut_in 88, restart_transient 79, gaslift_instability 59, water_breakthrough 5, productivity_loss 5 (Bảng 1). Tác giả nêu rõ nhãn là nhãn dựng, không phải sự cố được nhà điều hành xác nhận, và có tính vòng lặp vì luật đọc cùng telemetry với model (mục 4.4).
- **Kết quả [TV]:** Isolation Forest không thấy nhãn: ROC-AUC 0,825, PR-AUC 0,379 trên 5 giếng, 7.692 giếng-ngày (mục 6.5, tr. 9). Model hai đầu khoảng 4.000 tham số, leave-one-well-out, 1.141 cửa sổ 60 ngày chồng nhau 88%: presence AUC 0,819–0,939, sai số onset 14–17 ngày, type accuracy 0,511–0,794 (Bảng 2, tr. 12).
- **Rò rỉ:** split giữ nguyên giếng (mục 7.3); chuẩn hóa theo giếng dùng toàn bộ lịch sử giếng đó.
- **Giấy phép:** CC BY-NC-SA 4.0, nêu trong bài (mục 9) và trên thẻ Hugging Face [TV, DL]. Không phát hành lại file gốc của Equinor.
- **Sai lệch so với kế hoạch:** `plan.md` mục 2.2 ghi "nhãn bất thường WITSML". **Sai.** Đây là nhãn sự kiện khai thác theo ngày; không dùng được để kiểm định nhãn T2 hay T3.
- **Volve-DIA dùng thế nào:** chỉ trích làm tiền lệ cho cách làm "nhãn dựng bằng luật, có provenance từng nhãn, không có đội chuyên gia, nêu thẳng giới hạn". Không đưa vào lớp kiểm định nhãn thứ hai.
### 2.3 Bài EAGE 2026 (10.3997/2214-4609.2026101276)
- **Thư mục:** *From Field Logs to Actionable Insights: A Multi-Agent LLM Approach for Factual Summarization of Drilling Operations*, 87th EAGE Annual Conference & Exhibition, 6/2026 [tiêu đề và hội nghị lấy từ đoạn trích tìm kiếm của trang EarthDoc]. **Tác giả: [CXM].**
- **Tình trạng:** trang EarthDoc trả 403; DOI không phân giải tại doi.org (404) và không có trong Crossref ngày 17/11/2026. Trích dẫn bằng URL EarthDoc cho đến khi DOI hoạt động.
- **Nội dung [TT, qua đoạn trích tìm kiếm]:** quy trình đa agent tóm tắt tham số khoan có cấu trúc và báo cáo ngày thành điểm nổi bật, điểm yếu, bài học; có mô-đun kiểm chứng với log gốc và một agent chấm điểm. Bài nói đa agent tốt hơn một agent. Dữ liệu, metric, con số: [CXM]; không có dấu hiệu dùng Volve.
- **Quan hệ với Volve-DIA:** gần với phần văn bản của T4 nhưng là tóm tắt, không phải benchmark công khai. Không trùng.
### 2.4 OTC-36422-MS (Idrus và cộng sự, 2026)
- **Thư mục:** Idrus S. S. và 10 đồng tác giả. *Cognitive Drilling AI: Transforming Activity Logs into Actionable Insights.* Offshore Technology Conference Asia, 3/2026, DOI 10.4043/36422-MS. Toàn văn trả phí; chỉ đọc tóm tắt [TT].
- **Nội dung [TT]:** DDR do giám sát khoan nhập tay; hệ thống có sẵn mã hoạt động và mã phase nhưng mức chi tiết và cách chọn mã khác nhau giữa các giám sát, nên không thể chỉ dựa vào mã để phân tích thời gian. Hệ thống phân loại hơn 482 hoạt động, áp cho hơn một nghìn giếng, độ chính xác 80–90%, giảm thời gian xử lý từ 10 ngày xuống 10–15 phút mỗi giếng. Dữ liệu nội bộ.
- **Đối chiếu với kế hoạch:** phát biểu "mã hoạt động không nhất quán giữa supervisor" (plan mục 4.4, 9) **được tóm tắt hậu thuẫn** [TT]. Tóm tắt không đưa con số đo mức không nhất quán; không trích như một phép đo.
### 2.5 Bộ dữ liệu TSPP: OMAE2024-128386 và arXiv 2503.07440
Kế hoạch gộp hai bài làm một. Thực tế:
| | OMAE2024-128386 | arXiv 2503.07440 |
| --- | --- | --- |
| Tiêu đề | *Development of Time Series Drilling Datasets for Stuck Pipe Prediction Using Volve Field Data* | *Early signs of stuck pipe detection based on Crossformer* |
| Tác giả | Cao B., Song Y., Xu F., Peng F. | Cao B., Song Y., Yang J., Li L. |
| Nơi đăng | ASME OMAE 2024, Volume 8, DOI 10.1115/OMAE2024-128386 | arXiv, 10/3/2025, 33 trang |
| Đã đọc | Tóm tắt [TT]; toàn văn trả phí | Toàn văn [TV], `docs/lit_cao2025_crossformer.pdf` |
| Vai trò | Bài mô tả bộ dữ liệu | Bài phương pháp dùng bộ dữ liệu đó |
- **Dữ liệu [TV, mục 2, Bảng 1, tr. 8; DL]:** sáu file CSV từ log thời gian WITSML, nội suy về bước 4 giây, 10–11 kênh (hookload, hole depth, WOB, block position, RPM, torque, bit depth, SPP, flow in, ROP).
- **Nhãn [TV]:** file **không có cột nhãn**. TSPP1 và hai biến thể là khoan bình thường. Ba sự cố chỉ được nêu trong bài: TSPP2 kẹt lúc 16:59 (tr. 22–23), TSPP3 kẹt lúc 7:28 (tr. 26), TSPP4 kẹt đột ngột không có dấu hiệu sớm, không nêu giờ (tr. 29). Đoạn bất thường "không được giải quyết trong thời gian dài" đã bị cắt bằng tay (mục 2.2, tr. 7). Múi giờ của mốc thời gian: [CXM].
- **Phương pháp và kết quả [TV]:** Crossformer huấn luyện trên dữ liệu bình thường, chia 0,7:0,1:0,2 theo thời gian trong cùng chuỗi (tr. 9); sai số tái dựng tương đối là rủi ro. Cảnh báo sớm 4,67 phút ở TSPP2 (Hình 7) và 23,60 phút ở TSPP3 (Hình 8). Không có độ chính xác tổng hợp; chỉ là hai nghiên cứu tình huống.
- **Đối chiếu với DDR của ta [DL]:** trong cả ba cửa sổ (nới ±3 giờ), DDR không có dòng nào `stateDetailActivity = stuck equipment` và không có comment nào nói kẹt cần.
- TSPP2 (15/9-F-4, 23/10/2007): DDR ghi khoan 12 1/4" từ 1.365 m đến 1.584 m, sau đó dừng để sửa IBOP của top drive (`equipment failure`).
- TSPP3 (15/9-F-9 A, 3–4/7/2009): khoan 12 1/4" đến 997 m, kéo cần với quá kéo tối đa 15 tấn, mã `success`.
- TSPP4 (15/9-F-1, 1/12/2007): khoan đoạn 36" đến 226 m, mã `success`; hôm sau ghi quá kéo 10 MT tại 215 m.
- 109 dòng `stuck equipment` của DDR nằm ở wellbore và ngày khác (79 dòng ở 15/9-F-4, 18–24/2/2008).
- **Giấy phép [DL]:** repo `promiseeee/Time-series-stuck-pipe-prediction` (commit 1297d8b, 23/10/2023) **không có file LICENSE**. Dữ liệu là dẫn xuất của Volve nên vẫn chịu CC BY-NC-SA 4.0 của nguồn, nhưng tác giả không cấp phép rõ. Không phát hành lại file; chỉ dẫn URL và commit.
- **Volve-DIA dùng thế nào:** ba tình huống đối chiếu định tính giữa tín hiệu WITSML và DDR, và là ví dụ rằng "sự cố" suy từ tín hiệu có thể không được DDR ghi nhận. Không tính độ khớp thống kê từ n = 3.
### 2.6 DrillScribe (Paul, 2026)
- **Nguồn:** repo GitHub `chinmoypaul8897/drillscribe`, commit 0abca00 (7/8/2026), bài dự thi sinh viên; **không phải bài báo** [DL].
- **Dữ liệu [DL]:** bản Parquet của DDR Volve trên Hugging Face (`bengsoon/volve_daily_drilling_report`). `build_dataset.py` sắp activity theo (`nameWell`, `dTimStart`) và gộp các dòng liên tiếp cùng `stateDetailActivity` thành episode. Kết quả: 1.758 episode, 23 giá trị `nameWell`, 23.447 dòng, 477.796 từ. Ánh xạ lớp: success → normal (872); equipment failure (742); operation failed (107); circulation loss, mud loss, stuck equipment → hole_problem (36); injury → hse (1). 886 episode NPT.
- **Kết quả [DL, README và `data/RESULTS.json`]:** phân loại nhị phân NPT theo episode, chỉ dùng văn bản, GroupKFold 5 phần theo `nameWell`: F1 0,866, ROC-AUC 0,941; baseline chỉ dùng độ dài: 0,772 và 0,838; lớp đa số: 0,670 và 0,500. Chuyển sang 200 báo cáo BSEE (Vịnh Mexico) chấm tay: AUC 0,691, sát baseline từ khóa 0,678; thêm 60 ngày gán nhãn tại chỗ lên 0,785.
- **Rò rỉ:** mã không vào input; split theo `nameWell`. Nhãn 200 mẫu BSEE do một người không phải kỹ sư khoan chấm (README).
- **Độ độc lập [DL]:** dựng lại episode từ `outputs/ddr/activities.parquet` theo đúng quy tắc trên cho 1.758 episode; khớp 1.758/1.758 theo khóa (`nameWell`, nhãn gốc, thời điểm bắt đầu, số dòng). **Nhãn DrillScribe là một phép biến đổi của chính trường mà T2 dùng; không độc lập.**
- **Giấy phép [DL]:** mã MIT. File LICENSE và README ghi DDR Volve là "CC-BY-4.0", theo thẻ của bản mirror Hugging Face; `license.txt` đi kèm dữ liệu Volve ghi CC BY-NC-SA 4.0. `data/episodes.csv` chứa nguyên văn comment DDR, nên chịu giấy phép của Volve. Không sao chép file; ta sinh lại được đúng nội dung từ XML.
- **Volve-DIA dùng thế nào:**
1. kiểm chéo parser: hai đường xử lý khác nhau (XML của ta; mirror Hugging Face của họ) cho cùng 23.447 dòng và cùng 1.758 episode;
2. số tham chiếu cho T2 nhị phân theo episode, kèm baseline độ dài; Volve-DIA nên có baseline độ dài tương tự;
3. bằng chứng rằng model văn bản huấn luyện trên Volve gần như không chuyển giao sang nhà điều hành khác, liên quan tới bước chuyển sang dữ liệu nội bộ.
### 2.7 Repo Anatoly5ms (Grigorovich, 2026)
- **Nguồn:** `Anatoly5ms/drilling_complication_prognostication`, commit a0e16ed (19/10/2026), MIT; **không phải bài báo** [DL].
- **Nhiệm vụ [DL, README]:** dự báo rủi ro sự cố (mất dung dịch, kick, kẹt cần, mất ổn định thành giếng) cho từng **khoảng 10 m MD**, từ DDR Volve (cùng mirror Hugging Face; 1.759 báo cáo, 26 wellbore, 11 giếng). Rất gần T3.
- **Nhãn [DL, `config/config.yaml`]:** mã hoạt động cộng regex trên comment, có mẫu mạnh, mẫu yếu và mẫu loại trừ; mã well-control chỉ tính khi có văn bản xác nhận; kẹt cần và mất ổn định chỉ dựa vào văn bản. Sự kiện trong khoảng đã khoan: mất dung dịch 47, kẹt cần 44, mất ổn định 110; kick dưới ngưỡng huấn luyện. **Repo không kèm file nhãn hay dữ liệu.**
- **Rò rỉ [DL, README mục "Leakage control"]:** bản đầu lấy đặc trưng tại lần đo cuối trước khi choòng rời khoảng. Tỷ lệ khoảng dương có đặc trưng dung dịch đo **sau khi mất dung dịch bắt đầu**: 53% trước khi sửa, 4% sau khi sửa. Sửa bằng cách lấy đặc trưng tại lúc choòng vào khoảng và không gán nhãn cho khoảng nằm dưới độ sâu sự kiện. Dấu hiệu rò rỉ: hệ số hồi quy logistic của fracture margin đổi dấu sau khi sửa.
- **Split [DL]:** theo **giếng**, không theo wellbore, vì các sidetrack dùng chung đoạn trên. Giữ riêng 3 giếng thử (F-11, F-14, F-5).
- **Kết quả [DL, README]:** mất dung dịch, 3 giếng thử, 1.503 khoảng, 14 dương: ensemble PR-AUC 0,048 [0,023; 0,111], ROC-AUC 0,879 [0,836; 0,922]; heuristic 2019: 0,022 và 0,671. Tỷ lệ dương khoảng 1%.
- **Volve-DIA dùng thế nào:**
1. sửa câu trong plan mục 9: 53% → 4% là tỷ lệ khoảng dương bị nhiễm đặc trưng sau sự kiện, không phải điểm số;
2. bộ luật regex (MIT) là nguồn nhãn **dựa trên văn bản**, độc lập một phần với `stateDetailActivity`; có thể cài lại trong `volve_dia` (giữ ghi công MIT) để đối chiếu với nhãn T3;
3. tiền lệ cho split theo giếng (plan mục 4.5) và cho quy tắc "đặc trưng tại lúc vào khoảng";
4. số tham chiếu cho T3 mất dung dịch.
### 2.8 Bodén và cộng sự, SPE-228117-MS (2025)
- **Thư mục:** Boden J. và 7 đồng tác giả. *Building an Intelligent Research Assistant – RAG Isn't All You Need.* SPE ATCE, 10/2025, DOI 10.2118/228117-MS [TT].
- **Đối chiếu:** "75 người dùng thử" đúng: 75 tình nguyện viên từ 30 nước, bài tập lập kế hoạch giếng trên khoảng 30.000 tài liệu Volve; độ chính xác tăng 152%, thời gian giảm 86% so với RAG chuẩn; vòng sau 86% so với 27% câu đúng [TT]. Bộ câu hỏi có công bố hay không: [CXM].
---
## 3. Bảng các bộ nhãn bên thứ ba
Vị trí: `data/third_party/<tên>/` (gitignore). 26 wellbore DDR của ta lấy từ `outputs/ddr/reports.parquet`; tên được chuẩn hóa bằng `volve_dia.names.canonical`.
| Bộ | Gán nhãn gì | Định dạng, kích thước | Wellbore và thời gian | Trùng với DDR của ta [DL] | Khóa ghép | Giấy phép và phát hành lại |
| --- | --- | --- | --- | --- | --- | --- |
| **DrillScribe** `drillscribe/` (4,7 MB) | Episode NPT từ `stateDetailActivity`, 5 lớp | `data/episodes.csv`, 1.758 dòng, 2,9 MB; 200 nhãn tay BSEE (không phải Volve) | 23 `nameWell`, 9/1992–10/2016 | 26/26 wellbore (BT2, ST2, T2 nằm dưới `nameWell` của giếng mẹ); 23.447/23.447 dòng activity; 1.758/1.758 episode dựng lại được | (`nameWell`, `dTimStart` nhỏ nhất theo UTC, số dòng); có `md_min`, `md_max` | Mã MIT; văn bản DDR chịu CC BY-NC-SA 4.0 của Volve. Không sao chép; sinh lại từ XML |
| **Anatoly5ms** `anatoly5ms_drilling_complication/` (0,4 MB) | Sự cố theo khoảng 10 m: mất dung dịch, kick, kẹt cần, mất ổn định | Chỉ có mã và `config/config.yaml`; **không có file nhãn** | 26 wellbore, 11 giếng (theo README) | Không tính được vì không có nhãn; giếng thử F-11, F-14, F-5 | (wellbore, khoảng 10 m MD, `dTimStart` của sự kiện, độ sâu đáy giếng) | MIT. Được cài lại luật, giữ ghi công |
| **TSPP** `tspp_stuck_pipe_cao2024/` (19 MB) | 3 sự cố kẹt cần và 1 đoạn bình thường; nhãn chỉ nằm trong bài | 6 CSV, 4 giây, 5.633–59.163 dòng | F-12 (6–8/7/2007), F-4 (23/10/2007), F-9 A (3–4/7/2009), F-1 (1/12/2007) | 4/4 wellbore; số dòng activity trong cửa sổ ±3 giờ: 25, 9, 14, 15; **0 dòng `stuck equipment`** | (wellbore, mốc thời gian, hole depth MD) với `start_utc`, `end_utc`, `md`; múi giờ [CXM] | Không có giấy phép. Không phát hành lại; dẫn URL và commit |
| **Bassey 2026** `bassey2026_volve_anomaly/` (2,6 MB) | 236 sự kiện khai thác, 5 loại | `volve_grounded_events.csv`, `volve_events_provenance.csv`, `volve_well_daily.csv` | 6 giếng khai thác, 2/2008–9/2016 | 6/6 giếng có DDR; 33/236 sự kiện trùng ngày với 214 báo cáo DDR cùng giếng, chủ yếu P&A, workover, hoàn thiện (4.167 dòng; không có lớp sự cố giếng) | (giếng, ngày) với (`well_of(wellbore)`, `file_date`) | CC BY-NC-SA 4.0, tương thích; nhưng không liên quan tới nhãn khoan |
Ghi chú cho Bassey: ghép theo tên wellbore chính xác cho 29/236 sự kiện và 193 báo cáo, nhưng tên "15/9-F-11" trong dữ liệu khai thác ứng với giếng, không phải wellbore pilot cùng tên trong DDR; nên ghép theo giếng.
---
## 4. Quét novelty 2025–2026
Nguồn: arXiv API, Crossref (gồm tiền tố SPE, OTC, IPTC, EAGE), OpenAlex, Europe PMC, tìm kiếm web; ngày 17/11/2026. Semantic Scholar trả 429 nên không dùng. Scopus chưa quét. Mọi mục dưới đây là [TT].
**Chưa có trong `plan.md` mục 2.2, liên quan trực tiếp:**
| Công trình | Nội dung | Ý nghĩa với Volve-DIA |
| --- | --- | --- |
| Hussain và Reddy, **SPE-236554-MS**, ADIPEC 11/2026, 10.2118/236554-MS | Hỏi đáp trên 1.266 DDR Volve; cây corpus field → wellbore → báo cáo → mục; 114 câu hỏi sinh từ corpus, 6 lớp; recall@10, MRR, nDCG@10, F1, tỷ lệ lấy nhầm giếng. Xếp hạng từ vựng không có cổng lọc lấy nhầm wellbore ở 84% câu hỏi định danh | **Đối thủ trực tiếp của T4.** Khác: không có nhiệm vụ nhãn, không có WITSML, câu hỏi tự sinh. Nên thêm metric "nhầm wellbore" vào T4 |
| Bihani và cộng sự, **SPE-235330-MS**, ADIPEC 11/2026, 10.2118/235330-MS | Agent ReAct trên 1.681 DDR Volve và 1.888 báo cáo BSEE; so sánh năm cách tổ chức tri thức; đáp án kiểm bằng máy; chấm mù theo cặp 1.080 ô, hiệu chỉnh Holm; bảng dữ kiện hai trục thời gian | **Đối thủ trực tiếp của T4**, có thống kê nghiêm túc. Khác: không có kiểm soát rò rỉ nhãn, không có nhiệm vụ T1–T3 |
| Mbamarah và cộng sự, SPE-237272-STU, ATCE 10/2026, 10.2118/237272-STU | Dự báo NPT từ DDR Volve, 2 giếng: huấn luyện F-10 (848 dòng, 90 NPT), thử F-9: F1 0,436, AUC 0,798 | Số tham chiếu cho T2 liên giếng; quy mô nhỏ |
| Joshi và cộng sự, SPE-229435-MS, ADIPEC 11/2025, 10.2118/229435-MS | Nền tảng agent thương mại trên WITSML và PDF, thử trên Volve; không có số định lượng trong tóm tắt | Hệ thống đóng |
| DrillScribe (mục 2.6) và repo Anatoly5ms (mục 2.7) | Xem trên | Số tham chiếu cho T2 và T3; không phải bài báo |
| Mishra và cộng sự, workshop FMSD, ICML 2026 (OpenReview X1s2qN24kX) | Sinh DDR từ chuỗi thời gian: model nền chuỗi thời gian, VLM, agent SQL | Bài toán ngược; dữ liệu [CXM] |
**Liên quan gián tiếp, không dùng Volve hoặc không phải DDR:** DrillBench, SPE-234135-MS (2.155 episode từ một chiến dịch khoan địa nhiệt); PetroBench, arXiv 2605.28032 và UpstreamBench (trắc nghiệm kiến thức); SPE-234026-MS (LLM giải thích nguyên nhân rủi ro, 45 giếng nội bộ); SPE-233220-MS (rig-state theo luật trên Volve và FORGE); SPE-227420-MS (RAG trên DDR mô phỏng).
**Cảnh báo rò rỉ:** IPTC-25191-MS báo F1 0,993 và ROC-AUC 1,000 trên 4 giếng Volve với leave-one-well-out và 17,4% khoảng dương. Tóm tắt nói leave-one-well-out, trong khi plan mục 9 xếp bài này vào nhóm "split theo cửa sổ"; cần đọc toàn văn để biết nguồn của điểm gần tuyệt đối [CXM].
**Kết luận novelty:** đến 17/11/2026 chưa thấy bài **tạp chí** nào đánh giá định lượng LLM hay agent trên DDR Volve, và chưa thấy benchmark nào có đồng thời kiểm soát rò rỉ mã, nhãn có provenance và kiểm định nhãn. Nhưng đã có **hai bài hội nghị SPE** đánh giá định lượng hỏi đáp trên DDR Volve. Không viết "first quantitative evaluation"; phát biểu gap phải giới hạn ở ba điều kiện trên.
---
## 5. Hệ quả cho kế hoạch
1. **Mục 0 và 4.4, đóng góp C2:** bỏ cụm "đối chiếu ba bộ nhãn độc lập (Bassey 2026, OMAE 2024, DrillScribe)". Lớp hai nên viết lại thành ba việc có thật:
- đối chiếu nhãn T3 với **luật văn bản** cài lại từ repo Anatoly5ms (độc lập một phần với mã);
- kiểm chéo parser với DrillScribe (đã khớp 100%);
- ba tình huống TSPP để minh họa lệch giữa tín hiệu WITSML và DDR.
Lớp một (audit mù) vì thế mang phần lớn sức nặng của C2; nên cân nhắc tăng cỡ mẫu audit hoặc tìm người chấm thứ hai.
2. **Mục 2.2:** sửa dòng Bassey (dữ liệu khai thác, không phải WITSML; chỉ là tiền lệ phương pháp). Ghi PetroAgents là [TV] với hai số 0,464 và 0,442, cùng cỡ mẫu 60 ví dụ mỗi seed và 30 ví dụ cho phép cắt lộ mã. Thêm SPE-236554-MS, SPE-235330-MS, SPE-237272-STU, DrillScribe, repo Anatoly5ms.
3. **Mục 2.1 ý 4 và mục 0:** "chưa có kết quả LLM nào trên Volve qua peer review tạp chí" còn đúng ở mức tạp chí, nhưng phải nhắc hai bài ADIPEC.
4. **Mục 4.2 và 4.6:** thêm baseline chỉ dùng độ dài văn bản cho T2; thêm metric nhầm wellbore cho T4.
5. **Mục 4.5:** hai repo độc lập đều tránh tách sidetrack khỏi giếng mẹ (Anatoly5ms chia theo 11 giếng; DrillScribe theo 23 `nameWell`). Đây là căn cứ để chọn nhóm split theo giếng.
6. **Mục 9:** sửa dòng Anatoly5ms thành "53% → 4% khoảng dương có đặc trưng đo sau khi sự cố bắt đầu". Dòng "split theo cửa sổ": tóm tắt IPTC-25191-MS nói leave-one-well-out, nên chưa đủ căn cứ để dẫn bài này cho rủi ro đó. Dòng rủi ro "nhóm khác ra bài trước": đã xảy ra ở mức hội nghị (2/11/2026).
7. **Mục 10:** thêm các claim không được viết: "ba bộ nhãn độc lập"; nhãn DrillScribe là nhãn độc lập; nhãn Bassey là nhãn khoan hay nhãn WITSML; độ khớp thống kê với TSPP.
8. **Mục 11:** tách OMAE2024-128386 (Cao, Song, Xu, Peng) khỏi arXiv 2503.07440 (Cao, Song, Yang, Li); ghi tiêu đề và DOI của OTC-36422-MS; ghi tiêu đề bài EAGE và việc DOI chưa phân giải; thêm URL DrillScribe.
9. **Việc còn lại:** (PetroAgents đã đọc toàn văn); đọc toàn văn OMAE2024-128386, SPE-236554-MS, SPE-235330-MS, IPTC-25191-MS nếu có quyền truy cập OnePetro và ASME; quét Scopus trước khi nộp.

View File

@@ -19,21 +19,21 @@ Nhãn trong tài liệu này:
| Mục | Quyết định |
| --- | --- |
| **Gap** | Chưa có benchmark công khai cho drilling intelligence trên DDR + WITSML đáp ứng cả ba điều: kiểm soát rò rỉ nhãn, nhãn có nguồn gốc tái lập được, nhãn được kiểm định độc lập. Trên Volve, TADI không có kết quả định lượng; PetroAgents có số liệu nhưng nhãn rò rỉ từ mã hoạt động, khác biệt không có ý nghĩa thống kê và chưa qua peer review [KT, S]. EGS của TADI chưa từng được đối chiếu với người (mục 2). |
| **Gap** | Chưa có benchmark công khai cho drilling intelligence trên DDR + WITSML đáp ứng cả ba điều: kiểm soát rò rỉ nhãn, nhãn có nguồn gốc tái lập được, nhãn được kiểm định độc lập. Trên Volve, TADI không có kết quả định lượng; PetroAgents có số liệu nhưng nhãn rò rỉ từ mã hoạt động, khác biệt không có ý nghĩa thống kê và chưa qua peer review [KT, TT]. Hai bài hội nghị ADIPEC 11/2026 (SPE-236554-MS, SPE-235330-MS) đã đánh giá định lượng hỏi đáp trên DDR Volve, nhưng không có nhiệm vụ nhãn và không kiểm soát rò rỉ mã [TT]. EGS của TADI chưa từng được đối chiếu với người (mục 2). |
| **Tên làm việc** | *Volve-DIA: a grounded benchmark and baselines for drilling-context recognition, trouble-interval identification and evidence-grounded question answering over public daily drilling reports and real-time data.* |
| **Đóng góp C1–C4** [ĐX] | **C1** Benchmark T1–T4 (T5 tùy chọn): nhãn sinh bằng mã từ XML và WITSML, bảng ánh xạ công khai, split theo wellbore. **C2** Kiểm định nhãn ba lớp: audit mù của tác giả với intra-rater κ; đối chiếu ba bộ nhãn độc lập (Bassey 2026, OMAE 2024, DrillScribe); LLM-judge có hiệu chuẩn. **C3** Baseline từ không-LLM đến agent dùng tool kiểu TADI, ablation rò rỉ (che/không che mã), ≥ 3 seed, CI bootstrap theo wellbore. **C4** Độ trung thực của bước đọc tài liệu: mỗi DDR có ba phiên bản XML, HTML, PDF, nên đo được sai lệch của bản in và của OCR so với nguồn, và ảnh hưởng của sai lệch OCR lên điểm T1–T4. Kho DDR của PVEP chỉ có PDF hoặc scan, nên con số này cần có trước khi chuyển giao (mục 5). |
| **Đóng góp C1–C4** [ĐX] | **C1** Benchmark T1–T4 (T5 tùy chọn): nhãn sinh bằng mã từ XML và WITSML, bảng ánh xạ công khai, split theo giếng (11 giếng, leave-one-well-out). **C2** Kiểm định nhãn ba lớp, **không có người chấm** (quyết định 17/11/2026, mục 12 ý 20): nhiều LLM rater mù thuộc các họ model khác nhau, báo κ của từng rater với nhãn code và κ giữa các rater (lớp chính; không gọi là audit của tác giả hay của chuyên gia); kiểm chéo với nguồn ngoài (DrillScribe cho parser, luật văn bản cài lại từ repo Anatoly5ms cho T3, ba tình huống kẹt cần TSPP làm ví dụ định tính); LLM-judge có hiệu chuẩn. Không bộ nhãn công khai nào trên Volve là nhãn NPT khoan độc lập (mục 4.4, 12 ý 17). **C3** Baseline từ không-LLM đến agent dùng tool kiểu TADI, ablation rò rỉ (che/không che mã), ≥ 3 seed, CI bootstrap theo giếng. **C4** Độ trung thực của bước đọc tài liệu: mỗi DDR có ba phiên bản XML, HTML, PDF, nên đo được sai lệch của bản in và của OCR so với nguồn, và ảnh hưởng của sai lệch OCR lên điểm T1–T4. Kho DDR của PVEP chỉ có PDF hoặc scan, nên con số này cần có trước khi chuyển giao (mục 5). |
| **Không phải đóng góp** | Chatbot hay dashboard; kiến trúc agent mới; nhãn đồng thuận liên chuyên gia (không có, nêu là giới hạn). |
| **Nguồn nhãn** | **XML và WITSML là nguồn duy nhất của nhãn và đáp án.** HTML và PDF là bản in; OCR không bao giờ dùng để tạo nhãn (mục 1.3, 5.3). |
| **Parser tài liệu** | chandra trên dịch vụ vLLM, request và prompt giống hệt vopec-chatbot (yêu cầu ngày 29/10/2026), cấu hình `configs/ocr.yaml`. Độ trung thực đo theo hai bước, mục 5.1. |
| **Parser tài liệu** | chandra trên dịch vụ vLLM, request và prompt giống hệt vopec-chatbot (yêu cầu ngày 29/10/2026), cấu hình `configs/ocr.yaml`. OCR toàn tập do một đồng nghiệp chạy và xuất qua Dataset Hub (17/11/2026); `04_ocr_hub.py` ghép từng trang về DDR (mục 1.3, 12 ý 12). Độ trung thực đo theo hai bước, mục 5.1. |
| **Venue** | *Geoenergy Science and Engineering* trước. Kế tiếp *Computers & Geosciences*, *Journal of Petroleum Exploration and Production Technology*. Dự phòng MDPI (*Applied Sciences*, *Energies*, *Processes*), *Petroleum* (KeAi). Quartile tra lại trên SCImago khi nộp [XM]. |
| **Thời gian** | 6 tháng [ĐX]: M1 = 30/10–30/11/2026 đến M6 = 4/2027, nộp cuối 4/2027; preprint ở M4–M5 nếu venue cho phép (mục 6). |
| **Việc hai tuần tới** | Mục 12, ý 1. |
| **Việc tiếp theo** | M1 xong phần dữ liệu, nhãn, T4, protocol nháp (17/11/2026); còn chờ điểm chấm thử 100 dòng của tác giả. Việc tiếp theo: mục 12, ý 1. |
---
## 1. Hiện trạng: những gì P0 kiểm tra trực tiếp (29/10/2026)
## 1. Hiện trạng: những gì P0 và M1 kiểm tra trực tiếp (29/10 và 17/11/2026)
Số liệu lấy từ `outputs/{inventory,ddr,render_qc,ocr_qc}/summary.json` của lượt `20261029-105934_p0` (lượt trước `20261029-101523_p0` cho cùng số liệu).
Số liệu P0 lấy từ `outputs/{inventory,ddr,render_qc,ocr_qc}/summary.json` của lượt `20261029-105934_p0` (lượt trước `20261029-101523_p0` cho cùng số liệu). Số liệu M1 (OCR toàn tập, WITSML, nhãn, T4) lấy từ `outputs/{ocr/hub,ocr_qc,witsml,labels,t4}/summary.json` của các lượt ngày 17/11/2026 ghi ở mục 12.
### 1.1 Kiểm kê [KT]
@@ -42,10 +42,10 @@ Số liệu lấy từ `outputs/{inventory,ddr,render_qc,ocr_qc}/summary.json` c
| DDR | 1.759 báo cáo, cả 1.759 có đủ ba phiên bản XML, HTML, PDF; 26 wellbore, mỗi wellbore 6 (F-15 B) đến 165 (F-12) báo cáo |
| Dung lượng | XML 21,3 MB; HTML 31,0 MB; PDF 56,8 MB; WITSML 19,3 GB |
| PDF | 3.066 trang: 457 báo cáo 1 trang, 1.297 báo cáo 2 trang, 5 báo cáo 3 trang. Born-digital (in từ HTML, có lớp text). 83 trang gần rỗng (< 50 ký tự), đều là trang cuối. Không trang nào chứa ảnh nặng |
| WITSML | 26 thư mục → 17 wellbore; 16 có DDR; 15 có log thời gian, trong đó 14 có DDR. 964 DDR thuộc các wellbore có log |
| Không khớp | WITSML `15/9-F-15 S` không có DDR, có thể chính là DDR `15/9-F-15` [XM]. 10 wellbore DDR không có WITSML: 15/9-19 A, B, BT2, S, ST2; F-1 A; F-11 A; F-11 T2; F-15 C; F-15 D |
| WITSML | **Sửa 17/11/2026** (số cũ của `01_inventory.py` đặt tên wellbore theo thư mục nên sai): 26 thư mục giếng (3 rỗng) → 33 thư mục wellbore → 22 tên wellbore công bố → **21 wellbore DDR đều có log thời gian**. Chỉ năm wellbore 15/9-19 không có WITSML. **1.384 báo cáo** nằm trên wellbore có log thời gian |
| Tên lệch | WITSML `15/9-F-15 S` là DDR `15/9-F-15`; WITSML `15/9-F-15` là DDR F-15 A; WITSML `15/9-F-15A` là DDR F-15 C (khớp theo `uidWellbore`, độ sâu cuối báo cáo, trạm survey, TD) [KT, mục 12 ý 14]. Wellbore DDR không có WITSML: 15/9-19 A, B, BT2, S, ST2 |
Hệ quả: phần chỉ cần DDR (T2, T4 và phần văn bản của T1) dùng được 1.759 báo cáo của 26 wellbore; phần cần WITSML (T3, T5, phần thời gian thực của T1) chỉ có 14 wellbore và 964 báo cáo. Split theo wellbore phải tính đến hai tập này.
Hệ quả: phần chỉ cần DDR (T2, T4 và phần văn bản của T1) dùng được 1.759 báo cáo của 26 wellbore; phần cần WITSML (T3, T5, phần thời gian thực của T1) có 21 wellbore và 1.384 báo cáo (1.102 báo cáo có ít nhất 1 h dữ liệu log trong kỳ, 983 báo cáo có ≥ 23 h). Split phải tính đến hai tập này.
### 1.2 DDR XML [KT]
@@ -63,7 +63,7 @@ Hệ quả: phần chỉ cần DDR (T2, T4 và phần văn bản của T1) dùng
- không activity nào thiếu comment hay mã, có thời lượng ≤ 0 hay nằm ngoài kỳ báo cáo;
- khoảng hở giữa hai activity liền nhau: 21.667 bằng 0, 25 dương, 5 âm (chồng lấn);
- tổng thời lượng activity bằng kỳ báo cáo ở 1.529 báo cáo, thiếu ở 221 (tổng 2.605,01 h), không báo cáo nào vượt.
- **Báo cáo bất thường:** 9 báo cáo không có activity, trong đó `15_9_19_A_1980_01_01` là báo cáo duy nhất có ngày trước 1990 [XM].
- **Báo cáo bất thường:** 9 báo cáo không có activity, trong đó `15_9_19_A_1980_01_01` là báo cáo duy nhất có ngày trước 1990. Đã kiểm (17/11): kỳ 31/12/1979–1/1/1980, spud của wellbore là 25/7/1997, hai tóm tắt ghi "None", chỉ chứa 5 trạm survey cùng ngày 1/1/1980, tạo năm 2018. Đây là báo cáo giữ chỗ cho survey tie-in với ngày mặc định, không phải một ngày khoan: `labels.yaml` gán trạng thái `placeholder_date` và loại khỏi T1–T3; T4 vẫn thấy nó trong dữ liệu công bố.
- **Văn bản:** `sum24Hr` ghi đúng chữ "None" ở 73 báo cáo, `forecast24Hr` ở 103. Độ dài trung bình: comment 114,3 ký tự, tóm tắt 24 h 173,2 ký tự (bản đánh giá ước ~116 và ~179).
Hệ quả: các lớp sự cố hiếm (stuck equipment 109, circulation loss 92, mud loss 12, injury 1) làm macro-F1 kém ổn định. Phải báo theo từng lớp kèm CI; việc gộp lớp, nếu có, chốt trong protocol trước G1 [ĐX].
@@ -75,6 +75,12 @@ Hệ quả: các lớp sự cố hiếm (stuck equipment 109, circulation loss 9
- Hai cờ này chỉ lấy từ XML. Một pipeline chỉ đọc PDF mang theo lỗi này và không OCR nào sửa được: ví dụ đầu tiên cho C4.
- 13 bảng còn lại của HTML (Drilling Fluid, Survey Station, ...) chưa được so với XML.
**OCR toàn tập [KT, 17/11/2026].** Một đồng nghiệp chạy OCR cho cả 3.639 trang PDF (3.066 trang DDR) và xuất qua Dataset Hub (COCO: 3.502 ảnh, 33.489 khối). Export không ghi tên file, nên `04_ocr_hub.py` ghép từng trang về DDR: lọc theo TF-IDF rồi tính F1 token có trọng số idf (ngưỡng 0,7 cho trang ≥ 50 token), dùng tương quan ảnh thu nhỏ (≥ 0,9) khi trang không có chữ; hòa trong 0,01 thì lấy F1 chữ cao hơn. Kết quả: 3.059/3.066 trang DDR ghép được (49 trang trắng đều ghép được), 1.752/1.759 báo cáo đủ trang; 7 trang chưa ghép (tương quan 0,69–0,94). Kiểm ngày: 1.753 trang có ngày, 16 trang có tập ngày trong PDF không nằm hết trong ngày OCR đọc được; cả 16 đều có F1 chữ ≥ 0,91 và tương quan ảnh ≥ 0,94, nên nhiều khả năng ghép đúng trang và OCR đọc sai chữ số hoặc bỏ dòng Period (chưa xem từng trang [XM]). Với 47 trang pilot, bản hub khác bản dịch vụ ở 3,97% ký tự (7/47 trang giống hệt): đó là hai lượt OCR khác nhau, nên cả hai lấy làm đại diện cho OCR chứ không so được từng ký tự với nhau.
QC toàn tập (`05_ocr_qc.py --source hub`, 1.752 báo cáo, 3.056 trang, 365.698 mục nội dung): khớp tuyệt đối **0,9181**, CER **2,40%**, WER **5,56%**. Ô bảng 280.995 mục, khớp 0,9116, CER 2,67%; Operations (140.322 ô) khớp 0,8605, CER 2,99%; Drilling Fluid CER 1,09%; Survey Station CER 0,24%; Casing Liner Tubing CER 4,72%; Pore Pressure CER 4,30%. Trường đầu báo cáo khớp 0,9280, CER 3,00%. Lỗi theo trường nặng nhất: độ sâu (depth mMD khớp 0,9241, CER 6,97%; mTVD 0,9418), hole dia (CER 5,4%), rig name (khớp 0,3385), pressure và temperature (OCR bịa đơn vị). CER nội dung theo báo cáo: trung vị 0,93%, phân vị 90 là 4,98%, lớn nhất 85,7% (một báo cáo gần như hỏng); chỉ 9/1.752 báo cáo khớp tuyệt đối toàn bộ. Ký tự hay sai nhất: chèn khoảng trắng (9.507), bỏ "-" (9.160), thay "-" bằng "–" (7.952), chèn "°" (2.524), "Æ" thành "E" (1.152). `parse_ocr` phải hoàn tác bố cục: nối bảng 1.136 lần, gộp hàng nối tiếp 151 lần (trên HTML luật này không kích hoạt, nên đây là lỗi riêng của OCR). Số toàn tập gần số pilot (CER 2,50%) nên pilot là đại diện tốt, nhưng độ sâu và tên riêng kém hơn mức trung bình.
**Phạm vi của QC bản in (sửa 17/11).** `03_render_qc.py` chỉ so header, 31 trường đầu báo cáo, hai đoạn tóm tắt và bảng Operations, không phải 14 bảng. Khi đối chiếu T4, thấy thêm một lỗi render: cột "End mMD" của bảng Bit Record in `bitRun_mdHoleStart` (16/16 hàng kiểm tay; 90/90 theo T4), và "Form ROP" bằng `bitRun_ropAv` (88/88). Như Tight well và HPHT, giá trị này chỉ lấy từ XML.
**OCR pilot [KT trên pilot].** 1 báo cáo mỗi wellbore (báo cáo giữa theo ngày): 26 báo cáo, 47 trang.
- 47/47 trang đọc được ở lần thử đầu; không trang nào lặp vòng hay chạm trần token.
- Mỗi request 23,9 s; với 4 worker là 6,2 s/trang (lượt pilot: 5 phút 3 giây kể cả render). Mỗi trang khoảng 2.017 token prompt và 2.196 token output; ảnh PNG 200 DPI khoảng 219 KB.
@@ -106,14 +112,14 @@ Theo báo cáo: CER nội dung trung vị 0,83%, phân vị 90 là 4,5%, lớn n
- **Nhãn và chữ số:** "mTD" hoặc "TVD" thay cho mTVD; "Wellbores:" thay cho "Wellbore:"; 3273 → 2273; −999,99 → −999,89; tên wellbore thành "15/9-F15 D".
- **Bố cục:** chèn khoảng trắng giữa từ ("b op", "u p/down"), lỗi ký tự phổ biến nhất với 207 lần trên 393 mục gần đúng; "formation integrity tes t" là do PDF ngắt dòng giữa từ.
**Giới hạn.** 26 báo cáo này không phải mẫu ngẫu nhiên của các trang. Số liệu sẽ được thay bằng số của toàn tập khi OCR đủ 1.759 báo cáo (mục 12, ý 1).
**Giới hạn.** 26 báo cáo này không phải mẫu ngẫu nhiên của các trang; số toàn tập ở trên thay cho số pilot khi báo cáo C4. 7 báo cáo chưa đủ trang bị loại khỏi QC và khỏi thí nghiệm C4.
### 1.4 Hệ quả cho bài
1. Với DDR, nhãn dựng từ XML, không cần OCR. OCR có hai vai trò: đo C4, và đọc các tài liệu chỉ có dạng PDF (`Reports/`: Discovery report, PUD) cho T4 [ĐX].
2. Lỗi đáng ngại nhất không lộ trong CER: độ sâu lệch nhãn, cột bị gộp, chữ số bị đổi. C4 vì vậy đo ảnh hưởng lên điểm nhiệm vụ, không chỉ CER.
3. Cờ Tight well và HPHT cho thấy bản in born-digital vẫn có thể sai so với nguồn.
4. WITSML giới hạn T3, T5 và phần thời gian thực của T1 ở 14 wellbore.
4. WITSML giới hạn T3, T5 và phần thời gian thực của T1 ở 21 wellbore (11 giếng trừ giếng 15/9-19).
5. `ropCurrent` và `mdPlanned` trống ở mọi báo cáo, nên các template T4 về ROP phải tính từ `distDrill`, `bits.bitRun_ropAv` hoặc WITSML; template ghi rõ nguồn.
6. `diaHole` trống ở 260 báo cáo có activity khoan, nên nhãn pha T1 không suy trực tiếp được ở các ngày đó.
@@ -127,7 +133,7 @@ Theo bản đánh giá mục 5.3, bốn chỗ trống:
1. chưa có benchmark công khai cho các nhiệm vụ Atlas trên DDR + WITSML có kiểm soát rò rỉ, nhãn rõ nguồn gốc và được kiểm định độc lập;
2. chưa có đánh giá truy xuất giếng hoặc khoảng tương đồng nào có nhãn liên quan và kiểm tra ngoại suy;
3. EGS của TADI chưa được đối chiếu với đánh giá của người;
4. chưa có kết quả LLM nào trên Volve qua peer review tạp chí.
4. chưa có kết quả LLM nào trên Volve qua peer review tạp chí (đến 17/11/2026; đã có hai bài hội nghị ADIPEC về hỏi đáp, mục 2.2).
P0 thêm một chỗ trống [ĐX]: chưa bài nào trên Volve đo ảnh hưởng của bước đọc tài liệu (bản in, OCR) lên nhiệm vụ phía sau, dù Volve là bộ dữ liệu hiếm có cả nguồn XML lẫn bản in của cùng một báo cáo.
@@ -136,14 +142,17 @@ P0 thêm một chỗ trống [ĐX]: chưa bài nào trên Volve đo ảnh hưở
| Công trình | Có gì | Thiếu gì so với Volve-DIA |
| --- | --- | --- |
| TADI, arXiv 2605.00060 (4/2026) [KT, đã đọc toàn văn] | DuckDB 12 bảng + ChromaDB; 12 tool; EGS; taxonomy 130 câu hỏi | Không có kết quả định lượng; EGS chưa tính trên câu nào; không có nhãn chuẩn |
| PetroAgents, preprints.org (6/2026) [KT tồn tại; số liệu S] | Volve Bench 6 nhiệm vụ; DRILL-NPT macro-F1 ≈ 0,46; multi-agent hơn single-LLM +0,048 (p = 0,22, 3 seed) | Nhãn sinh từ chính mã DDR; lộ mã nâng baseline 0,355 → 0,431; chưa peer review |
| PetroAgents, preprints.org (6/2026) [TV, đọc toàn văn 17/11/2026] | Volve Bench 6 nhiệm vụ trên đặc tả, mới báo DRILL-NPT (nhãn lớp NPT theo well-day từ `stateDetailActivity` và `proprietaryCode`, 1.750 ví dụ, 7 lớp; mẫu 60 ví dụ mỗi seed) và 12 câu hỏi DISCOVERY-QA; macro-F1 0,464 (mọi wellbore) và 0,442 (tập con có WITSML); multi-agent hơn single-LLM +0,048 (p = 0,22, 3 seed) | Lộ mã nâng 0,355 → 0,431 nhưng chỉ trên 30 ví dụ; split theo wellbore (sub-wellbore F-11 tách riêng), không theo giếng; không có metric theo lớp hiếm, không nhãn kiểm định; chưa peer review; chưa có bản tạp chí (Crossref 17/11/2026) |
| Bodén et al., SPE-228117-MS (2025) [KT tồn tại] | Trợ lý agentic, 75 người dùng thử | Hệ thống đóng, bộ câu hỏi không công bố |
| Bassey et al., arXiv 2608.05685 (8/2026) [KT tồn tại] | Nhãn bất thường WITSML dựng theo luật, có provenance, CC BY-NC-SA | Dùng làm bộ nhãn độc lập để đối chiếu (C2) |
| Các bài SPE/IADC/IPTC (bản đánh giá mục 5.2) [S] | LLM trích sự kiện DDR, stuck pipe, NPT | Dữ liệu nội bộ, hoặc split theo cửa sổ |
| Bassey et al., arXiv 2608.05685 (8/2026) [TV] | Nhãn sự kiện **khai thác theo ngày** (236 sự kiện, 6 giếng) dựng theo luật kèm PUD, có provenance, CC BY-NC-SA | Không dùng WITSML hay DDR khoan, nên không phải bộ nhãn đối chiếu; chỉ là tiền lệ phương pháp cho nhãn dựng bằng luật |
| Hussain và Reddy, SPE-236554-MS; Bihani và cộng sự, SPE-235330-MS (ADIPEC 11/2026) [TT] | Hỏi đáp định lượng trên 1.266 và 1.681 DDR Volve; bài sau có ReAct agent, chấm mù theo cặp | Không có nhiệm vụ nhãn T1–T3, không kiểm soát rò rỉ mã; đối thủ trực tiếp của T4 |
| DrillScribe (GitHub, 8/2026) và repo Anatoly5ms (GitHub, 10/2026) [DL] | NPT theo episode (F1 0,866 chỉ dùng văn bản) và sự cố theo khoảng 10 m | Không phải bài báo; nhãn DrillScribe là phép biến đổi của `stateDetailActivity`; Anatoly5ms không kèm file nhãn |
| Mbamarah và cộng sự, SPE-237272-STU (10/2026) [TT] | Dự báo NPT từ DDR Volve, huấn luyện F-10, thử F-9: F1 0,436 | Hai giếng; số tham chiếu cho T2 liên giếng |
| Các bài SPE/IADC/IPTC (bản đánh giá mục 5.2; chi tiết ở `docs/literature_notes.md`) [S] | LLM trích sự kiện DDR, stuck pipe, NPT | Dữ liệu nội bộ, hoặc split theo cửa sổ |
### 2.3 Kiểm tra novelty [XM]
Đọc toàn văn PetroAgents, Bassey 2026, EAGE 2026101276; kiểm PetroAgents đã có bản tạp chí chưa; quét OnePetro, arXiv, Scopus lần cuối trước khi nộp. Không viết "first" trước khi xong (mục 10).
Đã quét 17/11/2026 (`docs/literature_notes.md` mục 4): chưa thấy bài tạp chí nào đánh giá định lượng LLM trên DDR Volve; có hai bài hội nghị SPE về hỏi đáp. Còn lại: EAGE 2026101276, SPE-236554-MS, SPE-235330-MS, IPTC-25191-MS; quét OnePetro, arXiv, Scopus lần cuối trước khi nộp. Không viết "first" trước khi xong (mục 10).
---
@@ -153,7 +162,7 @@ P0 thêm một chỗ trống [ĐX]: chưa bài nào trên Volve đo ảnh hưở
| --- | --- | --- | --- |
| RQ1 | Các họ baseline (không-LLM, encoder fine-tune, LLM open-weight, model API, RAG, agent) giải T1–T4 tốt đến đâu khi che mã và split theo wellbore? | H1: trên T2, LLM zero-shot không hơn TF-IDF + LR một cách có ý nghĩa khi che mã | macro-F1, PR-AUC, CI bootstrap theo wellbore |
| RQ2 | Bao nhiêu phần điểm số đã công bố trên Volve đến từ rò rỉ (mã trong input, đặc trưng sau sự kiện, split theo cửa sổ)? | H2: bỏ cả ba nguồn rò rỉ làm điểm giảm rõ; PetroAgents gợi ý ≈ 0,08 macro-F1 riêng phần mã | Ablation có/không cho từng nguồn |
| RQ3 | Nhãn xác định có khớp với audit mù và các bộ nhãn độc lập không? | H3: κ ≥ 0,6 cho NPT nhị phân; thấp hơn ở các lớp nguyên nhân hiếm | Cohen κ theo lớp và theo wellbore |
| RQ3 | Nhãn xác định có khớp với các LLM rater mù (không có người chấm) và các kiểm chéo không? | H3: κ ≥ 0,6 cho NPT nhị phân; thấp hơn ở các lớp nguyên nhân hiếm | Cohen κ của từng LLM rater với nhãn code, theo lớp và theo giếng; κ giữa các rater |
| RQ4 | EGS của TADI có tương quan với điểm của người không? | H4: EGS (regex) tương quan yếu với độ đúng thật | Spearman trên ~100 câu tác giả chấm mù |
| RQ5 | Sai lệch của bước đọc tài liệu làm điểm T1–T4 đổi bao nhiêu? | H5: OCR làm giảm điểm T4 nhiều hơn T2, vì T4 cần số liệu chính xác | Cùng nhãn từ XML; input từ XML so với input từ OCR |
@@ -166,8 +175,8 @@ Kết quả được báo cáo bất kể chiều nào; giả thuyết không đ
### 4.1 Dữ liệu và parser
- **DDR XML → DuckDB** [KT]: 17 bảng, mục 1.2. Giữ tên phần tử WITSML làm tên cột để mọi giá trị truy được về schema.
- **WITSML** (chưa làm): log thời gian (68 kênh, chu kỳ khoảng 3 s theo bản đánh giá mục 3; parser sẽ đếm lại), `bhaRun`, `message`, `trajectory`, `mudLog`, vào DuckDB. Sentinel và bộ lọc kênh lấy theo TADI [S], ghi rõ trong code. Kiểm `15/9-F-15 S` so với `15/9-F-15`.
- **Formation tops:** bản đánh giá mục 3 ghi 409 pick trên 35 wellbore; thư mục nguồn chưa xác định và chưa có trong manifest [XM].
- **WITSML** [KT, `06_parse_witsml.py`, 17/11/2026]: log thời gian, log độ sâu, `trajectory`, `message`, `bhaRun`, `mudLog`. Log lưu dạng dài (1.744 mnemonic), mỗi wellbore một file parquet zstd, `time_log` 2,25 tỉ giá trị, `depth_log` 45,4 triệu, tổng 2,2 GB; view DuckDB không sao chép dòng. Log Baker Hughes `GenTime` (2013–2016): 78 kênh, bước 3,0 s; log Schlumberger (2007–2009): 42–252 kênh, bước trung vị 3,97 s, nên "68 kênh, 3 s" của bản đánh giá không đúng. Trùng lặp trong một log: 2,9 triệu giá trị, đều giống hệt, 0 xung đột; giữa các log: xếp hạng `dup_rank`, không xóa. Dùng view `drill_depth` cho độ sâu, không dùng cột `Depth` của Baker Hughes qua `time_log_dedup`. Sentinel của TADI không xuất hiện trong log; 3.703 giá trị trong file object được đổi thành thiếu; giá trị đáng ngờ (99999, −999) được giữ và đếm ở `log_suspects`. BHA 161, mudLog 2.882 khoảng, message 11.134 khớp đúng TADI; trạm trajectory 5.561 so với 4.217 của TADI, chưa tái hiện được. Sentinel và bộ lọc kênh lấy theo TADI [S], ghi rõ trong code. Kiểm `15/9-F-15 S` so với `15/9-F-15`.
- **Formation tops** [KT]: nguồn là `Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat` (tìm ngày 29/10/2026, mục 12 ý 11): 409 pick trên 35 wellbore, khớp đúng số của bản đánh giá mục 3. 23/26 wellbore DDR có pick khi so tên trực tiếp; sau ánh xạ (17/11): `15/9-19 SR` là DDR `15/9-19 ST2`; DDR 15/9-19 S thừa hưởng 4 pick của SR phía trên điểm kick-off 1.493 m; F-9 A thừa hưởng 2 pick của F-9; `15/9-F-12 pilot` thuộc F-12. Kết quả: 24 wellbore DDR có pick riêng, 2 chỉ có pick chung, không wellbore nào thiếu. File đã vào manifest (25.571 file). Đối chiếu với `stratInfo` của DDR: 130 pick khớp tên, chênh trung vị 0,0 m, 97 trong 5 m, lớn nhất 1.093 m (33 ngoại lệ chưa xem).
- **PDF ngoài DDR** (`Reports/`): đọc bằng OCR cho T4 nếu còn thời gian [ĐX].
### 4.2 Nhiệm vụ và metric
@@ -175,7 +184,7 @@ Kết quả được báo cáo bất kể chiều nào; giả thuyết không đ
| Nhiệm vụ | Đầu vào | Metric | Chống rò rỉ |
| --- | --- | --- | --- |
| T1 Nhận diện bối cảnh | Cửa sổ 24 h: văn bản DDR và thống kê WITSML | macro-F1 cho pha, section, operation | Che hole size khi hole size là nhãn |
| T2 Phân loại dòng NPT | Comment và tóm tắt 24 h, **che mã hoạt động** | macro-F1, PR-AUC; GroupKFold theo wellbore | Báo cả chế độ không che để đo rò rỉ |
| T2 Phân loại dòng NPT | Comment và tóm tắt 24 h, **che mã hoạt động** | macro-F1, PR-AUC; leave-one-well-out | Báo cả chế độ không che để đo rò rỉ |
| T3 Định vị khoảng khó khăn | Chuỗi activity và formation | IoU khoảng; PR-AUC trên lưới 10 m | Chỉ đặc trưng trước sự kiện |
| T4 Hỏi đáp có dẫn chứng | Câu hỏi tự nhiên | Đúng/sai trong dung sai; citation precision; tỉ lệ số liệu bịa; tương quan EGS với điểm người | Đáp án tính bằng SQL, không bằng LLM |
| T5 (tùy chọn) Truy xuất khoảng tương đồng | Embedding cửa sổ WITSML, DDR, formation | nDCG@k, MRR; PR-AUC khi dự báo khó khăn từ láng giềng; leave-one-wellbore-out | Nhãn liên quan xác định bằng luật |
@@ -183,24 +192,32 @@ Kết quả được báo cáo bất kể chiều nào; giả thuyết không đ
### 4.3 Nhãn xác định
Nguyên tắc: **mọi nhãn sinh bằng mã từ dữ liệu gốc**, có provenance. Người chỉ *kiểm định*, không *tạo* nhãn (tiền lệ: Bassey 2026 [S]).
- **T1:** pha theo chuyển `diaHole` (36"/30", 26", 17½", 12¼", 8½"); operation theo `proprietaryCode`; section theo WITSML. Mốc spud và TD kiểm chéo với NPD FactPages [S]. `diaHole` trống ở 260 báo cáo có activity khoan (mục 1.2): luật điền (ví dụ hole size gần nhất của cùng wellbore, hoặc `bits.diaBit`) chốt trong `labels.yaml` và kiểm trên audit [ĐX].
- **Kết quả dựng nhãn [KT, `07_labels.py`, `labels.yaml` sha256 `0b1f877f…`, 17/11/2026]:**
- **T1 section** (hole size theo ngày báo cáo): luật điền `ffill` (hole section gần nhất đã mở của wellbore), chọn vì trên lược đồ `tail_half` (giống các khoảng trống thật) cho 1,0000 và trên `single` cho 0,9051, và khớp kích thước nêu trong văn bản 7/8, bản ghi bit 23/30 ở các ngày thiếu thật. 17 báo cáo trước hole size đầu tiên lấy section đầu (`bfill_leading`, đánh dấu để protocol loại được). Ngày khoan: 932 (672 có `diaHole` công bố, 260 điền); 818 ngày khác (hoàn thiện, workover, P&A) không chấm. Section sau điền: 8,5" 404, 12,25" 196, 17,5" 151, 26" 93, 36" 57, 6" 27, 9,875" 4 (ngày khoan).
- **T1 op_class:** 14 lớp theo `proprietaryCode`, 19.870 dòng (loại interruption).
- **T2:** NPT định nghĩa (a) chỉ interruption: 3.577 dòng, 8.343 h (21,2% giờ báo cáo); (b) hợp ba điều kiện: 4.286 dòng, 9.626 h (24,4%). Nhóm nguyên nhân: equipment 1.985/2.425, weather 445, stuck_fishing 246/248, unspecified 262/299, waiting 229, sidetrack 202, operation_failed 101/322, lost_circulation 78/86, well_control 29, hse 0/1 (a/b). Có 192 dòng mã và văn bản mâu thuẫn; mã được ưu tiên, điểm cũng báo với thứ tự ngược.
- **T3:** chỉ 50,3% dòng NPT (44,6% giờ) định vị được trong lỗ, do 9.116 activity có độ sâu 0 và 2.923 nằm trên mudline. 8.757 ô 10 m, 844 dương (a) và 979 (b); 656 và 728 khoảng. 191 ô dương nằm trên đầu lỗ của chính wellbore (thừa hưởng từ wellbore mẹ), báo riêng, không chấm.
- **Văn bản có nêu nhãn không:** từ khóa trong comment tìm lại NPT (a) với recall 0,33 và precision 0,51; weather recall 0,80; well_control 0: baseline từ vựng sẽ yếu, đúng kỳ vọng cho che mã.
- Lớp không đánh giá được theo split theo giếng (luật ≥ 3 giếng mỗi giếng ≥ 5 mục): sidetrack (3 wellbore, 1 giếng), lost_circulation, well_control, hse ở T2; 6" và 9,875" ở T1 section. Gộp và bỏ ghi trong `protocol_v1` (mục 12 ý 15).
- **T1:** pha theo chuyển `diaHole` (36"/30", 26", 17½", 12¼", 8½"); operation theo `proprietaryCode`; section theo WITSML. Mốc spud và TD kiểm chéo với NPD FactPages [S]. `diaHole` trống ở 260 báo cáo có activity khoan (mục 1.2): luật điền đã chốt là `ffill` (xem kết quả ngay phía trên), kiểm trên audit ở M2.
- **T2:** NPT có/không và nhóm nguyên nhân từ `stateDetailActivity`, `proprietaryCode`, `state` (số lượng ở mục 1.2). Bảng ánh xạ công khai ở `configs/labels.yaml`. Định nghĩa NPT chốt trước G1: chỉ nhóm interruption (3.577), hay hợp ba điều kiện (4.286).
- **T3:** khoảng MD có khó khăn = gộp các activity NPT liền kề theo độ sâu, trên lưới 10 m.
- **Kết quả T4 [KT, `08_t4_questions.py`, 17/11/2026]:** 39 template, 3.915 ứng viên, 1.662 câu hỏi (1.638 có đáp án, 24 không trả lời được) sau khi loại 371 ứng viên; theo họ: lookup 825, aggregation 513, temporal_event 134, comparison 102, multi_hop 88. Phạm vi: 1.560 câu một wellbore, 92 câu cặp, 10 câu toàn field. Đáp án SQL (DuckDB), cài đặt pandas độc lập, và đọc thẳng XML thô khớp 100% (3.915/3.915 và 1.662/1.662). Mỗi câu có dòng dẫn chứng (trung vị 3, tối đa 488; 169 câu quá 50 dòng). Chấm chính câu trả lời với chính nó đạt 1.662/1.662.
- **T4:** câu hỏi từ template, đáp án **tính bằng SQL trên DuckDB**, kèm id các dòng dẫn chứng (ví dụ: ROP trung bình theo section, số ngày theo pha, độ sâu và ngày của sự kiện X, mud weight tại sự cố, so sánh hai giếng). LLM chỉ paraphrase câu hỏi; đáp án gốc giữ nguyên; chấm tự động trong dung sai.
- **T5:** hai khoảng liên quan nếu cùng hole section, cùng formation, cùng nhóm NPT.
### 4.4 Kiểm định nhãn: ba lớp
1. **Audit mù của tác giả:** khoảng 300 activity, phân tầng theo wellbore và lớp, che `proprietaryCode` và `stateDetailActivity`; gán nhãn chỉ từ comment và tóm tắt 24 h; chấm hai lần cách ≥ 2 tuần. Báo intra-rater κ và độ khớp nhãn xác định với audit theo lớp.
2. **Bộ nhãn độc lập:** Bassey 2026, OMAE 2024 (stuck pipe), các episode NPT của DrillScribe [S]. Báo độ khớp theo wellbore và theo thời gian; kiểm giấy phép từng bộ trước khi phát hành kèm [XM].
1. **LLM rater mù** (thay audit của tác giả, quyết định 17/11/2026 vì không có người chấm): khoảng 300 activity, phân tầng theo vùng NPT, nhóm nguyên nhân và giếng, che `proprietaryCode` và `stateDetailActivity`; mỗi rater là một họ model khác nhau (bản thử: Sonnet, Opus, Haiku; M2 thêm ít nhất một model open-weight), chỉ thấy view đã che, tự chấm từng dòng, không thấy kết quả của rater khác; chạy lại lần hai cách ≥ 2 tuần để đo độ nhất quán của từng rater. Báo κ của từng rater với nhãn code theo lớp, κ giữa các rater (Fleiss và từng cặp) và các dòng bất đồng. Thống kê quyết định (chọn định nghĩa NPT, gộp lớp) là trung vị theo rater. Giới hạn nói thẳng: LLM rater dùng chung dữ liệu huấn luyện và quy ước với các baseline LLM của M3–M4, nên độ khớp chỉ là bằng chứng nhất quán với một cách đọc văn bản, không phải bằng chứng đúng theo chuyên gia. Nếu sau này có người chấm, thêm như một rater riêng và báo trên dòng riêng.
2. **Kiểm chéo với nguồn ngoài** (đã đọc và đối chiếu ngày 17/11/2026, `docs/literature_notes.md`): không bộ nhãn công khai nào trên Volve là nhãn NPT khoan độc lập. Bassey 2026 gán nhãn trên dữ liệu khai thác theo ngày; nhãn DrillScribe dựng lại khớp 1.758/1.758 episode từ `stateDetailActivity`; bộ TSPP chỉ có 3 sự cố kẹt cần, không có cột nhãn, không có giấy phép, và DDR không ghi kẹt cần ở cả ba lần. Còn lại ba việc: (i) kiểm chéo parser với DrillScribe (khớp 100%); (ii) đối chiếu T3 với luật văn bản cài lại từ repo Anatoly5ms (MIT, giữ ghi công), độc lập một phần với mã; (iii) ba tình huống TSPP như ví dụ định tính. Lớp một (LLM rater mù) cùng các kiểm chéo vì thế mang phần lớn sức nặng của C2.
3. **LLM-judge có hiệu chuẩn** cho phần văn bản của T4: đối chiếu với điểm tác giả trên khoảng 100 câu; chỉ dùng khi đạt ngưỡng G3.
Giới hạn nêu thẳng trong bài: không có đồng thuận liên chuyên gia; nhãn T2 và T3 phụ thuộc cách supervisor mã hóa, vốn không nhất quán (OTC-36422 [S]).
Giới hạn nêu thẳng trong bài: không có người chấm và không có đồng thuận liên chuyên gia; nhãn T2 và T3 phụ thuộc cách supervisor mã hóa, vốn không nhất quán (OTC-36422 [S]).
### 4.5 Split và chống rò rỉ
- GroupKFold theo wellbore cho mọi nhiệm vụ; không chọn gì (hyperparameter, prompt, ngưỡng) trên wellbore test.
- Nhóm theo wellbore hay theo giếng [XM]: 26 wellbore có DDR thuộc 11 giếng (15/9-19 và F-15 mỗi giếng 5 wellbore, F-1 và F-11 mỗi giếng 4, F-9 có 2, sáu giếng còn lại mỗi giếng 1). Các sidetrack dùng chung phần lỗ phía trên điểm rẽ nhánh và cùng vị trí, nên chia theo wellbore có thể để lọt thông tin giữa các nhánh. `protocol_v1` chốt một cách trước G1.
- **Đã chốt trong bản nháp `protocol_v1` (17/11/2026): nhóm theo giếng**, leave-one-well-out ở vòng ngoài, GroupKFold(5) theo giếng ở vòng trong, điểm tính trên dự đoán out-of-fold gộp; split theo wellbore chỉ là phân tích độ nhạy. Không chọn gì (hyperparameter, prompt, ngưỡng) trên giếng test; hai giếng phát triển cho hệ dùng prompt là 15/9-F-7 và 15/9-F-9 (hai giếng ít báo cáo nhất).
- Căn cứ chọn nhóm theo giếng [KT, `outputs/labels/summary.json`]: 26 wellbore có DDR thuộc 11 giếng (15/9-19 và F-15 mỗi giếng 5 wellbore, F-1 và F-11 mỗi giếng 4, F-9 có 2, sáu giếng còn lại mỗi giếng 1). 16 ngày báo cáo được hai wellbore của cùng giếng dùng chung; comment dài ≥ 40 ký tự lặp nguyên văn ở wellbore anh em với tỷ lệ 0,30% so với 0,96% ở giếng khác; 191 trong 844 ô dương của T3 nằm trên điểm đầu lỗ của chính wellbore (đoạn thừa hưởng từ wellbore mẹ). Hai repo độc lập (DrillScribe, Anatoly5ms) đều giữ sidetrack cùng giếng mẹ. Hậu quả: lớp hiếm tập trung ở vài giếng, nên GroupKFold(5) không giúp; luật "lớp chấm riêng chỉ khi ≥ 3 giếng mỗi giếng ≥ 5 mục" áp dụng (mục 12 ý 15).
- Hai chế độ input cho T2 và T3: che mã (chính) và không che (đo rò rỉ).
- T3 chỉ dùng đặc trưng trước thời điểm dự báo; kiểm thủ công một mẫu cửa sổ.
- **`configs/protocol_v1.yaml` khóa bằng SHA-256 trước lần chạy model đầu tiên**, chốt split, seed, metric, định nghĩa NPT, gộp lớp và ngưỡng các cổng.
@@ -231,7 +248,7 @@ Hàng, nhãn và cột căn bằng quy hoạch động đơn điệu, tối đa
### 5.2 Thí nghiệm C4 [ĐX]
1. OCR toàn bộ 1.759 DDR, QC toàn tập; số liệu mục 1.3 thay bằng số toàn tập.
1. OCR toàn bộ DDR và QC toàn tập (xong 17/11, mục 1.3; còn 7 trang chưa ghép).
2. Ảnh hưởng lên nhiệm vụ: cùng nhãn từ XML, cùng model; input từ XML hoặc từ `parse_ocr` của PDF. Báo chênh lệch điểm T1, T2, T4 kèm CI.
3. (Tùy chọn) Mô phỏng scan: in lại trang ở DPI thấp, thêm nhiễu kiểu fax, đo lại bước 1–2. Gần với kho DDR scan của PVEP hơn.
@@ -250,10 +267,10 @@ Ngưỡng các cổng chốt trong `protocol_v1` trước G1; sau đó ngưỡng
| Pha | Thời gian | Việc chính | Đầu ra | Cổng |
| --- | --- | --- | --- | --- |
| **P0 Hạ tầng** | 29/10/2026 (xong) | Khung project theo ML-Porosity; manifest dữ liệu; parser DDR XML và DuckDB; QC bản in; OCR pilot và QC OCR; test | `scripts/run_p0.sh` chạy end-to-end 3 phút 18 giây với 4 luồng | **G0 (đạt 29/10):** số lượng khớp `EXPECTED`; sai lệch bản in giải thích được; OCR pilot đã đo |
| **M1 Dữ liệu và nhãn** | 30/10 – 30/11/2026 | OCR toàn bộ DDR và QC toàn tập; parser WITSML; bảng ánh xạ mã → nhãn; nhãn T1–T3; template và SQL cho T4; chấm mù thử 100 dòng | DuckDB đủ bảng; `configs/labels.yaml`; bộ câu hỏi T4 | — |
| **M2 Kiểm định và khóa protocol** | 12/2026 | Audit mù lần 1 (~300 dòng); đối chiếu Bassey, OMAE, DrillScribe; viết và khóa `protocol_v1` | `protocol_v1.yaml` + `.sha256`; báo cáo độ khớp nhãn | **G1:** protocol khóa trước mọi lần chạy model. Lớp có κ < 0,6 so với audit, hoặc < 20 mục audit, không báo như lớp riêng: gộp hoặc bỏ, có ghi lại |
| **M1 Dữ liệu và nhãn** | 30/10 – 30/11/2026 (làm xong phần máy 17/11; còn chấm thử 100 dòng) | OCR toàn bộ DDR và QC toàn tập; parser WITSML; bảng ánh xạ mã → nhãn; nhãn T1–T3; template và SQL cho T4; chấm mù thử 100 dòng | DuckDB đủ bảng; `configs/labels.yaml`; bộ câu hỏi T4; `protocol_v1` bản nháp | — |
| **M2 Kiểm định và khóa protocol** | 12/2026 | Chấm mù bằng ≥ 3 LLM rater (~300 dòng, chạy lại lần hai); kiểm chéo DrillScribe, Anatoly5ms, TSPP; viết và khóa `protocol_v1` | `protocol_v1.yaml` + `.sha256`; báo cáo độ khớp nhãn | **G1:** protocol khóa trước mọi lần chạy model. Lớp có κ < 0,6 (trung vị theo LLM rater), hoặc < 20 mục được chấm, không báo như lớp riêng: gộp hoặc bỏ, có ghi lại |
| **M3–M4 Baseline** | 1–2/2027 | Baseline T1–T4; agent; RAG; ablation rò rỉ; thí nghiệm C4 | Bảng kết quả, ≥ 3 seed, CI theo wellbore | **G2:** đủ baseline và ablation trên mọi nhiệm vụ; báo kết quả bất kể chiều |
| **M5 Audit 2 và judge** | 3/2027 | Audit mù lần 2 (intra-rater κ); T5 nếu kịp; phân tích lỗi; hiệu chuẩn LLM-judge; đối chiếu EGS | κ, agreement của judge, tương quan EGS | **G3:** chỉ dùng LLM-judge cho T4 khi agreement với tác giả đạt κ ≥ 0,6; không đạt thì T4 chỉ báo metric tự động và ghi rõ |
| **M5 Chạy lại rater và judge** | 3/2027 | Chạy lại LLM rater lần hai (độ nhất quán từng rater); T5 nếu kịp; phân tích lỗi; hiệu chuẩn LLM-judge; đối chiếu EGS | κ, agreement của judge, tương quan EGS | **G3:** chỉ dùng LLM-judge cho T4 khi agreement với tác giả đạt κ ≥ 0,6; không đạt thì T4 chỉ báo metric tự động và ghi rõ |
| **M6 Viết và nộp** | 4/2027 | Viết bài; đóng gói code, nhãn, protocol, hash theo CC BY-NC-SA 4.0; preprint; nộp | Bản nộp | **G4:** gói tái lập chạy lại được từ đầu; giấy phép các bộ nhãn bên thứ ba đã kiểm |
---
@@ -269,10 +286,13 @@ Ngưỡng các cổng chốt trong `protocol_v1` trước G1; sau đó ngưỡng
| `volve_dia/ddr/rendered.py`, `qc.py` | HTML và khối OCR → `Rendered`; so sánh, căn hàng và cột |
| `volve_dia/ocr.py` | Client chandra, page cache, kiểm tra dịch vụ |
| `scripts/00–05`, `run_p0.sh`, `runlog.sh` | Pipeline P0 (README) |
| `tests/` | 40 test; test cần dữ liệu mang marker `data` |
| `volve_dia/ocr_hub.py`, `witsml.py`, `tops.py`, `labels.py`, `t4.py`, `t4_pandas.py`, `audit.py` | Ghép trang OCR từ Dataset Hub về DDR; WITSML; formation tops; nhãn T1–T3; câu hỏi T4 (SQL và pandas độc lập); mẫu audit mù |
| `scripts/04_ocr_hub.py`, `06_parse_witsml.py`, `07_labels.py`, `08_t4_questions.py`, `08_t4_xml_check.py`, `09_audit.py`, `run_m1.sh` | Pipeline M1 (README) |
| `configs/labels.yaml`, `t4_templates.yaml`, `ocr_hub.yaml`, `protocol_v1.yaml` (nháp) | Bảng ánh xạ, 39 template T4, ghép OCR, protocol chưa khóa |
| `tests/` | 141 test (lượt WITSML 17/11); test cần dữ liệu mang marker `data` |
| `docs/technical_overview.md` | Bài giảng cho người mới (cấu trúc theo ML-Porosity): khái niệm, dữ liệu, thiết kế, kết quả, bản đồ code |
Dự kiến [ĐX]: `volve_dia/witsml.py` + `scripts/06_parse_witsml.py`; `volve_dia/labels.py` + `configs/labels.yaml` + `scripts/07_labels.py`; `scripts/08_t4_questions.py`; `scripts/09_audit_sample.py` (mẫu audit mù, che mã); `configs/protocol_v1.yaml` + `.sha256`; script baseline từ 10, driver `run_m*.sh`.
Dự kiến [ĐX]: `protocol_v1.yaml` + `.sha256` (khóa ở G1); script baseline từ 10; driver `run_m*.sh` cho các pha sau.
---
@@ -288,23 +308,25 @@ Reviewer các venue này thường đòi [S]: dữ liệu public; split theo gi
| Rủi ro | Phòng |
| --- | --- |
| Rò rỉ nhãn từ mã hoạt động (PetroAgents 0,355 → 0,431) | Che mã trong input; báo cả hai chế độ |
| Rò rỉ đặc trưng sau sự kiện (repo Anatoly5ms: 53% → 4%) | Chỉ đặc trưng trước thời điểm dự báo; kiểm thủ công |
| Split theo cửa sổ làm điểm cao ảo (Applied Sciences 2025, IPTC-25191) | GroupKFold theo wellbore; nêu rõ trong bài |
| Mã hoạt động không nhất quán giữa supervisor (OTC-36422) | Che mã; audit mù; báo độ khớp với audit và nhãn độc lập; nêu là giới hạn |
| Rò rỉ nhãn từ mã hoạt động (PetroAgents 0,355 → 0,431 trên 30 ví dụ) | Che mã trong input; báo cả hai chế độ |
| Rò rỉ đặc trưng sau sự kiện (repo Anatoly5ms: 53% khoảng dương có đặc trưng dung dịch đo sau khi sự cố bắt đầu, 4% sau khi sửa; đó là tỷ lệ nhiễm, không phải điểm số) | Chỉ đặc trưng trước thời điểm dự báo; kiểm thủ công |
| Split theo cửa sổ làm điểm cao ảo (Applied Sciences 2025; IPTC-25191-MS báo F1 0,993 nhưng tóm tắt nói leave-one-well-out, nguồn điểm gần tuyệt đối chưa rõ [CXM]) | Split theo giếng; nêu rõ trong bài |
| Mã hoạt động không nhất quán giữa supervisor (OTC-36422) | Che mã; LLM rater mù; báo độ khớp với rater và kiểm chéo; nêu là giới hạn |
| Lớp sự cố quá hiếm (mud loss 12, injury 1) | Báo theo lớp kèm CI; gộp lớp theo luật chốt ở G1 |
| WITSML chỉ có 14 wellbore có cả DDR | Tách kết quả DDR-only (26 wellbore) và DDR + WITSML (14 wellbore) |
| WITSML chỉ có 21 wellbore có cả DDR, và chỉ khoảng một nửa NPT định vị được theo độ sâu (50,3% dòng, 44,6% giờ) | Tách kết quả DDR-only (26 wellbore) và DDR + WITSML (21 wellbore); T3 báo riêng |
| LLM rater dùng để kiểm định nhãn trùng huấn luyện và quy ước với baseline LLM | Nhiều họ model, báo κ giữa các rater, nêu giới hạn; thêm người chấm nếu có |
| LLM-judge không hiệu chuẩn | Ngưỡng G3; ưu tiên metric tự động (SQL) cho số liệu |
| Dịch vụ OCR dùng chung bị dừng (đã xảy ra 29/10, mục 12 ý 7) | Cache theo trang, chạy lại để resume; script dừng khi dịch vụ không trả lời và ngừng gửi sau 8 trang lỗi liên tiếp. C4 không chặn C1–C3 |
| Giấy phép Volve CC BY-NC-SA 4.0 [KT `license.txt`] | Phát hành nhãn và code cùng giấy phép; không dùng thương mại |
| PetroAgents hoặc nhóm khác ra bài tạp chí trước | Preprint M4–M5; nhấn kiểm soát rò rỉ, nhãn độc lập, kiểm định EGS, C4 |
| Reviewer đòi nhãn chuyên gia liên người | Nêu giới hạn thẳng; dẫn Bassey 2026; ba lớp kiểm định; phát hành nhãn và script để người khác kiểm lại |
| PetroAgents hoặc nhóm khác ra bài tạp chí trước (đã có hai bài hội nghị ADIPEC 2/11/2026 về hỏi đáp trên DDR Volve) | Preprint M4–M5; nhấn kiểm soát rò rỉ, nhãn có provenance và audit mù, kiểm định EGS, C4; thêm metric nhầm wellbore cho T4 |
| Reviewer đòi nhãn chuyên gia liên người | Nêu giới hạn thẳng; dẫn Bassey 2026 chỉ như tiền lệ phương pháp; ba lớp kiểm định; phát hành nhãn và script để người khác kiểm lại |
---
## 10. Những claim không được viết
- "Expert-labelled", "gold standard", "validated by experts" cho nhãn xác định; gọi audit của tác giả là đồng thuận chuyên gia.
- "Human-audited", "author-audited" hay "manually validated" cho nhãn: việc kiểm định chỉ do LLM rater và kiểm chéo (mục 12 ý 20); điểm của LLM rater không trình bày như điểm của người.
- "First benchmark" hay "first quantitative evaluation" trước khi xong mục 2.3.
- Điểm có mã hoạt động trong input, hoặc split theo cửa sổ, trình bày như kết quả chính.
- Kết quả T3 dùng đặc trưng sau sự kiện.
@@ -313,27 +335,29 @@ Reviewer các venue này thường đòi [S]: dữ liệu public; split theo gi
- LLM-judge "calibrated" khi không có số agreement; EGS "valid" khi chưa đối chiếu với người.
- Số của ta và của PetroAgents trong cùng bảng như cùng protocol.
- Ý nghĩa thống kê từ dưới 3 seed, hoặc CI không tính theo wellbore.
- "Ba bộ nhãn độc lập"; nhãn DrillScribe là nhãn độc lập (nó là phép biến đổi của `stateDetailActivity`); nhãn Bassey là nhãn khoan hay nhãn WITSML (nó là nhãn khai thác theo ngày); độ khớp thống kê với TSPP (n = 3).
- "First quantitative evaluation of LLMs on Volve": đã có hai bài hội nghị ADIPEC về hỏi đáp; gap chỉ phát biểu ở ba điều kiện (kiểm soát rò rỉ, nhãn có provenance, kiểm định nhãn).
- Số điểm trên 1.759 báo cáo từ OCR như từ nguồn; số WITSML, nhãn hay đáp án T4 lấy từ OCR, HTML hay PDF.
- Phát hành lại dữ liệu Volve hay dẫn xuất ngoài điều khoản CC BY-NC-SA 4.0.
---
## 11. Tài liệu
Danh sách chính ở bản đánh giá mục 9. Đọc toàn văn trước M2: PetroAgents (10.20944/preprints202606.1385.v1); Bassey et al. 2026 (arXiv 2608.05685); EAGE 2026 (10.3997/2214-4609.2026101276); OTC-36422. Tải và kiểm giấy phép: DrillScribe, repo Anatoly5ms, dataset OMAE 2024 (arXiv 2503.07440). Khi trích dẫn, dùng skill `citation-management` để lấy metadata và BibTeX.
Danh sách chính ở bản đánh giá mục 9. Ghi chú đọc và BibTeX: `docs/literature_notes.md`, `docs/references.bib` (17/11/2026). Đã đọc toàn văn: Bassey et al. 2026 (arXiv 2608.05685) và Cao et al. 2025 (arXiv 2503.07440, Crossformer); đã tải và đối chiếu với dữ liệu: DrillScribe, repo Anatoly5ms, bộ TSPP. Hai bài khác nhau, không gộp: OMAE2024-128386 (Cao, Song, Xu, Peng; bộ dữ liệu, chỉ đọc tóm tắt) và arXiv 2503.07440 (Cao, Song, Yang, Li; phương pháp). Đã đọc toàn văn PetroAgents (10.20944/preprints202606.1385.v1; người dùng tải tay vào `docs/lit_petroagents.pdf`). Còn phải lấy toàn văn: EAGE 2026 (DOI 10.3997/2214-4609.2026101276 chưa phân giải), OTC-36422-MS, SPE-236554-MS, SPE-235330-MS, IPTC-25191-MS. Khi trích dẫn, dùng skill `citation-management` để lấy metadata và BibTeX.
---
## 12. Việc làm ngay và nhật ký quyết định
1. **Hai tuần tới (đến 12/11/2026):**
1. (Người dùng) Trình lãnh đạo Ban lựa chọn Ý tưởng 1 và lý do FWI không khả thi trên dữ liệu public (bản đánh giá mục 4).
2. Chạy OCR toàn bộ khi dịch vụ chạy lại (ý 7); QC toàn tập; cập nhật mục 1.3.
3. Đọc toàn văn PetroAgents, Bassey 2026, EAGE 2026101276. Tải DrillScribe, repo Anatoly5ms, dataset OMAE 2024.
4. Parser WITSML. Kiểm `15/9-F-15 S` so với `15/9-F-15` và báo cáo `15_9_19_A_1980_01_01`. Tìm nguồn formation tops và thêm vào manifest [XM].
5. Bảng ánh xạ mã → nhãn, gồm luật điền pha khi thiếu `diaHole` (mục 1.2); tự chấm mù 100 dòng để ước lượng độ khớp của nhãn xác định và thời gian chấm mỗi dòng.
6. Bản nháp `protocol_v1` (chỉ khóa ở G1), gồm lựa chọn nhóm split theo wellbore hay theo giếng (mục 4.5).
1. **Việc tiếp theo (từ 17/11/2026):**
1. Audit thử 100 dòng đã được LLM rater chấm (`RATINGS_llm_sonnet.csv`, mục 12 ý 16); tác giả chưa chấm, nên chưa có thời gian mỗi dòng của người. Audit 1 (M2) cần người chấm nếu muốn gọi là audit của tác giả.
2. (Xong 17/11) PDF PetroAgents đã được người dùng tải và đã đọc toàn văn.
3. 16 trang lệch ngày và 7 trang chưa ghép của OCR hub: đã quyết định ở mục 12 ý 21.
4. Rà `protocol_v1` (bản nháp) cùng điểm chấm thử của LLM rater; lên lịch chấm mù 300 dòng bằng ≥ 3 LLM rater (M2).
5. Các quyết định còn mở đã chốt ở mục 12 ý 21.
2. **29/10/2026: chọn hướng.** Ý tưởng 1 trên Volve, không chọn AI-FWI (bản đánh giá mục 1, 4).
3. **29/10/2026: khung project theo ML-Porosity.** Package `volve_dia`, script đánh số, `runlog` (log và runtime cho mọi lần chạy, `logs/index.csv`); manifest SHA-256 kiểm bằng `--check`; `data/Volve` symlink tới dữ liệu của ML-Porosity, không tải lại; pytest với marker `data`; driver `run_p0.sh`; tài liệu `AGENTS.md`, `README.md`, kế hoạch này, `report.html`.
3. **29/10/2026: khung project theo ML-Porosity.** Package `volve_dia`, script đánh số, `runlog` (log và runtime cho mọi lần chạy, `logs/index.csv`); manifest SHA-256 kiểm bằng `--check`; `data/Volve` lúc đó là symlink tới dữ liệu của ML-Porosity (nay là thư mục thật, ý 18); pytest với marker `data`; driver `run_p0.sh`; tài liệu `AGENTS.md`, `README.md`, kế hoạch này, `report.html`.
4. **29/10/2026: parser.** Nhãn lấy từ XML (`ddr/xml.py`): giữ tên phần tử WITSML làm tên cột; sentinel và đơn vị được đếm, không đổi âm thầm. Theo yêu cầu, parser tài liệu là chandra trên dịch vụ vLLM với request và prompt giống hệt vopec-chatbot (`configs/ocr.yaml`). Vì đã có XML, OCR dùng để đo C4, không để dựng nhãn.
5. **29/10/2026: QC bản in.** HTML in đúng XML trừ Tight well và HPHT, sai ở cả 1.759 báo cáo (mục 1.3). Hai cờ này chỉ lấy từ XML.
6. **29/10/2026: OCR pilot và QC OCR.** QC ban đầu: CER nội dung 6,85%, khớp tuyệt đối 0,9171; phần lớn sai lệch là cấu trúc mà parser chưa hoàn tác. Sau khi sửa parser và luật QC: CER 2,50%, khớp 0,9234; header CER 46% → 0,78%, khớp 0,54 → 0,96; ô Operations CER 8,5% → 3,12%.
@@ -347,3 +371,26 @@ Danh sách chính ở bản đánh giá mục 9. Đọc toàn văn trước M2:
- `bits.bitRun_ropAv` là nguồn ROP thứ ba cho T4, bên cạnh `distDrill` và WITSML.
- 26 wellbore thuộc 11 giếng: chưa chốt nhóm split theo wellbore hay theo giếng [XM].
10. **29/10/2026: đổi tên thư mục và commit đầu tiên.** Thư mục project đổi từ `Scientific` thành `Volve-DIA` (`/home/jovyan/lamlvh/Volve-DIA`); đường dẫn trong `.venv` sửa theo tên mới. Commit đầu tiên trên `main`, identity `lamlvh` như ML-Porosity; đã push lên remote `origin` `https://gitea.vts-ai.space/lamlvh/Volve-DIA`. Repo này **public**, nên `docs/danh-gia-huong-NCKH-2026-10-29.md` (trích tài liệu nội bộ `docs/NCKH_Ban TD.DOCX`) được gitignore và không có trong lịch sử git; các nhắc tới Ban Thăm dò/PVEP trong plan, overview và report vẫn giữ. Đường dẫn cũ trong `logs/index.csv` giữ nguyên vì là bản ghi lịch sử.
11. **29/10/2026: kiểm điều kiện bắt đầu M1.** M1 bắt đầu được theo lịch (30/10); chỉ việc OCR toàn bộ còn bị chặn.
- Dịch vụ OCR: lúc 13:04 vẫn trả 503 (kiểm bằng `ocr.check_service`, không gửi trang nào). Người dùng cần nhờ khởi động lại pod.
- Dữ liệu: `00_data_manifest.py --check` đạt, 25.570 file, không thiếu, không lệch hash (lượt `20261029-130503_m1_readiness_manifest`). Bộ test: 40 test đạt (lượt `20261029-130517_m1_readiness_pytest`; lượt `20261029-130513` trước đó thất bại exit 127 vì gọi runlog thiếu đường dẫn python, không phải lỗi code).
- WITSML có đủ các loại object cho parser: thư mục `log` ở 33 nơi, `trajectory` 29, `message` 17, `bhaRun` 14, `mudLog` 8; 18.814 file XML. `lxml` chưa cài; parser DDR dùng `xml.etree`, đủ cho WITSML (`iterparse`).
- Formation tops tìm thấy: `Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat`, 409 pick trên 35 wellbore (mục 4.1).
- Mạng ra ngoài thông (GitHub, Hugging Face, PyPI, doi.org), nên tải được DrillScribe, repo Anatoly5ms, dataset OMAE 2024.
- Tài nguyên máy dùng chung: `/home` dùng 98%, còn 274 GB (đủ cho bảng WITSML, phải theo dõi); load 57 trên 40 lõi; hai GPU H200 gần đầy bộ nhớ do job khác. M1 không cần GPU; M3 sẽ cần.
12. **17/11/2026: OCR toàn tập qua Dataset Hub.** Một đồng nghiệp chạy OCR và xuất COCO; export không ghi tên file nên ghép trang bằng nội dung (mục 1.3). Lượt cuối `20261117-021745_ocr_hub_import` (23,6 phút): 3.059/3.066 trang, 1.752/1.759 báo cáo. Lượt đầu ghép nhầm 3 trang và bỏ kiểm ngày trên trang chưa ghép; đã sửa (sàn F1 chữ 0,7, kiểm ngày chỉ trên trang đã ghép). QC trên bản hub (`20261117-024203_ocr_qc_hub`): CER 2,40%, khớp 0,9181. URL, dataset id và khóa API chỉ nằm trong `.env`, không có trong file commit hay lệnh runlog.
13. **17/11/2026: sửa phạm vi QC bản in.** `03` chỉ phủ header, 31 trường, tóm tắt và Operations; thêm lỗi render Bit Record (mục 1.3).
14. **17/11/2026: WITSML.** Parser `06_parse_witsml.py` (lượt `20261117-024309_06_parse_witsml`, 246 s): 21 wellbore DDR có log thời gian (không phải 14), 1.384 báo cáo (không phải 964); `15/9-F-15 S` là DDR F-15, và hai wellbore WITSML khác lệch tên một bậc (mục 1.1). Việc giao cho một agent con; số liệu trong mục này là báo cáo của agent, đã khóa trong `EXPECTED` và 30 test.
15. **17/11/2026: nhãn T1–T3 và `protocol_v1` nháp.** `labels.yaml` (mục 4.3). Quyết định trong bản nháp: split theo giếng, leave-one-well-out, hai giếng phát triển F-7 và F-9; NPT a (chỉ interruption) và b (hợp) cùng được tạo, chọn chính bằng κ của audit 1, mặc định a khi |Δκ| < 0,02; lớp chấm riêng chỉ khi ≥ 3 giếng có ≥ 5 mục; sidetrack ra khỏi đích nguyên nhân nhưng vẫn là NPT nhị phân. Chưa khóa; khóa ở G1.
16. **17/11/2026: T4 và audit thử.** 1.662 câu hỏi, ba cách tính đáp án khớp 100% (mục 4.3). Mẫu audit thử 100 dòng (SEED 20261117; 35 vùng a, 15 vùng b_only, 50 vùng none; 23 wellbore, 11 giếng). Điểm này do một **LLM rater (Sonnet, mù, chỉ đọc view đã che mã)** chấm, **không phải audit của tác giả**; không dùng làm nhãn, không báo như audit của tác giả. Kết quả (`score.json`, 100 dòng, κ có trọng số theo dân số): NPT (a) κ 0,553, NPT (b) κ 0,564, nhóm nguyên nhân (a) κ 0,476, loại thao tác κ 0,434 (65 dòng); độ khớp thô NPT 0,77 và 0,78. Chưa đạt κ ≥ 0,6 của G1, nhưng người chấm là LLM nên không kết luận gì về nhãn; κ theo vùng bằng 0 vì mỗi vùng gần như một lớp. Audit 1 của M2 vẫn cần người chấm nếu muốn gọi là audit của tác giả.
17. **17/11/2026: tài liệu và bộ nhãn bên thứ ba** (`docs/literature_notes.md`, `references.bib`): không bộ nhãn công khai nào là nhãn NPT khoan độc lập; lớp hai của mục 4.4 viết lại; bổ sung đối thủ (mục 2.2). Đã tải DrillScribe, Anatoly5ms, TSPP vào `data/third_party/` (không commit).
18. **17/11/2026: dữ liệu.** `data/Volve` giờ là thư mục thật (không còn symlink); `/home` còn 75 GB (98%); manifest thành 25.571 file (thêm formation tops), kiểm `--check` đạt.
19. **17/11/2026: phân công agent.** Từ nay chỉ dùng Sonnet cho việc giao agent, Opus cho việc rất phức tạp; không dùng Fable.
20. **17/11/2026: C2 bỏ audit của tác giả, dùng LLM rater mù.** Không có người chấm. Quyết định (người dùng): kiểm định nhãn bằng nhiều LLM rater mù thuộc họ model khác nhau (Sonnet, Opus, Haiku ở bản thử; thêm model open-weight ở M2), báo κ của từng rater với nhãn code và κ giữa các rater, cộng ba kiểm chéo (mục 4.4). Không gọi là audit của tác giả, audit chuyên gia hay nhãn được kiểm bởi chuyên gia (mục 10). Hệ quả: ngưỡng G1 κ ≥ 0,6 áp cho trung vị theo rater; bài ghi "không có người chấm" là giới hạn; rủi ro mới là LLM rater trùng huấn luyện với baseline LLM (mục 9). Đã sửa `protocol_v1` (`validation.llm_raters`).
21. **17/11/2026: LLM rater, bản thử ba model, và các quyết định còn mở.**
- **Bản thử** (100 dòng, Sonnet, Opus, Haiku; `scripts/09_rater_agreement.py`, `outputs/audit/trial_100/raters.json`). κ có trọng số với nhãn code: NPT (a) 0,553 / 0,584 / 0,529 (Sonnet / Opus / Haiku), NPT (b) 0,564 / 0,683 / 0,574; nhóm nguyên nhân (a) 0,476 / 0,448 / 0,456; loại thao tác 0,434 / 0,624 / 0,389. Giữa các rater: Fleiss NPT 0,662, nguyên nhân 0,644, loại thao tác 0,662; từng cặp NPT 0,58–0,71. Các LLM đồng thuận với nhau hơn với nhãn code, nên phần lệch với code là có hệ thống; nên đọc `disagreements.csv`. Trung vị theo rater: NPT (a) 0,553, (b) 0,574 (chênh 0,021, qua ngưỡng 0,02, nên theo luật đã định sẽ chọn (b)); chưa kết luận vì cỡ mẫu 100 và còn 3 rater, quyết định ở M2 trên 300 dòng. Chưa đạt κ ≥ 0,6 cho cả hai định nghĩa NPT; nhóm nguyên nhân (a) chỉ 0,45–0,48 ở cả ba rater, nên lớp nguyên nhân cần gộp nhiều.
- **Giá trị đáng ngờ của WITSML:** giữ nguyên trong bảng (provenance); ở bước đặc trưng coi −999, −99999, 99999, 9999 và |v| > 1e15 là thiếu. Căn cứ (`log_suspects`): −999 là chỗ giữ của kênh MWD (MWD_FRM, MWD_ID, MWD_POS, MWD_VAL: 224.841 giá trị), 99999 chủ yếu ở ANNVEL_MMIN (279.676 trong 279.866), 9999 chỉ ở kênh đếm thời gian (OFFBOTTOM_TIME, ROT_TIME, RUNCIRC), giá trị cực lớn ở RETI, SPPA, TQA là lỗi cảm biến. Ghi vào `protocol_v1` (`witsml_features.treat_as_missing`).
- **Pick lệch xa `stratInfo`:** giữ file pick làm nguồn nhãn formation (nhất quán, một nguồn); `stratInfo` của DDR chỉ để kiểm chéo. 33/130 pick lệch quá 5 m, tập trung ở F-10 (5), F-14, F-1 C, F-12; 3 ngoại lệ lớn nhất (−1.093, −1.089, −744 m) đều có hai giá trị khác nhau trong DDR cho cùng tầng (ví dụ F-1 C Hordaland 2.162 và 1.364 m), nên khác biệt đến từ chính `stratInfo` (nhập nhiều lần, chưa phân biệt dự báo hay thực tế) chứ chưa chứng tỏ pick sai. Chưa kiểm từng pick.
- **TD của F-15:** dùng DDR và WITSML (4.090 m, khớp nhau); số 4.105 m của NPD đọc bằng regex từ HTML nên chỉ là tham khảo; không ảnh hưởng nhãn. Ghi như một chênh lệch chưa giải thích.
- **OCR hub:** giữ 3.059 trang đã ghép; 7 báo cáo chưa đủ trang bị loại khỏi QC và khỏi thí nghiệm C4, không OCR lại (0,4% số báo cáo, chi phí không đáng); 16 trang lệch ngày được giữ và gắn cờ, thí nghiệm C4 báo kết quả có và không có chúng.
- **PetroAgents:** đã đọc toàn văn; đơn vị là well-day, mẫu nhỏ, split theo wellbore (mục 2.2). Không đặt số của hai bên chung bảng.

251
docs/references.bib Normal file
View File

@@ -0,0 +1,251 @@
% Volve-DIA reference list.
% Every entry below was resolved on 17 Nov 2026 by DOI content negotiation (doi.org, Accept: application/x-bibtex;
% the method of .agents/skills/citation-management/scripts/doi_to_bibtex.py) and checked against the Crossref or
% DataCite record. Entries without a DOI (code repositories, data releases) were checked against the hosting API.
% Notes on what was read are in docs/literature_notes.md.
@misc{lu2026petroagents,
author = {Lu, Rong},
title = {{PetroAgents}: A Multi-Agent, Multi-Modal Large-Language-Model Framework for Integrated Upstream
Petroleum Asset Reasoning, Benchmarked on the {Equinor} {Volve} Open Dataset},
year = {2026},
month = jun,
publisher = {MDPI AG},
howpublished = {Preprints.org},
doi = {10.20944/preprints202606.1385.v1},
note = {Preprint, version 1, posted 18 June 2026; not peer reviewed}
}
@misc{lu2026tadi,
author = {Lu, Rong},
title = {{TADI}: Tool-Augmented Drilling Intelligence via Agentic {LLM} Orchestration over Heterogeneous
Wellsite Data},
year = {2026},
publisher = {arXiv},
eprint = {2605.00060},
archivePrefix = {arXiv},
doi = {10.48550/arXiv.2605.00060},
note = {Also posted as Preprints.org 10.20944/preprints202604.1820.v1}
}
@misc{bassey2026grounded,
author = {Bassey, Gospel and Bassey, Samuel and Fakiyesi, Vincent},
title = {Grounded Well-Condition Anomaly Detection on the {Volve} Field: Constructed Labels, a Baseline, and a
Dual-Head Model},
year = {2026},
publisher = {arXiv},
eprint = {2608.05685},
archivePrefix = {arXiv},
primaryClass = {cs.AI},
doi = {10.48550/arXiv.2608.05685},
note = {Version 2, 12 August 2026}
}
@misc{bassey2026release,
author = {Bassey, Gospel},
title = {Grounded Anomaly Detection on the {Volve} Field: Dataset, Labels, and Models},
year = {2026},
howpublished = {Hugging Face repository \texttt{gospelgit/Anomaly\_Detection\_with\_Volve}},
url = {https://huggingface.co/gospelgit/Anomaly_Detection_with_Volve},
note = {Revision 75265537efde, 29 July 2026; CC BY-NC-SA 4.0}
}
@inproceedings{cao2024tspp,
author = {Cao, Bo and Song, Yu and Xu, Feng and Peng, Fukang},
title = {Development of Time Series Drilling Datasets for Stuck Pipe Prediction Using {Volve} Field Data},
booktitle = {Proceedings of the ASME 2024 43rd International Conference on Ocean, Offshore and Arctic Engineering.
Volume 8: Offshore Geotechnics; Petroleum Technology},
year = {2024},
month = jun,
publisher = {American Society of Mechanical Engineers},
doi = {10.1115/OMAE2024-128386},
note = {Paper OMAE2024-128386. The Crossref record lists given and family names in swapped order; the order
used here follows arXiv:2503.07440 by the same first authors}
}
@misc{cao2025crossformer,
author = {Cao, Bo and Song, Yu and Yang, Jin and Li, Lei},
title = {Early signs of stuck pipe detection based on {Crossformer}},
year = {2025},
publisher = {arXiv},
eprint = {2503.07440},
archivePrefix = {arXiv},
primaryClass = {cs.CE},
doi = {10.48550/arXiv.2503.07440}
}
@misc{cao2023tsppdata,
author = {Cao, Bo and others},
title = {Time-series-stuck-pipe-prediction ({TSPP}) dataset},
year = {2023},
howpublished = {GitHub repository \texttt{promiseeee/Time-series-stuck-pipe-prediction}},
url = {https://github.com/promiseeee/Time-series-stuck-pipe-prediction},
note = {Commit 1297d8b, 23 October 2023; no licence file. The repository names no author; it is attributed
here through the abstract of OMAE2024-128386 and Section 2.2 of arXiv:2503.07440, which give this URL}
}
@inproceedings{idrus2026cognitive,
author = {Idrus, S. Syed and Haikal, A. and Rahman, M. Abd and Zahid, A. and Redzuan, A. Ahmad and Isa, S. Mat and
Effendi, S. Mohd and Idris, M. and Parmar, H. and Singh, M. and Kiran, S.},
title = {Cognitive Drilling {AI}: Transforming Activity Logs into Actionable Insights},
booktitle = {Offshore Technology Conference Asia},
year = {2026},
month = mar,
publisher = {OTC},
doi = {10.4043/36422-MS},
note = {Paper OTC-36422-MS}
}
@inproceedings{boden2025rag,
author = {Boden, J. and Eckroth, J. and Gipson, S. and Myers, K. and Smith, R. and Schoen, E. and Keefe, J. and
Sequeira, P.},
title = {Building an Intelligent Research Assistant -- {RAG} Isn't All You Need},
booktitle = {SPE Annual Technical Conference and Exhibition},
year = {2025},
month = oct,
publisher = {SPE},
doi = {10.2118/228117-MS},
note = {Paper SPE-228117-MS}
}
@inproceedings{hussain2026similarity,
author = {Hussain, Syed Aaquib and Reddy, Babu Sai Sampath},
title = {When Similarity is Not Enough: Deterministic Retrieval Pathways for Wellbore-Accurate Knowledge
Synthesis on the {Volve} Field},
booktitle = {ADIPEC},
year = {2026},
month = nov,
publisher = {SPE},
doi = {10.2118/236554-MS},
note = {Paper SPE-236554-MS}
}
@inproceedings{bihani2026knowledge,
author = {Bihani, Anurag and Manikani, Sunil and Arabi, Hakim and Liu, Minyue},
title = {Knowledge Organization Matters: How Graph Design and Temporal Structure Shape Agentic {AI} Performance
on Drilling Activity Reports},
booktitle = {ADIPEC},
year = {2026},
month = nov,
publisher = {SPE},
doi = {10.2118/235330-MS},
note = {Paper SPE-235330-MS}
}
@inproceedings{mbamarah2026hierarchical,
author = {Mbamarah, Julia and Iyalla, Ibiye and Innocent, Prince},
title = {Hierarchical Phase-Adaptive Machine Learning Framework for Real-Time Non-Productive Time Prediction in
Offshore Drilling},
booktitle = {SPE Annual Technical Conference and Exhibition},
year = {2026},
month = oct,
publisher = {SPE},
doi = {10.2118/237272-STU},
note = {Paper SPE-237272-STU}
}
@inproceedings{joshi2025unified,
author = {Joshi, Amod and Singh, Vikas and Sutar, Suhel},
title = {A Unified Agentic and Generative {AI} Framework for Enhancing Drilling Intelligence Through {WITSML}
and Unstructured Data (pdfs) Interaction},
booktitle = {ADIPEC},
year = {2025},
month = nov,
publisher = {SPE},
doi = {10.2118/229435-MS},
note = {Paper SPE-229435-MS}
}
@inproceedings{abaalharith2026hybrid,
author = {Abaalharith, S. and Rachman, B. and Zumarah, B. and Otaibi, B.},
title = {Hybrid {AI} Framework for Predicting Geomechanical Risks and Hole Instability During Well Planning},
booktitle = {IPTC Summit on AI for the Energy Industry},
year = {2026},
month = jan,
publisher = {IPTC},
doi = {10.2523/IPTC-25191-MS},
note = {Paper IPTC-25191-MS}
}
@article{almamoori2025stuck,
author = {Al-Mamoori, Hasan N. and Tian, Jialin and Ma, Haifeng},
title = {Stuck Pipe Detection in Oil and Gas Drilling Operations Using Deep Learning Autoencoder for Anomaly
Diagnosis},
journal = {Applied Sciences},
year = {2025},
volume = {15},
number = {9},
pages = {5042},
doi = {10.3390/app15095042}
}
@inproceedings{cunedioglu2026practical,
author = {Cunedioglu, Y. and Baldino, S. and Ozbayoglu, M. E.},
title = {Practical, Rule-Based Approach for Real-Time Stand and Rig Activity Detection; A Complementary Tool to
Rig-State Identification},
booktitle = {SPE Europe Energy Conference and Exhibition},
year = {2026},
month = jun,
publisher = {SPE},
doi = {10.2118/233220-MS},
note = {Paper SPE-233220-MS}
}
@inproceedings{shah2026drillbench,
author = {Shah, A. and Jamal, M. and Wu, X. and Fu, X. and Chen, J.},
title = {{DrillBench}: A Sequential Decision-Making Benchmark for Drilling Operations with Cross-Stage Agent
Feedback},
booktitle = {SPE Annual Technical Conference and Exhibition},
year = {2026},
month = oct,
publisher = {SPE},
doi = {10.2118/234135-MS},
note = {Paper SPE-234135-MS}
}
@misc{wang2026petrobench,
author = {Wang, Xiang and Zhang, Tingting and Wang, Sen and Wu, Ying and Meng, Heng and Zhou, Peng and Li, Peng},
title = {{PetroBench}: A Benchmark for Large Language Models in Petroleum Engineering},
year = {2026},
publisher = {arXiv},
eprint = {2605.28032},
archivePrefix = {arXiv},
doi = {10.48550/arXiv.2605.28032}
}
@misc{paul2026drillscribe,
author = {Paul, Chinmoy},
title = {{DrillScribe}: Turning daily drilling reports into a non-productive-time ledger},
year = {2026},
howpublished = {GitHub repository \texttt{chinmoypaul8897/drillscribe}},
url = {https://github.com/chinmoypaul8897/drillscribe},
note = {Commit 0abca00, 7 August 2026; code under the MIT licence; not a peer-reviewed publication}
}
@misc{grigorovich2026complication,
author = {Grigorovich, Anatolii},
title = {Drilling Complication Prognostication},
year = {2026},
howpublished = {GitHub repository \texttt{Anatoly5ms/drilling\_complication\_prognostication}},
url = {https://github.com/Anatoly5ms/drilling_complication_prognostication},
note = {Commit a0e16ed, 19 October 2026; MIT licence; not a peer-reviewed publication}
}
@misc{equinor2018volve,
author = {{Equinor}},
title = {Volve field data set},
year = {2018},
howpublished = {Equinor open data},
note = {Data owners: Equinor, ExxonMobil, Bayerngas and the Norwegian Petroleum Directorate; licence
CC BY-NC-SA 4.0 as stated in the license.txt shipped with the data}
}
% --- Not fully verified: do not cite before the missing fields are confirmed ---------------------------------
% EAGE 2026: "From Field Logs to Actionable Insights: A Multi-Agent LLM Approach for Factual Summarization of
% Drilling Operations", 87th EAGE Annual Conference & Exhibition, June 2026,
% https://www.earthdoc.org/content/papers/10.3997/2214-4609.2026101276
% Title and venue from a web-search snippet of the EarthDoc page; authors NOT obtained; the DOI
% 10.3997/2214-4609.2026101276 did not resolve at doi.org and was absent from Crossref on 17 Nov 2026.
% ICML 2026 workshop: Mishra, A., Buiting, S., Sengupta, S., Benzine, A., "From Time-Series to Text: Multimodal and
% Agentic Approaches for Automated Drilling Report Generation", Workshop on Foundation Models for Structured Data,
% ICML 2026, https://openreview.net/forum?id=X1s2qN24kX (metadata from the icml.cc virtual page only).

File diff suppressed because it is too large Load Diff

View File

@@ -25,3 +25,35 @@ run_id,parent,name,status,exit_code,start,end,wall_s,wall,device,git,dirty,code_
20261029-105934_p0/06_05_ocr_qc,20261029-105934_p0,05_ocr_qc,ok,0,2026-10-29T11:02:28+00:00,2026-10-29T11:02:35+00:00,7.6,0:00:08,,,False,78ad01e2c88d637d,runlog,.venv/bin/python scripts/05_ocr_qc.py
20261029-105934_p0/07_pytest,20261029-105934_p0,pytest,ok,0,2026-10-29T11:02:36+00:00,2026-10-29T11:02:51+00:00,15.3,0:00:15,,,False,78ad01e2c88d637d,runlog,.venv/bin/python -m pytest -q
20261029-105934_p0,,p0,ok,0,2026-10-29T10:59:34+00:00,2026-10-29T11:02:52+00:00,197.6,0:03:18,,,False,78ad01e2c88d637d,runlog,bash scripts/run_p0.sh
20261029-130503_m1_readiness_manifest,,m1_readiness_manifest,ok,0,2026-10-29T13:05:03+00:00,2026-10-29T13:05:12+00:00,9.2,0:00:09,,a3c175638f7a,False,78ad01e2c88d637d,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
20261029-130513_m1_readiness_pytest,,m1_readiness_pytest,failed,127,2026-10-29T13:05:13+00:00,2026-10-29T13:05:13+00:00,0.1,0:00:00,,a3c175638f7a,True,78ad01e2c88d637d,runlog,-m pytest -q
20261029-130517_m1_readiness_pytest,,m1_readiness_pytest,ok,0,2026-10-29T13:05:17+00:00,2026-10-29T13:05:21+00:00,4.2,0:00:04,,a3c175638f7a,True,78ad01e2c88d637d,runlog,.venv/bin/python -m pytest -q
20261117-015603_m1_manifest_check,,m1_manifest_check,ok,0,2026-11-17T01:56:03+00:00,2026-11-17T01:56:11+00:00,7.3,0:00:07,,a3c175638f7a,True,3ebe94262011224b,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
20261117-015354_ocr_hub_import,,ocr_hub_import,ok,0,2026-11-17T01:53:54+00:00,2026-11-17T01:58:45+00:00,291.3,0:04:51,,a3c175638f7a,True,8b1e2eece6433379,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/04_ocr_hub.py
20261117-020356_ocr_hub_import,,ocr_hub_import,ok,0,2026-11-17T02:03:56+00:00,2026-11-17T02:14:26+00:00,629.3,0:10:29,,a3c175638f7a,True,e54053baa48c8a6a,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/04_ocr_hub.py
20261117-021300_07_labels,,07_labels,ok,0,2026-11-17T02:13:00+00:00,2026-11-17T02:14:29+00:00,88.3,0:01:28,,a3c175638f7a,True,d99df45cecf82683,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/07_labels.py
20261117-021439_t4_questions,,t4_questions,ok,0,2026-11-17T02:14:39+00:00,2026-11-17T02:15:29+00:00,49.5,0:00:49,,a3c175638f7a,True,cb3eac2541da84a5,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/08_t4_questions.py
20261117-022043_audit_sample,,audit_sample,failed,1,2026-11-17T02:20:43+00:00,2026-11-17T02:20:46+00:00,3.0,0:00:03,,a3c175638f7a,True,e11b1ae5dab367e3,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_audit.py sample
20261117-022050_audit_sample,,audit_sample,ok,0,2026-11-17T02:20:50+00:00,2026-11-17T02:20:59+00:00,9.4,0:00:09,,a3c175638f7a,True,8bdbbd74f2a2265e,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_audit.py sample
20261117-022208_t4_xml_check,,t4_xml_check,ok,0,2026-11-17T02:22:08+00:00,2026-11-17T02:22:12+00:00,3.3,0:00:03,,a3c175638f7a,True,238be83fc45a6fe6,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/08_t4_xml_check.py
20261117-022534_data_manifest_tops,,data_manifest_tops,ok,0,2026-11-17T02:25:34+00:00,2026-11-17T02:25:46+00:00,11.3,0:00:11,,a3c175638f7a,True,05ad2462bb031e2c,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py
20261117-022546_data_manifest_check,,data_manifest_check,ok,0,2026-11-17T02:25:46+00:00,2026-11-17T02:25:57+00:00,10.7,0:00:11,,a3c175638f7a,True,05ad2462bb031e2c,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
20261117-022606_06_parse_witsml,,06_parse_witsml,ok,0,2026-11-17T02:26:06+00:00,2026-11-17T02:31:39+00:00,333.0,0:05:33,,a3c175638f7a,True,05ad2462bb031e2c,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
20261117-023529_06_parse_witsml,,06_parse_witsml,ok,0,2026-11-17T02:35:29+00:00,2026-11-17T02:39:39+00:00,250.4,0:04:10,,a3c175638f7a,True,7a4dec250d344f0e,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
20261117-021745_ocr_hub_import,,ocr_hub_import,ok,0,2026-11-17T02:17:45+00:00,2026-11-17T02:41:22+00:00,1417.0,0:23:37,,a3c175638f7a,True,da0858f91c7aed66,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/04_ocr_hub.py
20261117-024203_ocr_qc_hub,,ocr_qc_hub,ok,0,2026-11-17T02:42:03+00:00,2026-11-17T02:42:38+00:00,35.1,0:00:35,,a3c175638f7a,True,0716b5f22173d6af,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/05_ocr_qc.py --source hub
20261117-024238_06_parse_witsml,,06_parse_witsml,interrupted,-15,2026-11-17T02:42:38+00:00,2026-11-17T02:42:49+00:00,11.1,0:00:11,,a3c175638f7a,True,b4a9f951f6ca9328,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
20261117-024309_06_parse_witsml,,06_parse_witsml,ok,0,2026-11-17T02:43:09+00:00,2026-11-17T02:47:15+00:00,246.3,0:04:06,,a3c175638f7a,True,12f02c5b0342f780,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
20261117-024813_data_manifest_check,,data_manifest_check,ok,0,2026-11-17T02:48:13+00:00,2026-11-17T02:48:23+00:00,10.9,0:00:11,,a3c175638f7a,True,12f02c5b0342f780,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
20261117-073525_m1_pytest,,m1_pytest,ok,0,2026-11-17T07:35:25+00:00,2026-11-17T07:36:05+00:00,39.8,0:00:40,,a3c175638f7a,True,12f02c5b0342f780,runlog,.venv/bin/python -m pytest -q
20261117-074344_audit_score_llm,,audit_score_llm,ok,0,2026-11-17T07:43:44+00:00,2026-11-17T07:43:45+00:00,0.7,0:00:01,,a3c175638f7a,True,12f02c5b0342f780,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_audit.py score outputs/audit/trial_100/RATINGS_llm_sonnet.csv
20261117-074954_rater_agreement,,rater_agreement,ok,0,2026-11-17T07:49:54+00:00,2026-11-17T07:49:55+00:00,1.2,0:00:01,,a3c175638f7a,True,9be27c5e57dab3f1,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_rater_agreement.py
20261117-080811_m1/01_04_ocr_hub,20261117-080811_m1,04_ocr_hub,ok,0,2026-11-17T08:08:11+00:00,2026-11-17T08:17:32+00:00,561.1,0:09:21,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/04_ocr_hub.py
20261117-080811_m1/02_05_ocr_qc,20261117-080811_m1,05_ocr_qc,ok,0,2026-11-17T08:17:32+00:00,2026-11-17T08:18:06+00:00,33.7,0:00:34,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/05_ocr_qc.py --source hub
20261117-080811_m1/03_06_parse_witsml,20261117-080811_m1,06_parse_witsml,ok,0,2026-11-17T08:18:06+00:00,2026-11-17T08:23:48+00:00,341.7,0:05:42,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/06_parse_witsml.py --workers 4
20261117-080811_m1/04_07_labels,20261117-080811_m1,07_labels,ok,0,2026-11-17T08:23:48+00:00,2026-11-17T08:24:37+00:00,49.7,0:00:50,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/07_labels.py
20261117-080811_m1/05_08_t4_questions,20261117-080811_m1,08_t4_questions,ok,0,2026-11-17T08:24:37+00:00,2026-11-17T08:25:03+00:00,25.3,0:00:25,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/08_t4_questions.py
20261117-080811_m1/06_08_t4_xml_check,20261117-080811_m1,08_t4_xml_check,ok,0,2026-11-17T08:25:03+00:00,2026-11-17T08:25:05+00:00,2.4,0:00:02,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/08_t4_xml_check.py
20261117-080811_m1/07_09_audit,20261117-080811_m1,09_audit,ok,0,2026-11-17T08:25:05+00:00,2026-11-17T08:25:06+00:00,1.0,0:00:01,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python scripts/09_audit.py sample
20261117-080811_m1/08_pytest,20261117-080811_m1,pytest,failed,1,2026-11-17T08:25:06+00:00,2026-11-17T08:25:46+00:00,39.8,0:00:40,,a3c175638f7a,True,8096b532470ce38b,runlog,.venv/bin/python -m pytest -q
20261117-080811_m1,,m1,failed,1,2026-11-17T08:08:11+00:00,2026-11-17T08:25:46+00:00,1055.5,0:17:35,,a3c175638f7a,True,8096b532470ce38b,runlog,bash scripts/run_m1.sh
1 run_id parent name status exit_code start end wall_s wall device git dirty code_sha source cmd
25 20261029-105934_p0/06_05_ocr_qc 20261029-105934_p0 05_ocr_qc ok 0 2026-10-29T11:02:28+00:00 2026-10-29T11:02:35+00:00 7.6 0:00:08 False 78ad01e2c88d637d runlog .venv/bin/python scripts/05_ocr_qc.py
26 20261029-105934_p0/07_pytest 20261029-105934_p0 pytest ok 0 2026-10-29T11:02:36+00:00 2026-10-29T11:02:51+00:00 15.3 0:00:15 False 78ad01e2c88d637d runlog .venv/bin/python -m pytest -q
27 20261029-105934_p0 p0 ok 0 2026-10-29T10:59:34+00:00 2026-10-29T11:02:52+00:00 197.6 0:03:18 False 78ad01e2c88d637d runlog bash scripts/run_p0.sh
28 20261029-130503_m1_readiness_manifest m1_readiness_manifest ok 0 2026-10-29T13:05:03+00:00 2026-10-29T13:05:12+00:00 9.2 0:00:09 a3c175638f7a False 78ad01e2c88d637d runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
29 20261029-130513_m1_readiness_pytest m1_readiness_pytest failed 127 2026-10-29T13:05:13+00:00 2026-10-29T13:05:13+00:00 0.1 0:00:00 a3c175638f7a True 78ad01e2c88d637d runlog -m pytest -q
30 20261029-130517_m1_readiness_pytest m1_readiness_pytest ok 0 2026-10-29T13:05:17+00:00 2026-10-29T13:05:21+00:00 4.2 0:00:04 a3c175638f7a True 78ad01e2c88d637d runlog .venv/bin/python -m pytest -q
31 20261117-015603_m1_manifest_check m1_manifest_check ok 0 2026-11-17T01:56:03+00:00 2026-11-17T01:56:11+00:00 7.3 0:00:07 a3c175638f7a True 3ebe94262011224b runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
32 20261117-015354_ocr_hub_import ocr_hub_import ok 0 2026-11-17T01:53:54+00:00 2026-11-17T01:58:45+00:00 291.3 0:04:51 a3c175638f7a True 8b1e2eece6433379 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/04_ocr_hub.py
33 20261117-020356_ocr_hub_import ocr_hub_import ok 0 2026-11-17T02:03:56+00:00 2026-11-17T02:14:26+00:00 629.3 0:10:29 a3c175638f7a True e54053baa48c8a6a runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/04_ocr_hub.py
34 20261117-021300_07_labels 07_labels ok 0 2026-11-17T02:13:00+00:00 2026-11-17T02:14:29+00:00 88.3 0:01:28 a3c175638f7a True d99df45cecf82683 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/07_labels.py
35 20261117-021439_t4_questions t4_questions ok 0 2026-11-17T02:14:39+00:00 2026-11-17T02:15:29+00:00 49.5 0:00:49 a3c175638f7a True cb3eac2541da84a5 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/08_t4_questions.py
36 20261117-022043_audit_sample audit_sample failed 1 2026-11-17T02:20:43+00:00 2026-11-17T02:20:46+00:00 3.0 0:00:03 a3c175638f7a True e11b1ae5dab367e3 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_audit.py sample
37 20261117-022050_audit_sample audit_sample ok 0 2026-11-17T02:20:50+00:00 2026-11-17T02:20:59+00:00 9.4 0:00:09 a3c175638f7a True 8bdbbd74f2a2265e runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_audit.py sample
38 20261117-022208_t4_xml_check t4_xml_check ok 0 2026-11-17T02:22:08+00:00 2026-11-17T02:22:12+00:00 3.3 0:00:03 a3c175638f7a True 238be83fc45a6fe6 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/08_t4_xml_check.py
39 20261117-022534_data_manifest_tops data_manifest_tops ok 0 2026-11-17T02:25:34+00:00 2026-11-17T02:25:46+00:00 11.3 0:00:11 a3c175638f7a True 05ad2462bb031e2c runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py
40 20261117-022546_data_manifest_check data_manifest_check ok 0 2026-11-17T02:25:46+00:00 2026-11-17T02:25:57+00:00 10.7 0:00:11 a3c175638f7a True 05ad2462bb031e2c runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
41 20261117-022606_06_parse_witsml 06_parse_witsml ok 0 2026-11-17T02:26:06+00:00 2026-11-17T02:31:39+00:00 333.0 0:05:33 a3c175638f7a True 05ad2462bb031e2c runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
42 20261117-023529_06_parse_witsml 06_parse_witsml ok 0 2026-11-17T02:35:29+00:00 2026-11-17T02:39:39+00:00 250.4 0:04:10 a3c175638f7a True 7a4dec250d344f0e runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
43 20261117-021745_ocr_hub_import ocr_hub_import ok 0 2026-11-17T02:17:45+00:00 2026-11-17T02:41:22+00:00 1417.0 0:23:37 a3c175638f7a True da0858f91c7aed66 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/04_ocr_hub.py
44 20261117-024203_ocr_qc_hub ocr_qc_hub ok 0 2026-11-17T02:42:03+00:00 2026-11-17T02:42:38+00:00 35.1 0:00:35 a3c175638f7a True 0716b5f22173d6af runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/05_ocr_qc.py --source hub
45 20261117-024238_06_parse_witsml 06_parse_witsml interrupted -15 2026-11-17T02:42:38+00:00 2026-11-17T02:42:49+00:00 11.1 0:00:11 a3c175638f7a True b4a9f951f6ca9328 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
46 20261117-024309_06_parse_witsml 06_parse_witsml ok 0 2026-11-17T02:43:09+00:00 2026-11-17T02:47:15+00:00 246.3 0:04:06 a3c175638f7a True 12f02c5b0342f780 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/06_parse_witsml.py
47 20261117-024813_data_manifest_check data_manifest_check ok 0 2026-11-17T02:48:13+00:00 2026-11-17T02:48:23+00:00 10.9 0:00:11 a3c175638f7a True 12f02c5b0342f780 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/00_data_manifest.py --check
48 20261117-073525_m1_pytest m1_pytest ok 0 2026-11-17T07:35:25+00:00 2026-11-17T07:36:05+00:00 39.8 0:00:40 a3c175638f7a True 12f02c5b0342f780 runlog .venv/bin/python -m pytest -q
49 20261117-074344_audit_score_llm audit_score_llm ok 0 2026-11-17T07:43:44+00:00 2026-11-17T07:43:45+00:00 0.7 0:00:01 a3c175638f7a True 12f02c5b0342f780 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_audit.py score outputs/audit/trial_100/RATINGS_llm_sonnet.csv
50 20261117-074954_rater_agreement rater_agreement ok 0 2026-11-17T07:49:54+00:00 2026-11-17T07:49:55+00:00 1.2 0:00:01 a3c175638f7a True 9be27c5e57dab3f1 runlog /home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/09_rater_agreement.py
51 20261117-080811_m1/01_04_ocr_hub 20261117-080811_m1 04_ocr_hub ok 0 2026-11-17T08:08:11+00:00 2026-11-17T08:17:32+00:00 561.1 0:09:21 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/04_ocr_hub.py
52 20261117-080811_m1/02_05_ocr_qc 20261117-080811_m1 05_ocr_qc ok 0 2026-11-17T08:17:32+00:00 2026-11-17T08:18:06+00:00 33.7 0:00:34 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/05_ocr_qc.py --source hub
53 20261117-080811_m1/03_06_parse_witsml 20261117-080811_m1 06_parse_witsml ok 0 2026-11-17T08:18:06+00:00 2026-11-17T08:23:48+00:00 341.7 0:05:42 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/06_parse_witsml.py --workers 4
54 20261117-080811_m1/04_07_labels 20261117-080811_m1 07_labels ok 0 2026-11-17T08:23:48+00:00 2026-11-17T08:24:37+00:00 49.7 0:00:50 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/07_labels.py
55 20261117-080811_m1/05_08_t4_questions 20261117-080811_m1 08_t4_questions ok 0 2026-11-17T08:24:37+00:00 2026-11-17T08:25:03+00:00 25.3 0:00:25 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/08_t4_questions.py
56 20261117-080811_m1/06_08_t4_xml_check 20261117-080811_m1 08_t4_xml_check ok 0 2026-11-17T08:25:03+00:00 2026-11-17T08:25:05+00:00 2.4 0:00:02 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/08_t4_xml_check.py
57 20261117-080811_m1/07_09_audit 20261117-080811_m1 09_audit ok 0 2026-11-17T08:25:05+00:00 2026-11-17T08:25:06+00:00 1.0 0:00:01 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python scripts/09_audit.py sample
58 20261117-080811_m1/08_pytest 20261117-080811_m1 pytest failed 1 2026-11-17T08:25:06+00:00 2026-11-17T08:25:46+00:00 39.8 0:00:40 a3c175638f7a True 8096b532470ce38b runlog .venv/bin/python -m pytest -q
59 20261117-080811_m1 m1 failed 1 2026-11-17T08:08:11+00:00 2026-11-17T08:25:46+00:00 1055.5 0:17:35 a3c175638f7a True 8096b532470ce38b runlog bash scripts/run_m1.sh

View File

@@ -122,14 +122,14 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<h2>Các mục cần xác minh [XM]</h2>
<div class="tw"><table id="xm"><thead><tr><th>Mục</th><th>Vị trí trong plan</th><th>Trạng thái</th><th>Kết quả hoặc việc còn lại</th></tr></thead><tbody></tbody></table></div>
<h2>Quyết định (D-1 đến D-7, chốt 29/10/2026)</h2>
<h2>Quyết định (D-1 đến D-7 chốt 29/10/2026; D-8 đến D-13 chốt 17/11/2026)</h2>
<div class="tw"><table id="dec"><thead><tr><th>Mã</th><th>Quyết định</th><th>Chốt</th><th>Căn cứ</th></tr></thead><tbody></tbody></table></div>
<h2>Phát hiện đã kiểm chứng (từ dữ liệu, plan §1)</h2>
<div class="grid2" id="finds"></div>
<h2>QC OCR trên pilot: chandra đọc PDF so với HTML</h2>
<div class="sub" style="margin:-6px 0 10px">Pilot: 1 báo cáo mỗi wellbore (báo cáo giữa theo ngày), 26 báo cáo, 47 trang; không phải mẫu ngẫu nhiên của các trang, nên đây không phải CER toàn tập. Chỉ gộp khoảng trắng; mục thiếu tính là xóa, mục OCR tự thêm tính là chèn. Số liệu sẽ thay bằng số toàn tập khi OCR đủ 1.759 báo cáo. Nguồn: <code>outputs/ocr_qc/summary.json</code>, plan §1.3.</div>
<h2>QC OCR toàn tập: chandra đọc PDF so với HTML</h2>
<div class="sub" style="margin:-6px 0 10px">1.752 báo cáo, 3.056 trang (OCR do một đồng nghiệp chạy, xuất qua Dataset Hub; 7 báo cáo chưa đủ trang bị loại). Chỉ gộp khoảng trắng; mục thiếu tính là xóa, mục OCR tự thêm tính là chèn. Số pilot (26 báo cáo, 47 trang): CER 2,50%, khớp 0,9234. Nguồn: <code>outputs/ocr_qc_hub/summary.json</code>, plan §1.3.</div>
<div class="tw"><table id="ocrqc"><thead><tr><th>Phần</th><th class="num">Mục</th><th class="num">Khớp tuyệt đối</th><th class="num">CER</th><th class="num">WER</th></tr></thead><tbody></tbody></table></div>
<h2>Nhật ký</h2>
@@ -152,8 +152,8 @@ const PHASES = [
gate:{label:"G0", date:"2026-10-29", text:"số lượng khớp <code>EXPECTED</code>; sai lệch bản in giải thích được; OCR pilot đã đo", res:"đạt ngày 29/10/2026."},
tasks:[
{id:"p0-scaffold", t:"Khung project theo ML-Porosity", s:"done", n:"Package <code>volve_dia/</code>, script đánh số <code>scripts/NN_*.py</code>, <code>runlog</code> (log và runtime mọi lần chạy, <code>logs/index.csv</code>), <code>pyproject.toml</code> và <code>requirements-lock.txt</code> (Python 3.13); URL dịch vụ OCR chỉ nằm trong <code>.env</code>."},
{id:"p0-manifest", t:"Manifest dữ liệu (<code>00_data_manifest</code>)", s:"done", n:"<code>data/Volve</code> là symlink tới <code>ML-Porosity/data/Volve</code>, không tải lại. Ba thư mục con (<code>Well_technical_data</code>, <code>Reports</code>, <code>WITSML Realtime drilling data</code>, khoảng 20 GB) có SHA-256 trong <code>data_manifest/volve_dia.json</code>, kiểm bằng <code>--check</code>."},
{id:"p0-inv", t:"Kiểm kê (<code>01_inventory</code>)", s:"done", n:"1.759 DDR, cả 1.759 có đủ XML, HTML, PDF; 26 wellbore; PDF 3.066 trang, born-digital. WITSML: 17 wellbore, 14 có cả log thời gian và DDR (964 báo cáo)."},
{id:"p0-manifest", t:"Manifest dữ liệu (<code>00_data_manifest</code>)", s:"done", n:"<code>data/Volve</code> lúc đó là symlink tới <code>ML-Porosity/data/Volve</code> (từ 17/11 là thư mục thật; manifest nay 25.571 file, thêm formation tops). Ba thư mục con (<code>Well_technical_data</code>, <code>Reports</code>, <code>WITSML Realtime drilling data</code>, khoảng 20 GB) có SHA-256 trong <code>data_manifest/volve_dia.json</code>, kiểm bằng <code>--check</code>."},
{id:"p0-inv", t:"Kiểm kê (<code>01_inventory</code>)", s:"done", n:"1.759 DDR, cả 1.759 có đủ XML, HTML, PDF; 26 wellbore; PDF 3.066 trang, born-digital. WITSML: số lúc kiểm kê (17 wellbore, 14 có cả log và DDR, 964 báo cáo) sai vì tên wellbore lấy từ thư mục; parser WITSML 17/11 đo lại: 21 wellbore DDR, 1.384 báo cáo."},
{id:"p0-ddr", t:"Parser DDR XML → DuckDB (<code>02_parse_ddr</code>)", s:"done", n:"17 bảng trong <code>outputs/ddr/volve_ddr.duckdb</code>; 23.447 activity (480 fail); 9.164 sentinel đổi thành thiếu. Số lượng khóa trong <code>EXPECTED</code>, kiểm tra nhất quán của nguồn ở <code>outputs/ddr/summary.json</code> (plan §1.2)."},
{id:"p0-render", t:"QC bản in HTML so với XML (<code>03_render_qc</code>)", s:"done", n:"272.544 mục của 1.759 báo cáo: mọi mục khớp, trừ hai cờ Tight well và HPHT (lỗi render của nhà phát hành, plan §1.3)."},
{id:"p0-ocr", t:"OCR pilot (<code>04_ocr.py --pilot</code>)", s:"done", n:"Chandra trên dịch vụ vLLM dùng chung, request và prompt giống hệt vopec-chatbot (hash kiểm trước mỗi lần chạy). 26 báo cáo, 47 trang, 47/47 đọc được ở lần đầu; 6,2 s/trang với 4 worker; lượt pilot 5 phút 3 giây."},
@@ -165,22 +165,22 @@ const PHASES = [
{id:"M1", name:"M1 Dữ liệu và nhãn", start:"2026-10-30", end:"2026-11-30", when:"30/10 – 30/11/2026",
out:"DuckDB đủ bảng; <code>configs/labels.yaml</code>; bộ câu hỏi T4", gate:null,
tasks:[
{id:"m1-ocr", t:"OCR toàn bộ 1.759 DDR (3.066 trang, khoảng 5,3 h) và QC toàn tập", s:"blocked", n:"Dịch vụ OCR trả 503, pod không chạy; lệnh chạy cũng là lệnh kiểm: <code>setsid nohup scripts/runlog.sh -n ocr_full -- scripts/04_ocr.py --all &gt; /dev/null 2&gt;&amp;1 &amp;</code>. Sau đó <code>scripts/runlog.sh scripts/05_ocr_qc.py</code>, cập nhật plan §1.3 và trang này."},
{id:"m1-witsml", t:"Parser WITSML vào DuckDB", s:"todo", n:"Log thời gian (68 kênh, chu kỳ khoảng 3 s), <code>bhaRun</code>, <code>message</code>, <code>trajectory</code>, <code>mudLog</code>; sentinel và bộ lọc kênh theo TADI (plan §4.1). Kiểm <code>15/9-F-15 S</code> so với <code>15/9-F-15</code>; tìm nguồn formation tops và thêm vào manifest."},
{id:"m1-labels", t:"Bảng ánh xạ mã → nhãn (<code>configs/labels.yaml</code>)", s:"todo", n:"T1 pha từ hole size (<code>diaHole</code>); T2 NPT và nhóm nguyên nhân từ <code>stateDetailActivity</code> + <code>proprietaryCode</code> + <code>state</code>; T3 khoảng MD trên lưới 10 m. T1 cần luật điền pha cho 260 báo cáo có activity khoan mà thiếu <code>diaHole</code> (plan §4.3). Kiểm báo cáo <code>15_9_19_A_1980_01_01</code> (ngày 1980, không có activity)."},
{id:"m1-t4", t:"Template câu hỏi T4 và đáp án SQL", s:"todo", n:"Đáp án tính bằng SQL trên DuckDB, kèm id các dòng dẫn chứng; LLM chỉ paraphrase câu hỏi (plan §4.3). ROP lấy từ <code>distDrill</code>, <code>bits.bitRun_ropAv</code> hoặc WITSML, template ghi rõ nguồn (plan §1.4 ý 5)."},
{id:"m1-audit", t:"Tự chấm mù thử 100 dòng", s:"todo", n:"Che mã hoạt động; ước lượng độ khớp của nhãn xác định và thời gian chấm mỗi dòng (plan §12 ý 1)."},
{id:"m1-protocol", t:"Bản nháp <code>configs/protocol_v1.yaml</code>", s:"todo", n:"Gồm lựa chọn nhóm split theo wellbore hay theo giếng (plan §4.5). Chỉ khóa bằng SHA-256 ở G1, trước mọi lần chạy model."},
{id:"m1-read", t:"Đọc toàn văn và tải các bộ nhãn độc lập", s:"todo", n:"Đọc PetroAgents, Bassey 2026, EAGE 2026101276. Tải DrillScribe, repo Anatoly5ms, dataset OMAE 2024 (plan §11, §12 ý 1)."}
{id:"m1-ocr", t:"OCR toàn bộ DDR và QC toàn tập", s:"done", n:"Một đồng nghiệp chạy OCR, xuất qua Dataset Hub; <code>04_ocr_hub.py</code> ghép trang về DDR bằng nội dung: 3.059/3.066 trang, 1.752/1.759 báo cáo đủ trang. QC (<code>05_ocr_qc.py --source hub</code>): CER 2,40%, WER 5,56%, khớp 0,9181. Còn: xem 16 trang lệch ngày và 7 trang chưa ghép (plan §1.3, §12 ý 12)."},
{id:"m1-witsml", t:"Parser WITSML vào DuckDB", s:"done", n:"<code>06_parse_witsml.py</code> (246 s): 21 wellbore DDR có log thời gian (không phải 14), 1.384 báo cáo; 2,25 tỉ giá trị log, 2,2 GB. <code>15/9-F-15 S</code> là DDR F-15; hai wellbore khác lệch tên một bậc. Formation tops 409 pick, 24 wellbore DDR có pick riêng (plan §12 ý 14)."},
{id:"m1-labels", t:"Bảng ánh xạ mã → nhãn (<code>configs/labels.yaml</code>) và nhãn T1–T3", s:"done", n:"T1 section: luật điền <code>ffill</code> (932 ngày khoan: 672 công bố, 260 điền). T2 NPT (a) 3.577 dòng, (b) 4.286 dòng. T3: 844 / 979 ô dương, chỉ 50% NPT định vị được theo độ sâu. Báo cáo <code>15_9_19_A_1980_01_01</code> là báo cáo giữ chỗ, loại khỏi T1–T3 (plan §4.3)."},
{id:"m1-t4", t:"Template câu hỏi T4 và đáp án SQL", s:"done", n:"39 template, 1.662 câu hỏi (1.638 có đáp án, 24 không); đáp án SQL, pandas độc lập và XML thô khớp 100% (plan §4.3)."},
{id:"m1-audit", t:"Chấm mù thử 100 dòng (LLM rater)", s:"done", n:"Mẫu 100 dòng chấm mù bởi <b>3 LLM rater (Sonnet, Opus, Haiku), không phải audit của người</b>. Trung vị κ với nhãn code: NPT (a) 0,553, (b) 0,574, nguyên nhân (a) 0,456, loại thao tác 0,434; Fleiss giữa rater khoảng 0,66. Không có thời gian chấm của người (plan §12 ý 21)."},
{id:"m1-protocol", t:"Bản nháp <code>configs/protocol_v1.yaml</code>", s:"done", n:"Bản nháp, chưa khóa: split theo giếng (leave-one-well-out), hai giếng phát triển F-7 và F-9, luật lớp chấm riêng (≥ 3 giếng mỗi giếng ≥ 5 mục), NPT a hay b chọn bằng κ của audit 1. Khóa bằng SHA-256 ở G1 (plan §12 ý 15)."},
{id:"m1-read", t:"Đọc toàn văn và tải các bộ nhãn bên thứ ba", s:"doing", n:"Đã đọc Bassey 2026, Cao 2025, PetroAgents (toàn văn); đã tải và đối chiếu DrillScribe, Anatoly5ms, TSPP (<code>docs/literature_notes.md</code>). Còn: EAGE 2026, SPE-236554-MS, SPE-235330-MS."}
]},
{id:"M2", name:"M2 Kiểm định và khóa protocol", start:"2026-12-01", end:"2026-12-31", when:"12/2026",
out:"<code>protocol_v1.yaml</code> + <code>.sha256</code>; báo cáo độ khớp nhãn",
gate:{label:"G1", date:"2026-12-31", text:"protocol khóa trước mọi lần chạy model. Lớp có κ &lt; 0,6 so với audit, hoặc &lt; 20 mục audit, không báo như lớp riêng: gộp hoặc bỏ, có ghi lại"},
tasks:[
{id:"m2-audit", t:"Audit mù lần 1 (~300 dòng)", s:"todo", n:"Phân tầng theo wellbore và lớp; che <code>proprietaryCode</code> và <code>stateDetailActivity</code>; gán nhãn chỉ từ comment và tóm tắt 24 h (plan §4.4)."},
{id:"m2-ext", t:"Đối chiếu Bassey 2026, OMAE 2024, DrillScribe", s:"todo", n:"Độ khớp theo wellbore và theo thời gian; kiểm giấy phép từng bộ trước khi phát hành kèm."},
{id:"m2-audit", t:"Chấm mù bằng ≥ 3 LLM rater (~300 dòng) và chạy lại lần hai", s:"todo", n:"Thay audit của tác giả (không có người chấm, plan §12 ý 20). Các họ model khác nhau, chỉ thấy view đã che mã; báo κ của từng rater với nhãn code, κ giữa các rater; thống kê quyết định là trung vị (plan §4.4)."},
{id:"m2-ext", t:"Kiểm chéo DrillScribe, Anatoly5ms, TSPP", s:"todo", n:"Parser so với DrillScribe (khớp 100%); T3 so với luật văn bản Anatoly5ms; ba tình huống kẹt cần TSPP định tính; kiểm giấy phép trước khi phát hành kèm."},
{id:"m2-proto", t:"Viết và khóa <code>protocol_v1</code> (<code>.yaml</code> + <code>.sha256</code>)", s:"todo", n:"Chốt split (nhóm theo wellbore hay theo giếng), seed, metric, định nghĩa NPT (chỉ interruption 3.577, hay hợp ba điều kiện 4.286), gộp lớp và ngưỡng các cổng (plan §4.5)."},
{id:"m2-agree", t:"Báo cáo độ khớp nhãn", s:"todo", n:"Cohen κ theo lớp và theo wellbore so với audit và các bộ nhãn độc lập (RQ3)."}
{id:"m2-agree", t:"Báo cáo độ khớp nhãn", s:"todo", n:"Cohen κ của từng LLM rater với nhãn code và giữa các rater, theo lớp và theo giếng (RQ3)."}
]},
{id:"M3", name:"M3–M4 Baseline", start:"2027-01-01", end:"2027-02-28", when:"1–2/2027",
out:"Bảng kết quả, ≥ 3 seed, CI theo wellbore",
@@ -192,11 +192,11 @@ const PHASES = [
{id:"m34-c4", t:"Thí nghiệm C4: input XML so với input OCR", s:"todo", n:"Cùng nhãn từ XML, cùng model; báo chênh lệch điểm T1, T2, T4 kèm CI (plan §5.2)."},
{id:"m34-stats", t:"Bảng kết quả ≥ 3 seed, CI bootstrap theo wellbore", s:"todo", n:"So từng cặp trên cùng fold; số của PetroAgents chỉ để tham chiếu, không cùng bảng (plan §4.7). Preprint ở M4–M5 nếu venue cho phép."}
]},
{id:"M5", name:"M5 Audit 2 và judge", start:"2027-03-01", end:"2027-03-31", when:"3/2027",
{id:"M5", name:"M5 Chạy lại rater và judge", start:"2027-03-01", end:"2027-03-31", when:"3/2027",
out:"κ, agreement của judge, tương quan EGS",
gate:{label:"G3", date:"2027-03-31", text:"chỉ dùng LLM-judge cho T4 khi agreement với tác giả đạt κ ≥ 0,6; không đạt thì T4 chỉ báo metric tự động và ghi rõ"},
tasks:[
{id:"m5-audit2", t:"Audit mù lần 2 (intra-rater κ)", s:"todo", n:"Chấm lại cách lần 1 ít nhất 2 tuần (plan §4.4)."},
{id:"m5-audit2", t:"Chạy lại LLM rater lần hai (độ nhất quán từng rater)", s:"todo", n:"Chấm lại cách lần 1 ít nhất 2 tuần (plan §4.4)."},
{id:"m5-t5", t:"T5 truy xuất khoảng tương đồng (nếu kịp)", s:"todo", n:"nDCG@k, MRR; leave-one-wellbore-out."},
{id:"m5-err", t:"Phân tích lỗi", s:"todo", n:""},
{id:"m5-judge", t:"Hiệu chuẩn LLM-judge và đối chiếu EGS", s:"todo", n:"Đối chiếu với điểm tác giả trên khoảng 100 câu; Spearman giữa EGS và điểm người (RQ4)."}
@@ -215,29 +215,35 @@ const PHASES = [
const TILES = [
{k:"DDR", v:"1.759", n:"báo cáo của 26 wellbore, đủ ba phiên bản XML, HTML, PDF"},
{k:"Activity", v:"23.447", n:"480 dòng <code>state</code> = fail; 64 mã hoạt động"},
{k:"Trang PDF đã OCR", v:"47 / 3.066", n:"pilot 26 báo cáo; OCR toàn bộ chờ dịch vụ (503)", bar:47/3066},
{k:"QC OCR (pilot)", v:"CER 2,50%", n:"WER 5,57%; khớp tuyệt đối 0,9234 trên 5.835 mục"},
{k:"Trang PDF đã OCR", v:"3.059 / 3.066", n:"OCR toàn tập qua Dataset Hub; 7 trang chưa ghép", bar:3059/3066},
{k:"QC OCR (toàn tập)", v:"CER 2,40%", n:"WER 5,56%; khớp tuyệt đối 0,9181 trên 365.698 mục"},
{k:"QC bản in", v:"272.544", n:"mục HTML so với XML; chỉ Tight well và HPHT sai"}
];
const XM = [
{name:"WITSML <code>15/9-F-15 S</code> có phải DDR <code>15/9-F-15</code>?", where:"mục 1.1, 4.1", s:"todo", r:"WITSML <code>15/9-F-15 S</code> là wellbore WITSML duy nhất không có DDR. Kiểm khi viết parser WITSML (M1)."},
{name:"Báo cáo <code>15_9_19_A_1980_01_01</code>", where:"mục 1.2", s:"todo", r:"Báo cáo duy nhất có ngày trước 1990; là 1 trong 9 báo cáo không có activity. Kiểm khi dựng nhãn (M1)."},
{name:"Split nhóm theo wellbore hay theo giếng", where:"mục 4.5", s:"todo", r:"26 wellbore có DDR thuộc 11 giếng; các sidetrack dùng chung phần lỗ phía trên điểm rẽ nhánh. Chốt trong <code>protocol_v1</code> trước G1."},
{name:"Thư mục nguồn của formation tops", where:"mục 4.1", s:"todo", r:"Bản đánh giá mục 3 ghi 409 pick trên 35 wellbore; thư mục nguồn chưa xác định, chưa có trong manifest."},
{name:"Giấy phép bộ nhãn Bassey 2026, OMAE 2024, DrillScribe", where:"mục 4.4 ý 2", s:"todo", r:"Kiểm trước khi phát hành kèm; là một điều kiện của G4."},
{name:"WITSML <code>15/9-F-15 S</code> có phải DDR <code>15/9-F-15</code>?", where:"mục 1.1, 4.1", s:"done", r:"Đúng: WITSML <code>15/9-F-15 S</code> là DDR <code>15/9-F-15</code> (khớp theo uid, độ sâu cuối báo cáo, trạm survey, TD). Hai wellbore khác lệch tên một bậc: WITSML <code>15/9-F-15</code> là F-15 A, <code>15/9-F-15A</code> là F-15 C (plan §12 ý 14)."},
{name:"Báo cáo <code>15_9_19_A_1980_01_01</code>", where:"mục 1.2", s:"done", r:"Báo cáo giữ chỗ: kỳ 31/12/1979–1/1/1980, spud 25/7/1997, chỉ chứa 5 trạm survey tie-in dùng ngày mặc định. <code>labels.yaml</code> loại khỏi T1–T3 (plan §1.2)."},
{name:"Split nhóm theo wellbore hay theo giếng", where:"mục 4.5", s:"done", r:"Chốt trong bản nháp: theo giếng, leave-one-well-out (16 ngày báo cáo dùng chung giữa wellbore, comment lặp nguyên văn ở wellbore anh em, 191/844 ô dương T3 nằm trên đầu lỗ). Khóa chính thức ở G1."},
{name:"Thư mục nguồn của formation tops", where:"mục 4.1", s:"done", r:"Tìm thấy ngày 29/10: <code>Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat</code>, 409 pick trên 35 wellbore, khớp bản đánh giá mục 3. 23/26 wellbore DDR trùng tên; còn ánh xạ <code>15/9-19 SR</code> với 15/9-19 S, ST2 và F-9 A. Đã vào manifest (25.571 file); ánh xạ <code>15/9-19 SR</code> là 15/9-19 ST2, F-9 A thừa hưởng pick của F-9 (plan §4.1)."},
{name:"Giấy phép nguồn ngoài (DrillScribe, Anatoly5ms, TSPP, Bassey)", where:"mục 4.4 ý 2", s:"todo", r:"Không bộ nào là nhãn độc lập (plan §4.4). Không phát hành lại file: TSPP không có giấy phép; DrillScribe, Anatoly5ms MIT, nhưng dữ liệu Volve chịu CC BY-NC-SA. Là một điều kiện của G4."},
{name:"Quartile của các venue", where:"mục 0 (Venue)", s:"todo", r:"Tra lại trên SCImago khi nộp."},
{name:"Kiểm tra novelty (PetroAgents đã có bản tạp chí chưa)", where:"mục 2.3", s:"todo", r:"Đọc toàn văn PetroAgents, Bassey 2026, EAGE 2026101276; quét OnePetro, arXiv, Scopus lần cuối trước khi nộp. Không viết \"first\" trước khi xong (mục 10)."}
{name:"Kiểm tra novelty (PetroAgents đã có bản tạp chí chưa)", where:"mục 2.3", s:"todo", r:"Quét 17/11: PetroAgents chưa có bản tạp chí; có hai bài hội nghị ADIPEC về hỏi đáp trên DDR Volve. Còn: toàn văn PetroAgents (tải tay), EAGE; quét Scopus trước khi nộp. Không viết \"first\" (mục 10)."}
];
const DECISIONS = [
{id:"D-1", q:"Hướng nghiên cứu", p:"Ý tưởng 1 (Drilling Intelligence Atlas) trên dữ liệu public Volve, không chọn AI-FWI.", n:"Bản đánh giá mục 1, 4: FWI không khả thi trên dữ liệu public (plan §12 ý 2)."},
{id:"D-2", q:"Khung project", p:"Theo ML-Porosity: package <code>volve_dia</code>, script đánh số, <code>runlog</code> (log và runtime mọi lần chạy, <code>logs/index.csv</code>), manifest SHA-256 kiểm bằng <code>--check</code>, pytest với marker <code>data</code>, driver <code>run_p0.sh</code>; tài liệu AGENTS.md, README.md, plan.md, report.html.", n:"<code>data/Volve</code> là symlink tới dữ liệu của ML-Porosity, không tải lại (plan §12 ý 3)."},
{id:"D-2", q:"Khung project", p:"Theo ML-Porosity: package <code>volve_dia</code>, script đánh số, <code>runlog</code> (log và runtime mọi lần chạy, <code>logs/index.csv</code>), manifest SHA-256 kiểm bằng <code>--check</code>, pytest với marker <code>data</code>, driver <code>run_p0.sh</code>; tài liệu AGENTS.md, README.md, plan.md, report.html.", n:"<code>data/Volve</code> lúc lập là symlink tới dữ liệu của ML-Porosity; từ 17/11 là thư mục thật (plan §12 ý 3, 18)."},
{id:"D-3", q:"Nguồn nhãn và parser tài liệu", p:"Nhãn và đáp án chỉ lấy từ XML (và WITSML); giữ tên phần tử WITSML làm tên cột; sentinel và đơn vị được đếm, không đổi âm thầm. Parser tài liệu là chandra trên dịch vụ vLLM, request và prompt giống hệt vopec-chatbot (<code>configs/ocr.yaml</code>).", n:"Parser chandra theo yêu cầu ngày 29/10/2026. Đã có XML nên OCR dùng để đo C4, không để dựng nhãn (plan §12 ý 4, §5.3)."},
{id:"D-4", q:"Tight well và HPHT", p:"Chỉ lấy từ XML.", n:"QC bản in: XML ghi 0 (N), HTML in \"Y\" ở cả 1.759 báo cáo; mọi mục khác khớp (plan §1.3, §12 ý 5)."},
{id:"D-5", q:"Sửa parser OCR và luật QC", p:"Parser chỉ khôi phục cấu trúc, mỗi lần sửa ghi vào <code>notes</code>: dòng header bị đọc thành hàng bảng đưa về header; hàng nối tiếp gộp vào hàng trên; bảng nối sang trang khác số cột vẫn nối. Luật QC: nhãn trường đọc sai ghép theo vị trí; khi số cột khác, ghép cột bằng căn tiêu đề; lỗi ký tự chỉ đếm trên mục gần đúng (≤ 25%). Regex \"Wellbore:\" giữ chặt.", n:"QC ban đầu CER 6,85%, phần lớn là sai lệch cấu trúc parser chưa hoàn tác; sau khi sửa CER 2,50%. Lỗi được đếm, không được tha (plan §12 ý 6)."},
{id:"D-6", q:"Bảo vệ dịch vụ OCR dùng chung", p:"<code>ocr.run</code> kiểm <code>/v1/models</code> và model <code>chandra</code> trước khi gửi trang nào; ngừng gửi sau 8 trang lỗi liên tiếp (<code>stop_after_failed</code>); giữ 4 worker.", n:"Sau pilot mọi endpoint trả 503, pod không tồn tại và không thuộc project này; OCR toàn bộ chờ người dùng khởi động lại (plan §12 ý 7)."},
{id:"D-7", q:"Chạy lại P0 end-to-end", p:"<code>run_p0.sh</code>: 00 <code>--check</code>, 01–05 (04 ở chế độ <code>--pilot</code>), pytest; biến luồng đặt 4 vô điều kiện, vì máy đặt sẵn 40 và <code>${VAR:-4}</code> sẽ giữ 40.", n:"Lượt <code>20261029-105934_p0</code>, 197,6 s, mọi bước đạt, 40 test đạt, <code>meta.json</code> ghi 4 luồng ở mọi bước. Lượt trước đó chạy trước lớp bảo vệ ở ý 7 và với 40 luồng (plan §12 ý 8)."}
{id:"D-7", q:"Chạy lại P0 end-to-end", p:"<code>run_p0.sh</code>: 00 <code>--check</code>, 01–05 (04 ở chế độ <code>--pilot</code>), pytest; biến luồng đặt 4 vô điều kiện, vì máy đặt sẵn 40 và <code>${VAR:-4}</code> sẽ giữ 40.", n:"Lượt <code>20261029-105934_p0</code>, 197,6 s, mọi bước đạt, 40 test đạt, <code>meta.json</code> ghi 4 luồng ở mọi bước. Lượt trước đó chạy trước lớp bảo vệ ở ý 7 và với 40 luồng (plan §12 ý 8)."},
{id:"D-8", q:"OCR toàn tập qua Dataset Hub", p:"Dùng bản OCR đồng nghiệp đã chạy thay vì chạy lại trên dịch vụ chung; ghép trang về DDR bằng nội dung (TF-IDF, F1 token trọng số idf với sàn 0,7, tương quan ảnh cho trang không chữ, kiểm ngày chỉ trên trang đã ghép). URL, dataset id, khóa API chỉ ở <code>.env</code>.", n:"Dịch vụ OCR chung vẫn 503; export không ghi tên file. 3.059/3.066 trang ghép được; lượt đầu ghép nhầm 3 trang, đã sửa (plan §12 ý 12)."},
{id:"D-9", q:"Split theo giếng", p:"Leave-one-well-out ở vòng ngoài, GroupKFold(5) theo giếng ở vòng trong, điểm trên dự đoán out-of-fold gộp; theo wellbore chỉ là độ nhạy; giếng phát triển F-7 và F-9.", n:"16 ngày báo cáo dùng chung giữa wellbore, comment lặp ở wellbore anh em, 191/844 ô dương T3 trên đầu lỗ; hai repo ngoài cũng giữ sidetrack cùng giếng mẹ (plan §4.5)."},
{id:"D-10", q:"Luật điền hole size (T1)", p:"<code>ffill</code>: hole section gần nhất đã mở của cùng wellbore; 17 báo cáo trước section đầu lấy section đầu (<code>bfill_leading</code>).", n:"Trên <code>tail_half</code> (giống khoảng trống thật) khôi phục 1,0000; khớp văn bản 7/8 và bản ghi bit 23/30 ở các ngày thiếu thật (plan §4.3)."},
{id:"D-11", q:"Lớp đánh giá được", p:"Lớp chấm riêng chỉ khi ≥ 3 giếng mỗi giếng ≥ 5 mục; không thì gộp hoặc bỏ (sidetrack ra khỏi đích nguyên nhân nhưng vẫn là NPT nhị phân).", n:"Lớp hiếm tập trung ở vài giếng; GroupKFold(5) không giúp. Ghi trong <code>protocol_v1</code> nháp (plan §12 ý 15)."},
{id:"D-12", q:"Bỏ \"ba bộ nhãn độc lập\"", p:"Lớp kiểm định thứ hai là kiểm chéo parser với DrillScribe, đối chiếu T3 với luật văn bản Anatoly5ms, và ba tình huống TSPP định tính.", n:"Bassey là nhãn khai thác theo ngày; nhãn DrillScribe dựng lại khớp 1.758/1.758 từ <code>stateDetailActivity</code>; TSPP chỉ có 3 sự cố, không có cột nhãn (plan §4.4, §12 ý 17)."},
{id:"D-13", q:"C2 không dùng audit của người", p:"Kiểm định nhãn bằng nhiều LLM rater mù thuộc các họ model khác nhau (Sonnet, Opus, Haiku ở bản thử; thêm model open-weight ở M2), báo κ từng rater với nhãn code và giữa các rater; cộng kiểm chéo. Không gọi là audit của tác giả hay của chuyên gia.", n:"Không có người chấm (quyết định người dùng 17/11/2026). Giới hạn nêu trong bài: rater trùng huấn luyện với baseline LLM (plan §4.4, §12 ý 20)."}
];
const FINDS = [
@@ -246,35 +252,47 @@ const FINDS = [
{h:"Ứng viên NPT: ba điều kiện cho ba con số", p:"Nhóm interruption <b>3.577</b>; <code>state</code> = fail <b>480</b>; <code>stateDetailActivity</code> ≠ success <b>2.645</b>. Hợp của ba điều kiện: <b>4.286 activity (18,3%)</b>. Định nghĩa NPT chốt trước G1."},
{h:"Lớp sự cố hiếm", p:"Stuck equipment <b>109</b>, circulation loss <b>92</b>, mud loss <b>12</b>, injury <b>1</b>: macro-F1 kém ổn định. Báo theo từng lớp kèm CI; việc gộp lớp, nếu có, chốt trong protocol trước G1."},
{h:"<code>ropCurrent</code> và <code>mdPlanned</code> trống ở mọi báo cáo", p:"Sentinel ở <b>cả 1.759 báo cáo</b>. T4 phải tính ROP từ <code>distDrill</code> (sentinel ở 1.247 báo cáo), từ <code>bits.bitRun_ropAv</code> (<b>88</b> giá trị ở 80 báo cáo, 21 wellbore) hoặc từ WITSML. Tổng cộng 9.164 giá trị sentinel đổi thành thiếu."},
{h:"Hole size trống ở 260 ngày đang khoan", p:"<code>diaHole</code> trống (NULL, không phải sentinel) ở <b>990/1.759</b> báo cáo; <b>260</b> báo cáo trong số đó, ở 24 wellbore, vẫn có activity nhóm drilling (<b>2.618</b> dòng), và bảng <code>bits</code> chỉ phủ 25. Pha T1 của các ngày này cần luật điền, chốt trong <code>labels.yaml</code> và kiểm trên audit."},
{h:"WITSML chỉ phủ 14 wellbore có cả log và DDR", p:"26 thư mục → 17 wellbore; 15 có log thời gian, <b>14</b> trong đó có DDR (<b>964</b> báo cáo); 10 wellbore DDR không có WITSML. T3, T5 và phần thời gian thực của T1 chỉ dùng được 14 wellbore; tách kết quả DDR-only (26) và DDR + WITSML (14)."},
{h:"Hole size trống ở 260 ngày đang khoan", p:"<code>diaHole</code> trống (NULL, không phải sentinel) ở <b>990/1.759</b> báo cáo; <b>260</b> báo cáo trong số đó, ở 24 wellbore, vẫn có activity nhóm drilling (<b>2.618</b> dòng), và bảng <code>bits</code> chỉ phủ 25. Luật điền <code>ffill</code> đã chốt trong <code>labels.yaml</code>; kiểm trên audit ở M2."},
{h:"WITSML phủ 21 wellbore DDR, không phải 14", p:"Thư mục WITSML là một giếng chứa nhiều wellbore; tên phải đọc từ nội dung. <b>21</b> wellbore DDR có log thời gian, <b>1.384</b> báo cáo (không phải 964); chỉ năm wellbore 15/9-19 không có. WITSML <code>15/9-F-15 S</code> là DDR F-15. Log Baker Hughes: 78 kênh, bước 3 s; Schlumberger: 42–252 kênh, bước trung vị 4 s (không phải \"68 kênh, 3 s\"). Chỉ 50% dòng NPT định vị được theo độ sâu."},
{h:"Các loại lỗi thật của chandra", p:"<b>Bịa đơn vị</b> vào cặp ngoặc rỗng (\"()\" thành \"(°)\", 43 lần chèn \"°\"); <b>tự sửa lỗi chính tả của nguồn</b> (Attempeted → Attempted, stnds → stands); <b>cột State gộp</b> vào cột Main-Sub Activity (59 lần chèn \"o\", 51 lần \"k\"); <b>giá trị độ sâu lệch xuống một nhãn</b>: sai nhưng trông hợp lệ, nguy hiểm nhất."},
{h:"CER theo báo cáo trên pilot", p:"CER nội dung trung vị <b>0,83%</b>, phân vị 90 là <b>4,5%</b>, lớn nhất <b>25,3%</b>; không báo cáo nào khớp tuyệt đối toàn bộ. Lỗi đáng ngại nhất (độ sâu lệch nhãn, cột gộp, chữ số đổi) không lộ trong CER, nên C4 đo ảnh hưởng lên điểm nhiệm vụ."}
{h:"CER theo báo cáo trên pilot", p:"CER nội dung trung vị <b>0,83%</b>, phân vị 90 là <b>4,5%</b>, lớn nhất <b>25,3%</b>; không báo cáo nào khớp tuyệt đối toàn bộ. Lỗi đáng ngại nhất (độ sâu lệch nhãn, cột gộp, chữ số đổi) không lộ trong CER, nên C4 đo ảnh hưởng lên điểm nhiệm vụ."},
{h:"Không có bộ nhãn NPT khoan độc lập trên Volve", p:"Bassey 2026 gán nhãn <b>khai thác theo ngày</b>; nhãn DrillScribe dựng lại khớp <b>1.758/1.758</b> episode từ <code>stateDetailActivity</code>; bộ TSPP chỉ có 3 sự cố kẹt cần, không có cột nhãn, không có giấy phép. Audit mù của tác giả mang phần lớn sức nặng của C2."},
{h:"Hai đối thủ hội nghị ADIPEC (2/11/2026)", p:"SPE-236554-MS (hỏi đáp trên 1.266 DDR Volve) và SPE-235330-MS (agent ReAct, 1.681 DDR) đánh giá định lượng hỏi đáp; không có nhiệm vụ nhãn, không kiểm soát rò rỉ mã. Không viết \"first quantitative evaluation\"; thêm metric nhầm wellbore cho T4."},
{h:"Lỗi render thứ ba: Bit Record", p:"Cột \"End mMD\" của Bit Record in <code>bitRun_mdHoleStart</code> (16/16 hàng kiểm tay, 90/90 theo T4), và <code>03</code> chỉ phủ header, 31 trường, tóm tắt, Operations, không phủ 14 bảng. Giá trị này chỉ lấy từ XML."},
{h:"OCR toàn tập yếu nhất ở độ sâu và tên riêng", p:"CER 2,40% toàn tập, nhưng depth mMD khớp <b>0,9241</b> (CER 6,97%), mTVD 0,9418, tên giàn khớp 0,3385; bịa \"°\" vào ngoặc rỗng (2.524 lần). CER theo báo cáo: trung vị 0,93%, p90 4,98%, lớn nhất 85,7%; chỉ 9/1.752 báo cáo khớp tuyệt đối."}
];
const OCRQC = [
{p:"<b>Toàn bộ nội dung</b>", n:"5.835", e:"0,9234", c:"2,50%", w:"5,57%"},
{p:"Header (Wellbore, Period)", n:"52", e:"0,9615", c:"0,78%", w:"1,16%"},
{p:"Trường đầu báo cáo (giá trị)", n:"806", e:"0,9355", c:"2,69%", w:"9,05%"},
{p:"Tóm tắt 24 h", n:"52", e:"0,7115", c:"0,30%", w:"1,37%"},
{p:"Ô bảng", n:"4.530", e:"0,9192", c:"2,84%", w:"6,15%"},
{p:"trong đó Operations", n:"2.244", e:"0,8587", c:"3,12%", w:""},
{p:"trong đó Drilling Fluid", n:"1.890", e:"0,9841", c:"1,17%", w:""},
{p:"trong đó Equipment Failure Information", n:"49", e:"0,8367", c:"6,50%", w:""},
{p:"Tiêu đề cột", n:"395", e:"0,9696", c:"0,98%", w:"1,34%"},
{p:"Nhãn trường (không tính vào nội dung)", n:"806", e:"0,8697", c:"1,89%", w:"5,14%"}
{p:"<b>Toàn bộ nội dung</b>", n:"365.698", e:"0,9181", c:"2,40%", w:"5,56%"},
{p:"Header (Wellbore, Period)", n:"3.504", e:"0,9777", c:"2,51%", w:"2,56%"},
{p:"Trường đầu báo cáo (giá trị)", n:"54.312", e:"0,9280", c:"3,00%", w:"8,17%"},
{p:"Tóm tắt 24 h", n:"3.504", e:"0,7740", c:"0,53%", w:"1,73%"},
{p:"Ô bảng", n:"280.995", e:"0,9116", c:"2,67%", w:"6,16%"},
{p:"trong đó Operations", n:"140.322", e:"0,8605", c:"2,99%", w:""},
{p:"trong đó Drilling Fluid", n:"108.342", e:"0,9648", c:"1,09%", w:""},
{p:"trong đó Casing Liner Tubing", n:"3.500", e:"0,9394", c:"4,72%", w:""},
{p:"trong đó Pore Pressure", n:"4.555", e:"0,9568", c:"4,30%", w:""},
{p:"trong đó Survey Station", n:"8.595", e:"0,9944", c:"0,24%", w:""},
{p:"Tiêu đề cột", n:"23.383", e:"0,9859", c:"0,83%", w:"1,01%"},
{p:"Nhãn trường (không tính vào nội dung)", n:"54.312", e:"0,8825", c:"2,85%", w:"5,65%"}
];
const LOG = [
["2026-10-29","Chọn hướng: Ý tưởng 1 (Drilling Intelligence) trên Volve, không chọn AI-FWI (bản đánh giá mục 1, 4)."],
["2026-10-29","Dựng P0 theo khung ML-Porosity: package <code>volve_dia</code>, scripts 00–05, <code>runlog</code>, manifest SHA-256 (<code>data/Volve</code> symlink tới ML-Porosity); kiểm kê 1.759 DDR ba phiên bản; parser DDR XML → DuckDB 17 bảng (26 wellbore, 23.447 activity, 480 fail)."],
["2026-10-29","Dựng P0 theo khung ML-Porosity: package <code>volve_dia</code>, scripts 00–05, <code>runlog</code>, manifest SHA-256 (<code>data/Volve</code> lúc đó symlink tới ML-Porosity); kiểm kê 1.759 DDR ba phiên bản; parser DDR XML → DuckDB 17 bảng (26 wellbore, 23.447 activity, 480 fail)."],
["2026-10-29","QC bản in: 272.544 mục HTML so với XML; chỉ Tight well và HPHT sai (HTML in \"Y\" ở cả 1.759 báo cáo, XML ghi 0). Hai cờ này chỉ lấy từ XML."],
["2026-10-29","OCR pilot 26 báo cáo, 47 trang: 47/47 đạt, 6,2 s/trang với 4 worker. QC OCR ban đầu CER 6,85%, khớp 0,9171; sau khi sửa parser và luật QC: CER 2,50%, khớp 0,9234, WER 5,57%; header CER 46% → 0,78%; ô Operations CER 8,5% → 3,12%."],
["2026-10-29","Dịch vụ OCR ngừng sau pilot: mọi endpoint trả 503, pod không tồn tại. Thêm lớp bảo vệ: kiểm <code>/v1/models</code> và model chandra trước khi gửi trang nào, ngừng gửi sau 8 trang lỗi liên tiếp; bộ test thành 40 test, đều đạt. OCR toàn bộ (3.066 trang, khoảng 5,3 h) chờ người dùng khởi động lại dịch vụ."],
["2026-10-29","Sửa <code>run_p0.sh</code>: đặt <code>OMP_NUM_THREADS</code>, <code>MKL_NUM_THREADS</code>, <code>OPENBLAS_NUM_THREADS</code> = 4 vô điều kiện (<code>${VAR:-4}</code> giữ giá trị 40 của máy). P0 chạy lại end-to-end (<code>20261029-105934_p0</code>, 197,6 s): mọi bước đạt, 40 test đạt, 4 luồng ở mọi bước; bước 04 không gửi trang nào (47/47 trang từ cache)."],
["2026-10-29","Viết <code>docs/plan.md</code>, <code>AGENTS.md</code>, <code>README.md</code> và trang tiến độ này."],
["2026-10-29","Viết bài giảng <code>docs/technical_overview.md</code> theo cấu trúc của ML-Porosity. Đối chiếu số liệu trên DuckDB thấy thêm: <code>diaHole</code> trống ở 990 báo cáo (260 có activity khoan); <code>bits.bitRun_ropAv</code> là nguồn ROP thứ ba; 26 wellbore thuộc 11 giếng, chưa chốt nhóm split [XM] (plan §12 ý 9)."],
["2026-10-29","Đổi tên thư mục project từ <code>Scientific</code> thành <code>Volve-DIA</code>; sửa đường dẫn trong <code>.venv</code>. Commit đầu tiên trên <code>main</code>, push lên Gitea <code>lamlvh/Volve-DIA</code> (public). Bản đánh giá <code>docs/danh-gia-huong-NCKH-2026-10-29.md</code> trích tài liệu nội bộ nên để ngoài git (plan §12 ý 10)."]
["2026-10-29","Đổi tên thư mục project từ <code>Scientific</code> thành <code>Volve-DIA</code>; sửa đường dẫn trong <code>.venv</code>. Commit đầu tiên trên <code>main</code>, push lên Gitea <code>lamlvh/Volve-DIA</code> (public). Bản đánh giá <code>docs/danh-gia-huong-NCKH-2026-10-29.md</code> trích tài liệu nội bộ nên để ngoài git (plan §12 ý 10)."],
["2026-10-29","Kiểm điều kiện bắt đầu M1: bắt đầu được theo lịch, chỉ OCR toàn bộ còn bị chặn (dịch vụ vẫn 503 lúc 13:04). Manifest dữ liệu đạt (25.570 file), 40 test đạt, WITSML đủ loại object, mạng ra ngoài thông. Tìm thấy nguồn formation tops (<code>Well_picks_Volve_v1.dat</code>, 409 pick, 35 wellbore). <code>/home</code> dùng 98% (còn 274 GB); hai GPU đầy do job khác, M1 không cần GPU (plan §12 ý 11)."],
["2026-11-17","Đồng nghiệp chạy xong OCR toàn tập, xuất qua Dataset Hub. <code>04_ocr_hub.py</code> ghép trang về DDR bằng nội dung: lượt đầu ghép nhầm 3 trang, sửa bằng sàn F1 chữ 0,7; lượt cuối 3.059/3.066 trang, 1.752/1.759 báo cáo. QC toàn tập: CER 2,40%, khớp 0,9181, WER 5,56% (plan §1.3, §12 ý 12)."],
["2026-11-17","Parser WITSML (agent con): 21 wellbore DDR có log thời gian, 1.384 báo cáo, 2,25 tỉ giá trị; <code>15/9-F-15 S</code> là DDR F-15; formation tops 409 pick; manifest 25.571 file; 141 test đạt (plan §12 ý 14)."],
["2026-11-17","Nhãn T1–T3 (<code>07_labels.py</code>, luật điền <code>ffill</code>), T4 1.662 câu hỏi với đáp án SQL, pandas và XML thô khớp 100%, mẫu audit thử 100 dòng chấm mù bởi LLM rater (không phải audit của tác giả), <code>protocol_v1</code> bản nháp (split theo giếng, leave-one-well-out) (plan §12 ý 15, 16)."],
["2026-11-17","Đọc tài liệu và bộ nhãn bên thứ ba (<code>docs/literature_notes.md</code>): không có nhãn NPT khoan độc lập; thêm hai đối thủ ADIPEC; sửa dòng Bassey và PetroAgents trong plan. <code>data/Volve</code> thành thư mục thật. Phân công agent: chỉ Sonnet, Opus cho việc rất phức tạp, không dùng Fable."],
["2026-11-17","Bản thử LLM rater (Sonnet, Opus, Haiku) trên 100 dòng; κ giữa rater cao hơn κ với nhãn code. Đọc toàn văn PetroAgents (well-day, 60 ví dụ mỗi seed, phép cắt lộ mã trên 30 ví dụ, split theo wellbore). Chốt các quyết định còn mở: giá trị đáng ngờ của WITSML, pick formation, TD F-15, 7 báo cáo OCR chưa ghép (plan §12 ý 21)."]
];
/* ===================== HẾT DATA ===================== */

View File

@@ -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
View 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())

View File

@@ -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
View 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
View 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
View 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
View 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
View 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 &amp; tiếp →</button></div></form>
</main><script>
const D=__DATA__,CAUSES=__CAUSES__,OPS=__OPS__,K="volve-dia-trial-audit-v1";
let S={};try{S=JSON.parse(localStorage.getItem(K)||"{}")}catch(e){}
let i=Math.max(0,D.findIndex(d=>!(S[d.item]&&S[d.item].r_npt)));if(i<0)i=0;
let t0=Date.now(),acc=0;
document.addEventListener("visibilitychange",()=>{if(document.hidden){acc+=Date.now()-t0}else{t0=Date.now()}});
function radios(el,name,vals,labels){el.textContent="";vals.forEach((v,k)=>{const l=document.createElement("label");
const r=document.createElement("input");r.type="radio";r.name=name;r.value=v;l.append(r," "+(labels?labels[k]:v));
el.append(l)})}
radios(npt,"r_npt",["y","n","?"],["có","không","không rõ"]);radios(cause,"r_cause",CAUSES);radios(op,"r_op_class",OPS);
radios(conf,"r_confidence",["1","2","3"],["1 thấp","2","3 cao"]);
function save(){try{localStorage.setItem(K,JSON.stringify(S))}catch(e){}}
function show(){const d=D[i],s=S[d.item]||{};
meta.textContent=`${d.item} · ${d.wellbore} · báo cáo ${d.report_date} · ${d.start_utc} → ${d.end_utc} · `+
`${d.duration_h} h · MD ${d.md} m · ${d.rig_phase}`;
sum.textContent=d.sum24Hr;prev.textContent=d.prev_comment?"Trước: "+d.prev_comment:"(hoạt động đầu tiên)";
cur.textContent=d.comment;next.textContent=d.next_comment?"Sau: "+d.next_comment:"(hoạt động cuối cùng)";
for(const n of["r_npt","r_cause","r_op_class","r_confidence"])f.querySelectorAll(`input[name=${n}]`)
.forEach(r=>r.checked=s[n]===r.value);note.value=s.r_note||"";
prog.textContent=`${i+1}/${D.length} · đã chấm ${D.filter(d=>S[d.item]&&S[d.item].r_npt).length}`;
t0=Date.now();acc=0;window.scrollTo(0,0)}
function store(){const d=D[i],s=S[d.item]||{};const fd=new FormData(f);
for(const n of["r_npt","r_cause","r_op_class","r_confidence"])s[n]=fd.get(n)||"";s.r_note=note.value;
s.r_seconds=String(Math.round(((s.r_seconds?+s.r_seconds:0)*1000+acc+(document.hidden?0:Date.now()-t0))/1000));
S[d.item]=s;save()}
go.onclick=()=>{if(!new FormData(f).get("r_npt")){alert("Chọn NPT trước");return}store();
if(i<D.length-1){i++;show()}else{alert("Đã hết mục. Hãy xuất RATINGS.csv.")}};
back.onclick=()=>{store();if(i>0){i--;show()}};
exp.onclick=()=>{store();const cols=["item","r_npt","r_cause","r_op_class","r_confidence","r_seconds","r_note"];
const q=v=>'"'+String(v??"").replace(/"/g,'""')+'"';
const csv=[cols.join(",")].concat(D.map(d=>{const s=S[d.item]||{};return[d.item].concat(cols.slice(1)
.map(c=>s[c]||"")).map(q).join(",")})).join("\n");
const a=document.createElement("a");a.href=URL.createObjectURL(new Blob([""+csv],{type:"text/csv"}));
a.download="RATINGS.csv";a.click()};
show();
</script></body></html>
"""
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("sample")
sc = sub.add_parser("score")
sc.add_argument("ratings", type=Path)
a = ap.parse_args()
return sample() if a.cmd == "sample" else score(a.ratings)
if __name__ == "__main__":
sys.exit(main())

View 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
View 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

39
tests/test_audit.py Normal file
View File

@@ -0,0 +1,39 @@
import numpy as np
import pandas as pd
import pytest
from volve_dia import audit
def test_allocate_minimum_then_sqrt_share():
a = audit.allocate({"big": 1600, "mid": 100, "tiny": 1}, 20, 2)
assert sum(a.values()) == 20 and a["tiny"] == 1 and a["mid"] >= 2 and a["big"] > a["mid"]
assert audit.allocate({"x": 3, "y": 3}, 10, 2) == {"x": 3, "y": 3} # never more than a stratum holds
with pytest.raises(ValueError):
audit.allocate({s: 10 for s in "abcdef"}, 5, 1)
def test_draw_weights_and_spread_over_wells():
f = pd.DataFrame({"act_id": range(400), "well": np.repeat(list("ABCD"), 100),
"zone": ["a"] * 100 + ["none"] * 300, "stratum": ["a/x"] * 100 + ["none/y"] * 300})
s = audit.draw(f, {"a": 8, "none": 8}, 2, seed=1)
assert len(s) == 16 and s["act_id"].is_unique
assert set(s.loc[s["zone"] == "none", "well"]) == {"B", "C", "D"} # spread over the wells of the stratum
assert s.groupby("stratum")["weight"].first().to_dict() == {"a/x": 12.5, "none/y": 37.5}
assert audit.draw(f, {"a": 8, "none": 8}, 2, seed=1)["act_id"].tolist() == s["act_id"].tolist()
def test_cohen_kappa():
a = pd.Series(list("yynnyn"))
assert audit.cohen_kappa(a, a) == pytest.approx(1.0)
b = pd.Series(list("ynynyn"))
po, pe = 4 / 6, 0.5 * 0.5 + 0.5 * 0.5
assert audit.cohen_kappa(a, b) == pytest.approx((po - pe) / (1 - pe))
w = pd.Series([1, 1, 1, 1, 1, 1.0])
assert audit.cohen_kappa(a, b, w) == pytest.approx(audit.cohen_kappa(a, b))
assert audit.cohen_kappa(pd.Series(["y", "y"]), pd.Series(["y", "y"])) is None # pe = 1
def test_zone():
z = audit.zone(pd.Series([True, False, False]), pd.Series([True, True, False]))
assert z.tolist() == ["a", "b_only", "none"]

642
tests/test_labels.py Normal file
View File

@@ -0,0 +1,642 @@
"""volve_dia.labels: every rule of T1-T3 on small synthetic frames, then the locked counts on the Volve tables
(`data` marker; skipped without outputs/ddr or the DDR XML folder)."""
import importlib.util
import numpy as np
import pandas as pd
import pytest
from volve_dia import labels as L
from volve_dia import paths
CFG = L.load_config()
# ---------------------------------------------------------------------------------------------------------------
# Synthetic frames
# ---------------------------------------------------------------------------------------------------------------
def _ts(day: int, hour: float = 0.0) -> pd.Timestamp:
return pd.Timestamp("2010-01-01", tz="UTC") + pd.Timedelta(days=day, hours=hour)
def _reports(rows: list[dict]) -> pd.DataFrame:
"""One report per row, one day each; defaults for every column the label code reads."""
out = []
for i, row in enumerate(rows):
day = row.pop("day", i)
wellbore = row.pop("wellbore", "15/9-F-1")
base = {"report_id": f"{wellbore}#{day:03d}", "wellbore": wellbore, "file_date": str(_ts(day + 1).date()),
"start_utc": _ts(day), "end_utc": _ts(day + 1), "dTimSpud": "2010-01-01T00:00:00+00:00",
"diaHole": np.nan, "diaPilot": np.nan, "mdDiaHoleStart": np.nan, "mdCsgLast": np.nan, "md": np.nan,
"tvd": np.nan, "distDrill": np.nan, "waterDepth": 91.0, "elevKelly": 54.9, "reportNo": day + 1,
"sum24Hr": "None", "forecast24Hr": "None", "rigAlias_NPD_Name": "RIG", "operator": "OP",
"drillContractor": "DC"}
out.append({**base, **row})
return pd.DataFrame(out)
def _activities(rows: list[tuple]) -> pd.DataFrame:
"""(report_id, wellbore, start hour within the series, hours, md, code, state, detail, comment)."""
out, seq = [], {}
for report_id, wellbore, start, hours, md, code, state, detail, comment in rows:
n = seq[report_id] = seq.get(report_id, -1) + 1
main, sub = code.split(" -- ")
out.append({"report_id": report_id, "wellbore": wellbore, "seq": n, "act_id": f"{report_id}:{n:03d}",
"md": md, "phase": "fixed", "proprietaryCode": code, "code_main": main, "code_sub": sub,
"state": state, "stateDetailActivity": detail, "comments": comment,
"start_utc": _ts(0, start), "end_utc": _ts(0, start + hours), "duration_h": float(hours)})
return pd.DataFrame(out)
EMPTY_BITS = pd.DataFrame({"report_id": [], "wellbore": [], "diaBit": []})
EMPTY_CASINGS = pd.DataFrame({"report_id": [], "wellbore": [], "od": [], "mdBottom": []})
W = "15/9-F-1"
def _one_activity_per_report(reports: pd.DataFrame, code: str = "drilling -- drill") -> pd.DataFrame:
return _activities([(r.report_id, r.wellbore, 24.0 * i, 24.0, 500.0, code, "ok", "success", "x")
for i, r in enumerate(reports.itertuples())])
# ---------------------------------------------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------------------------------------------
def test_config_maps_all_64_codes_to_declared_classes():
assert CFG["version"] == 1 and len(CFG["codes"]) == 64
assert sum(r["n"] for r in CFG["codes"].values()) == 23447
assert {r["op_class"] for r in CFG["codes"].values()} == set(CFG["t1"]["op_classes"])
interruption = {c: r for c, r in CFG["codes"].items() if c.startswith("interruption -- ")}
assert len(interruption) == 10 and {r["op_class"] for r in interruption.values()} == {"interruption"}
assert sum(r["n"] for r in interruption.values()) == 3577
assert all(r["cause"] == "detail" for c, r in CFG["codes"].items() if c not in interruption)
assert sum(r["n"] for r in CFG["t1"]["hole_sizes"].values()) == 769
@pytest.mark.parametrize("old, new, message", [
("op_class: trip,", "op_class: tripping,", "op_class"),
("cause: weather}", "cause: storm}", "cause"),
("version: 1", "version: 2", "version"),
('"drilling -- drill": {n: 1822, op_class: drill_ream, cause: detail}',
'"drilling -- drill": {n: 1822, op_class: drill_ream, cause: weather}',
"only interruption codes"),
])
def test_config_rejects_undeclared_classes(tmp_path, old, new, message):
text = (paths.REPO_ROOT / "configs" / "labels.yaml").read_text(encoding="utf-8")
assert old in text
bad = tmp_path / "labels.yaml"
bad.write_text(text.replace(old, new, 1), encoding="utf-8")
with pytest.raises(ValueError, match=message):
L.load_config(bad)
def test_check_code_counts_reports_every_difference():
a = _activities([("r", W, 0, 1, 0.0, "drilling -- drill", "ok", "success", "x")])
diff = L.check_code_counts(a, CFG)
assert diff["drilling -- drill"] == (1822, 1) and diff["drilling -- trip"] == (1430, None)
assert diff["state=ok"] == (22967, 1) and diff["stateDetailActivity=success"] == (20802, 1)
# ---------------------------------------------------------------------------------------------------------------
# T1: text sizes, masks, fill rules
# ---------------------------------------------------------------------------------------------------------------
@pytest.mark.parametrize("text, expected", [
('Drilled 12 1/4" hole from 2842 m to 2872 m MD', [12.25]),
("DRILLED 8-1/2\" HOLE", [8.5]),
("Drilled 8½\" hole and 17 ½\" section", [8.5, 17.5]),
("Drilled 17,5\" hole; drilled 12.25 in hole", [17.5, 12.25]),
('OPENED 9 7/8" PILOTHOLE TO 26" HOLE FROM 170 M', [9.875, 26.0]),
('Ran 9 5/8" casing. Made up 8 1/2" BHA. POOH with 5 1/2" DP', []), # not a hole size wording
('Drilled 16" hole', []), # not a size of this field
('pressure tested to 345 bar / 12 1/4" hole', [12.25]),
(None, []),
])
def test_hole_sizes_in_text(text, expected):
sizes = tuple(float(s) for s in CFG["t1"]["hole_sizes"])
assert L.hole_sizes_in_text(text, sizes) == expected
def test_known_runs_and_masks():
dia = np.array([np.nan, 36, 36, 26, 26, 26, 26, np.nan, 26, 17.5])
assert [r.tolist() for r in L.known_runs(dia)] == [[1, 2], [3, 4, 5, 6], [8], [9]]
assert [m.tolist() for m in L.fill_masks(dia, "single")] == [[1], [2], [3], [4], [5], [6], [8], [9]]
assert [m.tolist() for m in L.fill_masks(dia, "tail_half")] == [[2], [5, 6]]
assert [m.tolist() for m in L.fill_masks(dia, "head_half")] == [[1], [3, 4]]
assert [m.tolist() for m in L.fill_masks(dia, "whole_run")] == [[1, 2], [3, 4, 5, 6], [8], [9]]
with pytest.raises(ValueError):
L.fill_masks(dia, "random")
def _wellbore_frame() -> pd.DataFrame:
"""Ten days: lead-in, 36" (2 days), 26" (3 days), two days without diaHole, 17.5" (2 days)."""
dia = [np.nan, 36, 36, 26, 26, 26, np.nan, np.nan, 17.5, 17.5]
return pd.DataFrame({
"dia": dia, "start_utc": [_ts(i) for i in range(10)],
"mdDiaHoleStart": [0, 145, 145, 200, 200, 200, 1400, 1400, 1405, 1405],
"mdCsgLast": [np.nan, np.nan, 195, 195, 195, 1390, 1390, 1390, 1390, 1390],
"md": [0, 180, 200, 800, 1400, 1400, 1400, 1400, 1900, 2500],
"bit_dia": [np.nan, 36, np.nan, 26, np.nan, np.nan, np.nan, 17.5, np.nan, np.nan],
"casing_hole": [np.nan, np.nan, 26, 26, 26, 17.5, 17.5, 17.5, 17.5, 17.5],
"text_dia": [np.nan, 36, np.nan, np.nan, 26, np.nan, np.nan, np.nan, 17.5, np.nan]})
def test_fill_rules_on_one_wellbore():
g = _wellbore_frame()
nan = np.nan
np.testing.assert_array_equal(L.FILL_RULES["ffill"](g), [nan, 36, 36, 26, 26, 26, 26, 26, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["bfill"](g), [36, 36, 36, 26, 26, 26, 17.5, 17.5, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["ffill_bfill"](g), [36, 36, 36, 26, 26, 26, 26, 26, 17.5, 17.5])
# day 6 is one day after 26" and two before 17.5"; day 7 is two after and one before
np.testing.assert_array_equal(L.FILL_RULES["nearest"](g), [36, 36, 36, 26, 26, 26, 26, 17.5, 17.5, 17.5])
# the header opens a new record (1400 m) on the days without diaHole: no known report shares it
np.testing.assert_array_equal(L.FILL_RULES["hole_start"](g), [nan, 36, 36, 26, 26, 26, nan, nan, 17.5, 17.5])
# shoe at 195 m is shared by one 36" day and two 26" days; shoe at 1390 m by one 26" day and two 17.5" days
np.testing.assert_array_equal(L.FILL_RULES["csg_last"](g), [nan, nan, 26, 26, 26, 17.5, 17.5, 17.5, 17.5, 17.5])
# md 1400 lies in the 26" range [800, 1400] only; md 0 in none; 200 m in the 36" range [180, 200]
np.testing.assert_array_equal(L.FILL_RULES["depth_range"](g), [nan, 36, 36, 26, 26, 26, 26, 26, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["bit_ffill"](g), [nan, 36, 36, 26, 26, 26, 26, 17.5, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["casing_program"](g), g["casing_hole"])
np.testing.assert_array_equal(L.FILL_RULES["text"](g), g["text_dia"])
def test_evaluate_fill_rules_counts_masked_answered_correct():
g = _wellbore_frame().assign(wellbore=W, status="ok")
ev = L.evaluate_fill_rules(g, rules=("ffill", "bfill", "bit_report"))
s = L.summarise_fill_eval(ev).set_index(["rule", "scheme"])
# single: 7 known days; ffill misses the first day of each of the three runs (one of them unanswered)
assert tuple(s.loc[("ffill", "single"), ["n_masked", "n_answered", "n_correct"]]) == (7, 6, 4)
assert tuple(s.loc[("bfill", "single"), ["n_masked", "n_answered", "n_correct"]]) == (7, 6, 4)
# tail_half masks days 2, 5 and 9: the head of each run stays visible
assert tuple(s.loc[("ffill", "tail_half"), ["n_masked", "n_correct"]]) == (3, 3)
assert tuple(s.loc[("bfill", "tail_half"), ["n_masked", "n_answered", "n_correct"]]) == (3, 2, 0)
assert tuple(s.loc[("bfill", "head_half"), ["n_masked", "n_correct"]]) == (3, 3)
assert tuple(s.loc[("ffill", "whole_run"), ["n_masked", "n_answered", "n_correct"]]) == (7, 5, 0)
# a rule that does not read diaHole answers the same under every scheme
assert tuple(s.loc[("bit_report", "single"), ["n_masked", "n_answered", "n_correct"]]) == (7, 2, 2)
assert s.loc[("ffill", "single"), "recovered"] == round(4 / 7, 4)
assert s.loc[("ffill", "single"), "coverage"] == round(6 / 7, 4)
assert s.loc[("bit_report", "single"), "precision"] == 1.0
def test_fill_on_missing_compares_with_text_and_bit():
g = _wellbore_frame().assign(wellbore=W, status="ok", n_drilling_activities=[0, 1, 1, 1, 1, 1, 1, 0, 1, 1])
g.loc[7, "text_dia"] = 26.0
m = L.fill_on_missing(g, rules=("ffill", "bfill")).set_index(["rule", "subset"])
row = m.loc[("ffill", "all_missing")]
assert (row["n"], row["n_answered"], row["n_text"], row["n_both"], row["n_agree_text"]) == (3, 2, 1, 1, 1)
assert (row["n_bit"], row["n_both_bit"], row["n_agree_bit"]) == (1, 1, 0) # bit says 17.5 on day 7
assert m.loc[("bfill", "all_missing"), "n_agree_bit"] == 1
assert m.loc[("ffill", "missing_drilling_day"), "n"] == 1
# ---------------------------------------------------------------------------------------------------------------
# T1 labels
# ---------------------------------------------------------------------------------------------------------------
def test_timeline_status_and_placeholder_rule():
r = _reports([{"day": -6000, "sum24Hr": "None"}, {"day": 0}, {"day": 1}, {"day": -200}])
a = _activities([(r.report_id[1], W, 0, 24, 0.0, "drilling -- drill", "ok", "success", "x"),
(r.report_id[1], W, 0, 1, 0.0, "moving -- skid", "ok", "success", "x"),
(r.report_id[3], W, 0, 24, 0.0, "moving -- skid", "ok", "success", "x")])
tl = L.timeline(r, a, CFG).set_index("report_id")
assert tl.loc[r.report_id[0], "status"] == "placeholder_date" # no activity, 16 years before spud
assert tl.loc[r.report_id[2], "status"] == "no_activities" # no activity, real date
assert tl.loc[r.report_id[3], "status"] == "ok" # before spud but with activities
assert tl.loc[r.report_id[1], ["n_activities", "n_drilling_activities"]].tolist() == [2, 1]
assert tl["well"].eq("15/9-F-1").all() and tl.index.tolist() == [r.report_id[i] for i in (0, 3, 1, 2)]
def test_t1_reports_fill_provenance_and_phase():
r = _reports([{"day": -6000}, # placeholder
{"day": 0}, {"day": 1}, # before the first section
{"day": 2, "diaHole": 8.5, "diaPilot": 8.5}, # pilot
{"day": 3, "diaHole": 26.0},
{"day": 4}, {"day": 9}, # after the 26" section
{"day": 10, "diaHole": 12.25},
{"day": 11, "wellbore": "15/9-F-1 A", "diaHole": 6.0},
{"day": 12, "wellbore": "15/9-F-1 A"}])
a = _one_activity_per_report(r.iloc[[1, 3, 4, 5, 7, 8, 9]])
a.loc[a["report_id"].eq(r.report_id[9]), ["proprietaryCode", "code_main", "code_sub"]] = [
"completion -- perforate", "completion", "perforate"]
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
ops = L.operation_classes(a, CFG)
t = L.t1_reports(feat, ops, a, CFG).set_index("report_id")
ids = r.report_id.tolist()
assert t.loc[ids[0], ["status", "filled_by", "scope"]].tolist() == ["placeholder_date", "none", "excluded"]
assert pd.isna(t.loc[ids[0], "section"]) and pd.isna(t.loc[ids[0], "phase"])
# leading days take the first section and inherit its pilot flag
assert t.loc[ids[1], ["section", "phase", "filled_by", "section_rule"]].tolist() == [
"8.5", "pilot", "bfill_leading", "T1.S3"]
assert t.loc[ids[1], "fill_source_report_id"] == ids[3] and t.loc[ids[1], "fill_gap_reports"] == 2
assert t.loc[ids[2], "scope"] == "no_activities" and t.loc[ids[2], "section"] == "8.5"
assert t.loc[ids[3], ["section", "phase", "filled_by", "phase_rule"]].tolist() == [
"8.5", "pilot", "diaHole", "T1.P2"]
assert t.loc[ids[4], ["section", "phase", "filled_by", "section_rule", "phase_rule"]].tolist() == [
"26", "surface", "diaHole", "T1.S1", "T1.P1"]
assert pd.isna(t.loc[ids[4], "fill_gap_days"]) or t.loc[ids[4], "fill_gap_days"] == 0
# forward fill, with the distance to the source report
assert t.loc[ids[5], ["section", "filled_by", "fill_source_report_id", "section_rule"]].tolist() == [
"26", "ffill", ids[4], "T1.S2"]
assert t.loc[ids[6], ["fill_gap_reports", "fill_gap_days"]].tolist() == [2, 6.0]
assert t.loc[ids[7], ["section", "phase"]].tolist() == ["12.25", "production"]
# the fill never crosses to another wellbore; 6" shares the reservoir phase
assert t.loc[ids[9], ["section", "phase", "filled_by", "scope"]].tolist() == [
"6", "reservoir", "ffill", "other_day"]
assert t.loc[ids[8], ["day_op_group", "day_op_class", "day_op_class_share"]].tolist() == [
"drilling", "drill_ream", 1.0]
assert t["section_witsml"].isna().all() and t["section_agree"].isna().all()
def test_day_operation_is_the_class_with_most_hours():
r = _reports([{"day": 0, "diaHole": 26.0}])
rid = r.report_id[0]
a = _activities([(rid, W, 0, 5, 300.0, "drilling -- drill", "ok", "success", "x"),
(rid, W, 5, 4, 300.0, "drilling -- trip", "ok", "success", "x"),
(rid, W, 9, 4, 300.0, "plug abandon -- trip", "ok", "success", "x"),
(rid, W, 13, 7, 0.0, "interruption -- repair", "ok", "equipment failure", "x")])
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
t = L.t1_reports(feat, L.operation_classes(a, CFG), a, CFG).iloc[0]
assert (t["day_op_class"], t["day_op_class_share"]) == ("trip", 0.4) # 8 h in two main groups
assert (t["day_op_group"], t["day_op_group_share"]) == ("drilling", 0.45)
assert t["scope"] == "drilling_day"
def test_fill_features_bits_casings_text():
r = _reports([{"day": 0, "mdCsgLast": 1390.0, "sum24Hr": 'Drilled 17 1/2" hole to 1500 m'},
{"day": 1, "mdCsgLast": 1390.0}, {"day": 2, "mdCsgLast": 2500.0}, {"day": 3}])
ids = r.report_id.tolist()
a = _activities([(ids[0], W, 0, 24, 1500.0, "drilling -- drill", "ok", "success", 'Drilled 17 1/2" hole'),
(ids[1], W, 24, 12, 0.0, "drilling -- trip", "ok", "success", 'POOH with 17 1/2" BHA'),
(ids[1], W, 36, 12, 0.0, "completion -- other", "ok", "success", 'Drilled 8 1/2" hole'),
(ids[2], W, 48, 24, 0.0, "drilling -- drill", "ok", "success", '12 1/4" hole and 8 1/2" hole'),
(ids[3], W, 72, 24, 0.0, "drilling -- drill", "ok", "success", "x")])
bits = pd.DataFrame({"report_id": [ids[0], ids[0], ids[1]], "wellbore": W, "diaBit": [17.5, 36.0, -999.0]})
casings = pd.DataFrame({"report_id": [ids[0], ids[0]], "wellbore": ["15/9-F-1", "15/9-F-1 A"],
"od": [20.0, 13.375], "mdBottom": [1388.9, 2520.0]})
f = L.fill_features(L.timeline(r, a, CFG), a, bits, casings, CFG).set_index("report_id")
np.testing.assert_array_equal(f["bit_dia"], [36.0, np.nan, np.nan, np.nan]) # largest valid bit
# 20" shoe 1.1 m away -> 17.5"; the shoe of the sidetrack of the same well is 20 m away: out of tolerance
np.testing.assert_array_equal(f["casing_hole"], [17.5, 17.5, np.nan, np.nan])
# only drilling-group comments and sum24Hr are read; a tie between two sizes gives no answer
np.testing.assert_array_equal(f["text_dia"], [17.5, np.nan, np.nan, np.nan])
def test_operation_classes_cover_every_code_and_reject_unknown():
a = _activities([("r", W, i, 1, 0.0, code, "ok", "success", "x") for i, code in enumerate(CFG["codes"])])
ops = L.operation_classes(a, CFG)
assert ops["op_class"].tolist() == [r["op_class"] for r in CFG["codes"].values()]
assert ops["op_group"].nunique() == 7 and ops["op_sub"].nunique() == 41 and ops["op_class"].nunique() == 15
by_code = dict(zip(a["proprietaryCode"], ops["op_class"]))
assert by_code["plug abandon -- trip"] == by_code["formation evaluation -- trip"] == "trip"
assert by_code["plug abandon -- other"] == by_code["drilling -- other"] == "other"
assert by_code["interruption -- other"] == by_code["interruption -- waiting on weather"] == "interruption"
bad = a.assign(proprietaryCode="drilling -- fly")
with pytest.raises(ValueError, match="drilling -- fly"):
L.operation_classes(bad, CFG)
def test_t1_activities_inherit_the_section_of_the_day():
r = _reports([{"day": 0, "diaHole": 26.0}, {"day": 1}])
a = _one_activity_per_report(r)
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
ops = L.operation_classes(a, CFG)
t = L.t1_activities(ops, L.t1_reports(feat, ops, a, CFG))
assert t["act_id"].tolist() == a["act_id"].tolist()
assert t[["section", "phase", "filled_by", "op_class", "op_rule"]].values.tolist() == [
["26", "surface", "diaHole", "drill_ream", "T1.O1"], ["26", "surface", "ffill", "drill_ream", "T1.O1"]]
def test_witsml_section_hook():
r = _reports([{"day": 0, "diaHole": 26.0}, {"day": 1, "diaHole": 26.0}, {"day": 2}])
a = _one_activity_per_report(r)
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
t1 = L.t1_reports(feat, L.operation_classes(a, CFG), a, CFG)
assert L.attach_witsml_section(t1, None) is t1
w = pd.DataFrame({"wellbore": W, "start_utc": [_ts(0), _ts(1, 6)], "end_utc": [_ts(1, 6), _ts(2)],
"section_in": [26.0, 17.5]})
t = L.attach_witsml_section(t1, w)
assert t["section_witsml"].tolist()[:2] == [26.0, 17.5] and pd.isna(t["section_witsml"][2])
assert t["section_agree"].tolist()[:2] == [True, False] and pd.isna(t["section_agree"][2])
# ---------------------------------------------------------------------------------------------------------------
# T2
# ---------------------------------------------------------------------------------------------------------------
T2_ROWS = [
# code, state, detail -> npt_a, npt_b, cause, rule, conflict
("drilling -- drill", "ok", "success", False, False, "none", None, False),
("interruption -- repair", "ok", "success", True, True, "equipment", "T2.C1", False),
("interruption -- maintain", "ok", "operation failed", True, True, "equipment", "T2.C1", True),
("interruption -- waiting on weather", "ok", "success", True, True, "weather", "T2.C1", False),
("interruption -- wait", "ok", "success", True, True, "waiting", "T2.C1", False),
("interruption -- fish", "fail", "stuck equipment", True, True, "stuck_fishing", "T2.C1", False),
("interruption -- well control", "ok", "circulation loss", True, True, "well_control", "T2.C1", True),
("interruption -- sidetrack", "ok", "success", True, True, "sidetrack", "T2.C1", False),
("interruption -- lost circulation", "fail", "success", True, True, "lost_circulation", "T2.C1", False),
("interruption -- other", "ok", "equipment failure", True, True, "equipment", "T2.C2", False),
("interruption -- other", "ok", "mud loss", True, True, "lost_circulation", "T2.C2", False),
("interruption -- rig up/down", "ok", "operation failed", True, True, "operation_failed", "T2.C2", False),
("interruption -- other", "ok", "success", True, True, "unspecified", "T2.C3", False),
("drilling -- casing", "ok", "equipment failure", False, True, "equipment", "T2.C2", False),
("plug abandon -- other", "fail", "stuck equipment", False, True, "stuck_fishing", "T2.C2", False),
("drilling -- ream", "ok", "circulation loss", False, True, "lost_circulation", "T2.C2", False),
("drilling -- casing", "ok", "injury", False, True, "hse", "T2.C2", False),
("formation evaluation -- log", "fail", "success", False, True, "unspecified", "T2.C3", False),
("drilling -- wait", "ok", "success", False, False, "none", None, False),
]
def test_t2_labels_rules():
a = _activities([("r", W, i, 1, 0.0, code, state, detail, "x")
for i, (code, state, detail, *_) in enumerate(T2_ROWS)])
t = L.t2_labels(a, CFG)
for row, (code, state, detail, npt_a, npt_b, cause, rule, conflict) in zip(t.itertuples(), T2_ROWS):
case = (code, state, detail)
assert (row.npt_a, row.npt_b) == (npt_a, npt_b), case
assert row.cause_group == row.cause_b == cause, case
assert row.cause_a == (cause if npt_a else "none"), case
assert (row.cause_rule == rule if rule else pd.isna(row.cause_rule)) and row.cause_conflict == conflict, case
by_case = {(c, d): r for r, (c, _, d, *_) in zip(t.itertuples(), T2_ROWS)}
wc = by_case[("interruption -- well control", "circulation loss")]
assert (wc.cause_from_code, wc.cause_from_detail, wc.cause_fine) == (
"well_control", "lost_circulation", "well_control")
assert by_case[("interruption -- other", "equipment failure")].cause_fine == "equipment_failure"
assert by_case[("interruption -- waiting on weather", "success")].cause_fine == "waiting_on_weather"
assert by_case[("interruption -- other", "success")].cause_fine == "unspecified"
assert by_case[("drilling -- drill", "success")].cause_fine == "none"
assert pd.isna(by_case[("drilling -- drill", "success")].cause_from_code)
assert t["wait_code_outside_interruption"].tolist() == [False] * 18 + [True]
assert t["is_state_fail"].sum() == 4 and t["is_detail_nonsuccess"].sum() == 10
assert set(t["cause_group"]) - {"none"} <= set(CFG["t2"]["cause_groups"])
def test_t2_precedence_can_be_reversed():
cfg = {**CFG, "t2": {**CFG["t2"], "precedence": ["detail", "code", "default"]}}
a = _activities([("r", W, 0, 1, 0.0, "interruption -- well control", "ok", "circulation loss", "x"),
("r", W, 1, 1, 0.0, "interruption -- repair", "ok", "success", "x")])
t = L.t2_labels(a, cfg)
assert t["cause_group"].tolist() == ["lost_circulation", "equipment"]
assert t["cause_rule"].tolist() == ["T2.C2", "T2.C1"]
def test_t2_inputs_hide_every_code_column():
r = _reports([{"day": 0, "diaHole": 26.0, "sum24Hr": "Drilled.", "forecast24Hr": "Drill."}])
a = _activities([(r.report_id[0], W, 0, 24, 300.0, "interruption -- repair", "fail", "equipment failure", "text")])
view = L.t2_inputs(a, r, CFG)
assert not set(view.columns) & set(L.MASKED)
assert not any("interruption" in str(v) or "equipment failure" in str(v) or v == "fail" for v in view.iloc[0])
row = view.iloc[0]
assert (row["comments"], row["sum24Hr"], row["forecast24Hr"], row["rig_phase"]) == (
"text", "Drilled.", "Drill.", "fixed")
assert (row["well"], row["report_diaHole"], row["md"]) == ("15/9-F-1", 26.0, 300.0)
leaky = {**CFG, "t2": {**CFG["t2"], "input_activity_columns": ["act_id", "report_id", "wellbore", "state"]}}
with pytest.raises(ValueError, match="masked columns"):
L.t2_inputs(a, r, leaky)
def test_text_rates_and_literal_sub_codes():
r = _reports([{"day": 0, "sum24Hr": "Waited on weather all day."}, {"day": 1, "sum24Hr": "None"}])
ids = r.report_id.tolist()
wow, trip = "interruption -- waiting on weather", "drilling -- trip"
a = _activities([(ids[0], W, 0, 6, 0.0, wow, "ok", "success", "WOW. Wind 45 knots."),
(ids[0], W, 6, 6, 0.0, wow, "ok", "success", "Serviced TDS."),
(ids[0], W, 12, 12, 0.0, trip, "ok", "success", "POOH. Tripping speed 300 m/hr."),
(ids[1], W, 24, 12, 0.0, trip, "ok", "success", "RIH."),
(ids[1], W, 36, 12, 0.0, "interruption -- fish", "ok", "stuck equipment", "Pipe stuck at 3558.")])
t2 = L.t2_labels(a, CFG)
rates = L.text_rates(a, r, t2, CFG).set_index(["target", "definition", "scope"])
w = rates.loc[("weather", "a", "comment")]
assert (w["n_pos"], w["hit_pos"], w["n_neg"], w["hit_neg"]) == (2, 1, 3, 0)
assert (w["recall"], w["fpr"], w["precision"]) == (0.5, 0.0, 1.0)
w = rates.loc[("weather", "a", "comment+sum24Hr")] # the summary names the weather for the whole day
assert (w["hit_pos"], w["hit_neg"]) == (2, 1)
assert rates.loc[("stuck_fishing", "b", "comment"), "recall"] == 1.0
assert rates.loc[("npt", "a", "comment"), "hit_pos"] == 2 # "wow", "stuck"
assert len(rates) == len(CFG["text_lexicon"]) * 2 * 2
lit = L.code_sub_literal(a).set_index("code_sub")
assert lit.loc["trip", ["n", "hit", "rate"]].tolist() == [2, 1, 0.5]
assert lit.loc["waiting on weather", "rate"] == 0.0 and lit.loc["fish", "rate_other_rows"] == 0.0
# ---------------------------------------------------------------------------------------------------------------
# T3
# ---------------------------------------------------------------------------------------------------------------
def _t3_case():
"""One wellbore, mud line 145.9 m. (hour, md) of the rows: drill (0, 300), repair (1, 305), repair (2, 318),
drill (3, 400), repair (4, 0), repair (5, 100), failed trip (6, 334), drill (7, 500), weather (40, 505)."""
r = _reports([{"day": 0, "diaHole": 26.0, "mdDiaHoleStart": 200.0, "md": 600.0}])
rid = r.report_id[0]
drill, repair = "drilling -- drill", "interruption -- repair"
rows = [(0, 300.0, drill, "ok", "success"), (1, 305.0, repair, "ok", "success"),
(2, 318.0, repair, "ok", "equipment failure"), (3, 400.0, drill, "ok", "success"),
(4, 0.0, repair, "ok", "success"), (5, 100.0, repair, "ok", "success"),
(6, 334.0, "drilling -- trip", "fail", "stuck equipment"), (7, 500.0, drill, "ok", "success"),
(40, 505.0, "interruption -- waiting on weather", "ok", "success")]
a = _activities([(rid, W, h, 1, md, code, state, detail, "x") for h, md, code, state, detail in rows])
return r, a
def test_mudline_and_own_hole_top():
r = _reports([{"day": 0, "elevKelly": 0.0, "waterDepth": 91.0, "diaHole": 26.0, "mdDiaHoleStart": 300.0},
{"day": 1, "diaHole": 17.5, "mdDiaHoleStart": 1400.0}, {"day": 2, "mdDiaHoleStart": 5.0},
{"day": 3, "wellbore": "15/9-19 A", "waterDepth": 84.0, "elevKelly": 25.0}])
assert L.mudline(r).to_dict() == {"15/9-19 A": 109.0, "15/9-F-1": 145.9} # elevKelly 0 is not used
assert L.own_hole_top(r).to_dict() == {"15/9-F-1": 300.0}
def test_t3_depth_classes_cells_and_episodes():
r, a = _t3_case()
t = L.t3_activities(a, L.t2_labels(a, CFG), r, CFG)
assert t["depth_class"].tolist() == ["in_hole"] * 4 + ["zero", "above_mudline"] + ["in_hole"] * 3
assert t["cell"].tolist() == [30, 30, 31, 40, pd.NA, pd.NA, 33, 50, 50]
stem = "15_9_F_1"
# (a): hours 1-2, hours 4-5, hour 40; the drilling row at hour 3 and the 33 h gap end an episode
assert t["episode_a"].fillna("").tolist() == ["", f"{stem}:a:E0001", f"{stem}:a:E0001", "", f"{stem}:a:E0002",
f"{stem}:a:E0002", "", "", f"{stem}:a:E0003"]
# (b): the failed trip at hour 6 continues the episode of hours 4-5
assert t["episode_b"].tolist()[4:7] == [f"{stem}:b:E0002"] * 3
ea, eb = L.t3_episodes(t, "a"), L.t3_episodes(t, "b")
assert ea["n_activities"].tolist() == [2, 2, 1] and eb["n_activities"].tolist() == [2, 3, 1]
assert ea.loc[0, ["md_min", "md_max", "n_in_hole", "hours", "causes"]].tolist() == [
305.0, 318.0, 2, 2.0, "equipment"]
assert ea.loc[1, "n_in_hole"] == 0 and pd.isna(ea.loc[1, "md_min"]) # at surface: not located
assert eb.loc[1, ["md_min", "md_max", "causes"]].tolist() == [334.0, 334.0, "equipment|stuck_fishing"]
assert ea.loc[2, "act_ids"] == [a["act_id"].iloc[8]]
def test_t3_episode_gap_is_configurable():
r, a = _t3_case()
cfg = {**CFG, "t3": {**CFG["t3"], "episode_max_gap_h": 0.0}}
a.loc[2, ["start_utc", "end_utc"]] = [_ts(0, 2.5), _ts(0, 3.5)] # half an hour after the row before
t = L.t3_activities(a, L.t2_labels(a, CFG), r, cfg)
assert t["episode_a"].tolist()[1:3] == ["15_9_F_1:a:E0001", "15_9_F_1:a:E0002"]
def test_t3_cells_and_intervals():
r, a = _t3_case()
t = L.t3_activities(a, L.t2_labels(a, CFG), r, CFG)
cells = L.t3_cells(t, r, CFG)
assert cells["cell"].tolist() == list(range(14, 61)) # mud line 145.9 m to report md 600 m
c = cells.set_index("cell")
assert c.loc[14, ["md_top", "md_bottom", "in_own_hole"]].tolist() == [140.0, 150.0, False]
assert c.loc[20, "in_own_hole"] and not c.loc[19, "in_own_hole"] # own hole starts at 200 m
assert c.loc[30, ["n_activities", "n_npt_a", "n_npt_b", "label_a", "label_b"]].tolist() == [2, 1, 1, True, True]
assert c.loc[33, ["n_npt_a", "n_npt_b", "label_a", "label_b", "causes_b"]].tolist() == [0, 1, False, True,
"stuck_fishing"]
assert c.loc[40, ["n_activities", "label_a", "label_b"]].tolist() == [1, False, False]
assert c.loc[35, ["n_activities", "hours", "label_b"]].tolist() == [0, 0.0, False]
assert c.loc[31, "act_ids_a"] == [a["act_id"].iloc[2]] and c.loc[31, "first_npt_start_a"] == _ts(0, 2)
assert cells["label_a"].sum() == 3 and cells["label_b"].sum() == 4
ia, ib = L.t3_intervals(cells, t, "a", CFG), L.t3_intervals(cells, t, "b", CFG)
# touching cells 30-31 merge; 33 (b only) and 50 stand alone with the default gap of 0
assert ia[["cell_first", "cell_last", "md_top", "md_bottom", "length_m", "n_activities"]].values.tolist() == [
[30, 31, 300.0, 320.0, 20.0, 2], [50, 50, 500.0, 510.0, 10.0, 1]]
assert ib["interval_id"].tolist() == ["15_9_F_1:b:I001", "15_9_F_1:b:I002", "15_9_F_1:b:I003"]
assert ib[["cell_first", "cell_last"]].values.tolist() == [[30, 31], [33, 33], [50, 50]]
assert ia.loc[0, ["hours", "n_episodes", "causes", "first_start_utc"]].tolist() == [2.0, 1, "equipment", _ts(0, 1)]
# one empty cell (32) may lie between two positive cells when the gap is 1
wide = L.t3_intervals(cells, t, "b", CFG, merge_gap_cells=1)
assert wide[["cell_first", "cell_last", "n_positive_cells", "length_m"]].values.tolist() == [
[30, 33, 3, 40.0], [50, 50, 1, 10.0]]
out = L.attach_intervals(cells, {"a": ia, "b": ib}).set_index("cell")
assert out.loc[[30, 31], "interval_id_a"].tolist() == ["15_9_F_1:a:I001"] * 2
assert pd.isna(out.loc[33, "interval_id_a"]) and out.loc[33, "interval_id_b"] == "15_9_F_1:b:I002"
assert out["interval_id_b"].notna().sum() == 4
def test_t3_wellbores_do_not_merge():
r = _reports([{"day": 0, "md": 400.0}, {"day": 0, "wellbore": "15/9-F-1 A", "md": 400.0}])
a = _activities([(r.report_id[0], "15/9-F-1", 0, 1, 305.0, "interruption -- repair", "ok", "success", "x"),
(r.report_id[1], "15/9-F-1 A", 1, 1, 312.0, "interruption -- repair", "ok", "success", "x")])
t = L.t3_activities(a, L.t2_labels(a, CFG), r, CFG)
assert t["episode_a"].tolist() == ["15_9_F_1:a:E0001", "15_9_F_1_A:a:E0001"]
iv = L.t3_intervals(L.t3_cells(t, r, CFG), t, "a", CFG)
assert iv[["wellbore", "cell_first", "cell_last"]].values.tolist() == [["15/9-F-1", 30, 30], ["15/9-F-1 A", 31, 31]]
assert iv["well"].tolist() == ["15/9-F-1", "15/9-F-1"]
# ---------------------------------------------------------------------------------------------------------------
# Analysis
# ---------------------------------------------------------------------------------------------------------------
def test_class_coverage_and_distribution():
f = pd.DataFrame({"wellbore": ["15/9-F-1", "15/9-F-1 A", "15/9-F-1 A", "15/9-F-4", "15/9-F-4"],
"well": ["15/9-F-1", "15/9-F-1", "15/9-F-1", "15/9-F-4", "15/9-F-4"],
"label": ["x", "x", "x", "y", None]})
cov = L.class_coverage(f, "label", rare=3).set_index("class")
assert cov.loc["x", ["n", "n_wellbores", "n_wells", "top_wellbore", "top_wellbore_share"]].tolist() == [
3, 2, 1, "15/9-F-1 A", 0.6667]
assert cov.loc["x", ["rare", "single_wellbore", "single_well"]].tolist() == [False, False, True]
assert cov.loc["y", ["n", "rare", "single_wellbore", "single_well"]].tolist() == [1, True, True, True]
assert L.distribution(f, "label", "well") == {"15/9-F-1": {"x": 3}, "15/9-F-4": {"y": 1}}
# ---------------------------------------------------------------------------------------------------------------
# The Volve tables: locked counts
# ---------------------------------------------------------------------------------------------------------------
DDR = paths.outputs_dir() / "ddr"
TABLES = ("reports", "activities", "bits", "casings")
HAVE_TABLES = all((DDR / f"{t}.parquet").is_file() for t in TABLES)
HAVE_XML = paths.ddr_xml_dir().is_dir()
needs_tables = pytest.mark.skipif(not (HAVE_TABLES or HAVE_XML), reason="missing the DDR tables and the DDR XML folder")
@pytest.fixture(scope="module")
def volve() -> dict:
if HAVE_TABLES:
src = {t: pd.read_parquet(DDR / f"{t}.parquet") for t in TABLES}
else:
from volve_dia.ddr.xml import parse_dir
src = parse_dir(paths.ddr_xml_dir())
reports, activities = src["reports"], src["activities"]
feat = L.fill_features(L.timeline(reports, activities, CFG), activities, src["bits"], src["casings"], CFG)
ops = L.operation_classes(activities, CFG)
t1r = L.t1_reports(feat, ops, activities, CFG)
t2 = L.t2_labels(activities, CFG)
t3a = L.t3_activities(activities, t2, reports, CFG)
cells = L.t3_cells(t3a, reports, CFG)
return {"reports": reports, "activities": activities, "feat": feat, "t1r": t1r, "t1a": L.t1_activities(ops, t1r),
"t2": t2, "t3a": t3a, "cells": cells,
"intervals": {d: L.t3_intervals(cells, t3a, d, CFG) for d in L.NPT_DEFINITIONS},
"episodes": {d: L.t3_episodes(t3a, d) for d in L.NPT_DEFINITIONS}}
def _script():
spec = importlib.util.spec_from_file_location("labels_07", paths.REPO_ROOT / "scripts" / "07_labels.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.data
@needs_tables
def test_labels_yaml_matches_the_data(volve):
assert L.check_code_counts(volve["activities"], CFG) == {}
published = volve["reports"]["diaHole"].value_counts().to_dict()
assert published == {float(k): v["n"] for k, v in CFG["t1"]["hole_sizes"].items()}
assert volve["reports"]["diaPilot"].notna().sum() == 19
@pytest.mark.data
@needs_tables
def test_locked_counts(volve):
script = _script()
got = script.expected_counts(volve["t1r"], volve["t1a"], volve["t2"], volve["t3a"], volve["cells"],
volve["intervals"], volve["episodes"])
assert got == script.EXPECTED
assert got["t2_npt_a"] == CFG["t2"]["npt_definitions"]["a"]["n"] == 3577
assert got["t2_npt_b"] == CFG["t2"]["npt_definitions"]["b"]["n"] == 4286
@pytest.mark.data
@needs_tables
def test_volve_reports_and_fill(volve):
t1r, feat = volve["t1r"], volve["feat"]
assert len(t1r) == 1759 and t1r["report_id"].is_unique
assert t1r.loc[t1r["status"].eq("placeholder_date"), "report_id"].tolist() == ["15_9_19_A_1980_01_01"]
assert t1r["status"].eq("no_activities").sum() == 8
live = t1r[t1r["status"].ne("placeholder_date")]
assert live["section"].notna().all() and live["phase"].notna().all() # every real report has a section
published = live[live["filled_by"].eq("diaHole")]
assert len(published) == 769 and (published["section_in"] == published["diaHole"]).all()
filled = live[live["diaHole"].isna()]
assert len(filled) == 989 and (filled["scope"] == "drilling_day").sum() == 260
assert filled["fill_source_report_id"].notna().all() and (filled["fill_gap_reports"] >= 1).all()
source = filled.merge(t1r[["report_id", "wellbore", "diaHole"]], left_on="fill_source_report_id",
right_on="report_id", suffixes=("", "_source"))
assert (source["wellbore"] == source["wellbore_source"]).all() # never across wellbores
assert (source["section_in"] == source["diaHole_source"]).all()
ev = L.evaluate_fill_rules(feat, rules=("ffill", "bfill"), schemes=("tail_half", "head_half"))
ev = L.summarise_fill_eval(ev).set_index(["rule", "scheme"])
assert ev.loc[("ffill", "tail_half"), ["n_masked", "n_correct"]].tolist() == [364, 364]
assert ev.loc[("bfill", "head_half"), ["n_masked", "n_correct"]].tolist() == [364, 364]
assert ev.loc[("ffill", "head_half"), "n_correct"] == 5 and ev.loc[("bfill", "tail_half"), "n_correct"] == 29
@pytest.mark.data
@needs_tables
def test_volve_t2_and_t3(volve):
t2, t3a, cells, activities = volve["t2"], volve["t3a"], volve["cells"], volve["activities"]
assert len(t2) == 23447 and t2["act_id"].tolist() == activities["act_id"].tolist()
assert (t2["npt_a"] <= t2["npt_b"]).all() and (t2["cause_group"].ne("none") == t2["npt_b"]).all()
assert t2["cause_conflict"].sum() == 192 and t2["wait_code_outside_interruption"].sum() == 79
view = L.t2_inputs(activities, volve["reports"], CFG)
assert len(view) == 23447 and not set(view.columns) & set(L.MASKED)
assert t2["well"].nunique() == 11 and t2["wellbore"].nunique() == 26
assert set(t3a["act_id"]) == set(activities["act_id"]) and t3a["md"].notna().all()
assert not cells.duplicated(["wellbore", "cell"]).any()
for d in L.NPT_DEFINITIONS:
located = t3a[t3a[f"npt_{d}"] & t3a["depth_class"].eq("in_hole")]
iv = volve["intervals"][d]
assert cells[f"n_npt_{d}"].sum() == len(located) == iv["n_activities"].sum()
assert iv["n_positive_cells"].sum() == cells[f"label_{d}"].sum()
assert sorted(a for ids in iv["act_ids"] for a in ids) == sorted(located["act_id"])
assert (iv["length_m"] >= iv["n_positive_cells"] * CFG["t3"]["grid_m"]).all()
assert volve["episodes"][d]["n_activities"].sum() == t3a[f"npt_{d}"].sum()

75
tests/test_ocr_hub.py Normal file
View File

@@ -0,0 +1,75 @@
import numpy as np
from volve_dia import ocr, ocr_hub
def test_page_content_parses_like_a_service_answer():
cats = {1: "Section Header", 3: "Table", 7: "Image"}
anns = [
{"id": 1, "category_id": 1, "bbox": [165.3, 233.9, 330.6, 23.39], "text": "<p><b>Operations</b></p>"},
{"id": 2, "category_id": 3, "bbox": [0, 0, 1653, 2339],
"text": "<table><tr><td>Start</td><td>End</td></tr><tr><td>00:00</td><td>06:00</td></tr></table>"},
{"id": 3, "category_id": 7, "bbox": [10, 10, 5, 5], "text": ""},
]
blocks = ocr.html_blocks(ocr_hub.page_content(anns, cats, 1653, 2339), 2)
assert [(b.raw_label, b.label) for b in blocks] == [("Section Header", "section_header"), ("Table", "table")]
assert blocks[0].bbox == [100.0, 100.0, 300.0, 110.0]
assert blocks[1].bbox == [0.0, 0.0, 1000.0, 1000.0]
assert blocks[1].text == "Start | End\n00:00 | 06:00"
assert all(b.page == 2 for b in blocks)
def test_tokens_keep_dates_depths_and_names_whole():
assert ocr_hub.tokens("<p>Period: 2009-01-16 00:00</p> Wellbore: 15/9-F-15 B, 3.5 m") == [
"period", "2009-01-16", "00:00", "wellbore", "15/9-f-15", "b", "3.5", "m"]
def test_text_candidates_rank_the_right_page_first():
pages = [ocr_hub.tokens(t) for t in ("period 2009-01-16 drill 8.5 hole to 3000 m",
"period 2009-01-17 drill 8.5 hole to 3100 m",
"")]
images = [ocr_hub.tokens(t) for t in ("period 2009-01-17 drill 8.5 hole to 3100 m",
"", "period 2009-01-16 drill 8.5 hole to 3000 m")]
cands = ocr_hub.text_candidates(pages, images, prefilter=3, top_k=2)
assert cands[0][0] == (2, 1.0)
assert cands[1][0] == (0, 1.0)
assert cands[2] == [(1, 1.0)] # a page with no text layer: the images with no text
def test_correlation():
rng = np.random.default_rng(0)
a = rng.integers(0, 255, (40, 30), dtype=np.uint8)
assert ocr_hub.correlation(a, a) == 1.0
assert ocr_hub.correlation(a, np.pad(a, ((0, 1), (0, 1)))) == 1.0 # one pixel larger: common area
assert abs(ocr_hub.correlation(a, rng.integers(0, 255, (40, 30), dtype=np.uint8))) < 0.1
blank = np.full((40, 30), 255, np.uint8)
assert ocr_hub.correlation(blank, blank) == 1.0
def test_select_breaks_image_ties_by_text():
# Two reports that differ only in a date: equal correlation, the text decides.
assert ocr_hub.select([(0.978, 0.93, 1), (0.978, 0.99, 2), (0.95, 1.0, 3)], 0.9, 0.01) == (0.978, 0.99, 2)
# Outside the tie window the image decides, whatever the text says.
assert ocr_hub.select([(0.99, 0.80, 1), (0.95, 1.0, 2)], 0.9, 0.01) == (0.99, 0.80, 1)
assert ocr_hub.select([(0.85, 1.0, 1)], 0.9, 0.01) is None
assert ocr_hub.select([], 0.9, 0.01) is None
def test_select_text_floor_rejects_same_layout_other_report():
# A first page of another day: same layout (corr 0.92) but other text (F1 0.36); with a floor it is no match.
assert ocr_hub.select([(0.921, 0.364, 1)], 0.9, 0.01) == (0.921, 0.364, 1)
assert ocr_hub.select([(0.921, 0.364, 1)], 0.9, 0.01, 0.7) is None
assert ocr_hub.select([(0.95, 0.5, 1), (0.93, 0.95, 2)], 0.9, 0.01, 0.7) == (0.93, 0.95, 2)
def test_coarse_dot_is_a_correlation():
rng = np.random.default_rng(1)
a = rng.integers(0, 255, (585, 413), dtype=np.uint8)
assert abs(float(ocr_hub.coarse(a) @ ocr_hub.coarse(a)) - 1) < 1e-5
assert ocr_hub.coarse(a).shape == (ocr_hub.COARSE[0] * ocr_hub.COARSE[1],)
assert float(ocr_hub.coarse(np.full((585, 413), 255, np.uint8)) @ ocr_hub.coarse(a)) == 0.0
def test_iso_dates():
assert ocr_hub.iso_dates("Period: 1997-09-04 00:00 - 1997-09-05 00:00, created 2018-05-03; 12345-01-01") == {
"1997-09-04", "1997-09-05", "2018-05-03"}

437
tests/test_t4.py Normal file
View File

@@ -0,0 +1,437 @@
"""volve_dia.t4: template instantiation, drop rules, sampling, the scorer; and, with the data, the locked counts and
the agreement of the SQL answers with the pandas implementation."""
import copy
import importlib.util
import json
import duckdb
import pytest
from volve_dia import paths, t4
from volve_dia.names import well_of
CONFIG = paths.REPO_ROOT / "configs" / "t4_templates.yaml"
DDR = paths.REPO_ROOT / "outputs" / "ddr"
needs_db = pytest.mark.skipif(not (DDR / "volve_ddr.duckdb").is_file(), reason="missing outputs/ddr/volve_ddr.duckdb")
# ----------------------------------------------------------------------------------------------------------------------
# A small database and four templates: a header value with a missing case, a list, a tie, a sampled sum.
# ----------------------------------------------------------------------------------------------------------------------
MINI = {
"seed": 7,
"templates": [
{
"id": "T1_deepest", "family": "lookup", "tadi": {"category": 1},
"questions": ["Deepest depth of {wellbore}?", "How deep is {wellbore}?"],
"slots": {"wellbore": {"type": "wellbore"}},
"slots_sql": "SELECT DISTINCT wellbore FROM reports ORDER BY 1",
"answer_sql": "SELECT max(md) AS answer FROM reports WHERE wellbore = $wellbore",
"evidence_sql": "SELECT 'reports' AS \"table\", report_id, NULL AS seq FROM reports WHERE wellbore = "
"$wellbore AND md = (SELECT max(md) FROM reports WHERE wellbore = $wellbore)",
"evidence_mode": "any", "on_null": "not_reported",
"answer": {"type": "number", "unit": "m", "round": 1, "tolerance": {"abs": 1.0}},
"source": ["reports.md"],
},
{
"id": "T2_holes", "family": "lookup", "tadi": {"category": 1},
"questions": ["Hole sizes of {wellbore}?"],
"slots": {"wellbore": {"type": "wellbore"}},
"slots_sql": "SELECT DISTINCT wellbore FROM reports WHERE diaHole IS NOT NULL ORDER BY 1",
"answer_sql": "SELECT DISTINCT diaHole AS answer FROM reports WHERE wellbore = $wellbore "
"AND diaHole IS NOT NULL ORDER BY 1 DESC",
"evidence_sql": "SELECT 'reports' AS \"table\", report_id, NULL AS seq, diaHole AS grp FROM reports "
"WHERE wellbore = $wellbore AND diaHole IS NOT NULL",
"evidence_mode": "group",
"answer": {"type": "list", "item_type": "number", "unit": "in", "tolerance": {"abs": 0.01}},
"source": ["reports.diaHole"],
},
{
"id": "T3_top_code", "family": "aggregation", "tadi": {"category": 2},
"questions": ["Which code has the most hours in {wellbore}?"],
"slots": {"wellbore": {"type": "wellbore"}},
"slots_sql": "SELECT DISTINCT wellbore FROM activities ORDER BY 1",
"answer_sql": "WITH h AS (SELECT code, sum(duration_h) AS h FROM activities WHERE wellbore = $wellbore "
"GROUP BY 1) SELECT min(code) AS answer, CASE WHEN count(*) > 1 THEN 'tie' END AS "
"drop_reason FROM h WHERE h = (SELECT max(h) FROM h)",
"evidence_sql": "SELECT 'activities' AS \"table\", report_id, seq FROM activities WHERE wellbore = "
"$wellbore AND code = (SELECT code FROM activities WHERE wellbore = $wellbore GROUP BY 1 "
"ORDER BY sum(duration_h) DESC LIMIT 1)",
"evidence_mode": "all",
"answer": {"type": "enumeration", "choices": {"sql": "SELECT DISTINCT code FROM activities ORDER BY 1"}},
"source": ["activities.code"],
},
{
"id": "T4_hours", "family": "aggregation", "tadi": {"category": 2},
"questions": ["Hours of '{code}' in {wellbore}?"],
"slots": {"wellbore": {"type": "wellbore"}, "code": {"type": "string"}},
"slots_sql": "SELECT DISTINCT wellbore, code FROM activities ORDER BY 1, 2",
"answer_sql": "SELECT sum(duration_h) AS answer FROM activities WHERE wellbore = $wellbore "
"AND code = $code",
"evidence_sql": "SELECT 'activities' AS \"table\", report_id, seq FROM activities WHERE wellbore = "
"$wellbore AND code = $code",
"evidence_mode": "all", "sample": {"by": ["wellbore"], "n": 1},
"answer": {"type": "number", "unit": "h", "round": 2, "tolerance": {"abs": 0.25}},
"source": ["activities.duration_h"],
},
],
}
@pytest.fixture()
def con():
c = duckdb.connect(":memory:")
c.execute("CREATE TABLE reports (report_id VARCHAR, wellbore VARCHAR, md DOUBLE, diaHole DOUBLE)")
c.execute("""INSERT INTO reports VALUES
('15_9_F_1_2013_08_01', '15/9-F-1', 1000.0, 17.5), ('15_9_F_1_2013_08_02', '15/9-F-1', 2500.5, 12.25),
('15_9_F_1_2013_08_03', '15/9-F-1', 2500.5, 12.25), ('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 3000.0, NULL),
('15_9_F_4_2008_02_19', '15/9-F-4', NULL, NULL)""")
c.execute("CREATE TABLE activities (report_id VARCHAR, wellbore VARCHAR, seq BIGINT, code VARCHAR, "
"duration_h DOUBLE)")
c.execute("""INSERT INTO activities VALUES
('15_9_F_1_2013_08_01', '15/9-F-1', 0, 'drilling -- drill', 10.0),
('15_9_F_1_2013_08_01', '15/9-F-1', 1, 'interruption -- repair', 2.5),
('15_9_F_1_2013_08_02', '15/9-F-1', 0, 'drilling -- drill', 4.0),
('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 0, 'drilling -- drill', 6.0),
('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 1, 'drilling -- trip', 6.0)""")
yield c
c.close()
@pytest.fixture()
def mini():
cfg = copy.deepcopy(MINI)
for t in cfg["templates"]:
t4.validate_template(t)
return cfg
def by_template(questions):
out = {}
for q in questions:
out.setdefault(q["template_id"], []).append(q)
return out
def test_instantiation(con, mini):
questions, outcomes, summary = t4.build(con, mini)
q = by_template(questions)
deepest = {x["wellbore"]: x for x in q["T1_deepest"]}
assert deepest["15/9-F-1"]["answer"] == 2500.5 and deepest["15/9-F-1"]["answer_text"] == "2500.5 m"
assert deepest["15/9-F-1"]["question"] in ("Deepest depth of 15/9-F-1?", "How deep is 15/9-F-1?")
assert (deepest["15/9-F-1"]["unit"], deepest["15/9-F-1"]["tolerance_abs"]) == ("m", 1.0)
assert deepest["15/9-F-1 A"]["well"] == "15/9-F-1" and deepest["15/9-F-1 A"]["wells"] == ["15/9-F-1"]
# evidence mode any: the two reports that state the deepest depth are one group
assert [(e["report_id"], e["seq"], e["group"]) for e in deepest["15/9-F-1"]["evidence"]] == [
("15_9_F_1_2013_08_02", None, 0), ("15_9_F_1_2013_08_03", None, 0)]
# the stored SQL is the executed SQL, literals written in
assert deepest["15/9-F-1 A"]["sql"] == "SELECT max(md) AS answer FROM reports WHERE wellbore = '15/9-F-1 A'"
assert con.execute(deepest["15/9-F-1 A"]["sql"]).fetchone()[0] == 3000.0
# no depth in any report of 15/9-F-4: an unanswerable question, without evidence
assert deepest["15/9-F-4"]["answer"] == t4.NOT_REPORTED and not deepest["15/9-F-4"]["answerable"]
assert deepest["15/9-F-4"]["evidence"] == []
# a list answer with one evidence group per element
holes = q["T2_holes"][0]
assert holes["answer"] == [17.5, 12.25] and holes["answer_text"] == "17.5, 12.25 in"
assert holes["n_evidence"] == 3 and holes["n_evidence_groups"] == 2
assert summary["questions"] == len(questions) and summary["unanswerable"] == 1
assert len({x["id"] for x in questions}) == len(questions)
def test_drops_and_sampling(con, mini):
questions, outcomes, summary = t4.build(con, mini)
q = by_template(questions)
# 15/9-F-1 A: two codes with 6 h each, a tie, dropped and counted
assert [x["wellbore"] for x in q["T3_top_code"]] == ["15/9-F-1"]
assert q["T3_top_code"][0]["answer"] == "drilling -- drill"
assert q["T3_top_code"][0]["choices"] == ["drilling -- drill", "drilling -- trip", "interruption -- repair"]
assert summary["per_template"]["T3_top_code"]["dropped"] == {"tie": 1}
assert summary["dropped"] == {"tie": 1} and summary["dropped_total"] == 1
# four (wellbore, code) candidates, one kept per wellbore, the same ones on every run
hours = summary["per_template"]["T4_hours"]
assert (hours["candidates"], hours["questions"], hours["not_sampled"]["answerable"]) == (4, 2, 2)
again, _, _ = t4.build(con, mini)
assert [x["id"] for x in again] == [x["id"] for x in questions]
# every answerable question has evidence rows; the sums are over all rows of the code
assert all(x["evidence"] for x in questions if x["answerable"])
for x in q["T4_hours"]:
rows = con.execute(x["evidence_sql"]).fetchall()
assert len(rows) == x["n_evidence"] == x["n_evidence_groups"]
def test_null_answer_is_dropped_without_on_null(con, mini):
del mini["templates"][0]["on_null"]
_, outcomes, summary = t4.build(con, mini)
assert summary["per_template"]["T1_deepest"]["dropped"] == {"null_answer": 1}
assert [o.status for o in outcomes["T1_deepest"]] == ["ok", "ok", "drop"]
def test_rendering():
assert t4.format_inch(12.25) == '12 1/4" (12.25 in)' and t4.format_inch(36.0) == '36"'
assert t4.format_inch(13.375) == '13 3/8" (13.375 in)' and t4.format_inch(9.875) == '9 7/8" (9.875 in)'
assert t4.format_number(3520.0) == "3520" and t4.format_number(1.48) == "1.48"
sql = t4.render_sql("SELECT 1 WHERE w = $w AND d = $d AND x = $x", {"w": "15/9-F-1 A", "d": 12.25, "x": "o'k"})
assert sql == "SELECT 1 WHERE w = '15/9-F-1 A' AND d = 12.25 AND x = 'o''k'"
assert t4.evidence_id("activities", "15_9_F_4_2008_02_19", 10) == "activities:15_9_F_4_2008_02_19:10"
assert t4.evidence_id("reports", "15_9_F_4_2008_02_19") == "reports:15_9_F_4_2008_02_19"
def test_validate_template(mini):
t = copy.deepcopy(mini["templates"][0])
t["questions"] = ["Depth of {well}?"]
with pytest.raises(t4.TemplateError, match="undeclared slots"):
t4.validate_template(t)
t = copy.deepcopy(mini["templates"][0])
t["answer"] = {"type": "number", "unit": "m"}
with pytest.raises(t4.TemplateError, match="tolerance"):
t4.validate_template(t)
t = copy.deepcopy(mini["templates"][0])
t["answer_sql"] = "SELECT max(md) AS answer FROM reports WHERE wellbore = $name"
with pytest.raises(t4.TemplateError, match="undeclared parameters"):
t4.validate_template(t)
t = copy.deepcopy(mini["templates"][3])
t["negatives"] = {"n": 2}
with pytest.raises(t4.TemplateError, match="on_null"):
t4.validate_template(t)
# ----------------------------------------------------------------------------------------------------------------------
# Scorer
# ----------------------------------------------------------------------------------------------------------------------
def gold(answer, kind, evidence=(), **kw):
q = {"answer": answer, "answer_type": kind, "answerable": True, "evidence": list(evidence), "unit": None,
"tolerance_abs": None, "tolerance_rel": None, "tolerance_days": 0, "item_type": None}
q.update(kw)
return q
def test_tolerance():
assert t4.within_tolerance(3520.9, 3520.0, abs_tol=1.0) and not t4.within_tolerance(3521.1, 3520.0, abs_tol=1.0)
assert t4.within_tolerance(13.7, 13.45, rel_tol=0.02) and not t4.within_tolerance(13.8, 13.45, rel_tol=0.02)
assert t4.within_tolerance(11, 11, abs_tol=0) and not t4.within_tolerance(12, 11, abs_tol=0)
assert t4.within_tolerance(1.0, 0.5, abs_tol=0.5, rel_tol=0.01) # the larger of the two limits applies
def test_score_number():
q = gold(3520.0, "number", unit="m", tolerance_abs=1.0)
assert t4.score(3520.4, q)["correct"] and t4.score("3,520 m", q)["correct"] and t4.score("3520,4", q)["correct"]
assert not t4.score(3522, q)["correct"] and not t4.score("deep", q)["correct"]
assert t4.score({"answer": 11548.6, "unit": "ft"}, q)["correct"] # 3520.0 m
assert t4.score("11548.6 ft", q)["correct"] and t4.score("3520 metres", q)["correct"]
assert not t4.score({"answer": 3520, "unit": "ft"}, q)["correct"] and not t4.score("3520 ft", q)["correct"]
assert not t4.score({"answer": 3520, "unit": "h"}, q)["correct"] # another dimension
rop = gold(13.45, "number", unit="m/h", tolerance_rel=0.02)
assert t4.score("13.6 m/h", rop)["correct"] and not t4.score(14.0, rop)["correct"]
count = gold(11.0, "number", unit="reports", tolerance_abs=0)
assert t4.score({"answer": 11, "unit": "days"}, count)["correct"] and not t4.score(12, count)["correct"]
size = gold(12.25, "number", unit="in", tolerance_abs=0.01)
assert t4.score('12 1/4"', size)["correct"] and t4.score("12.25 in", size)["correct"]
def test_score_date_string_boolean():
d = gold("1997-11-27", "date")
assert t4.score("1997-11-27", d)["correct"] and t4.score("27.11.1997", d)["correct"]
assert t4.score("27 November 1997", d)["correct"] and t4.score("1997-11-27T14:00:00+01:00", d)["correct"]
assert not t4.score("1997-11-28", d)["correct"] and not t4.score("November", d)["correct"]
assert t4.score("1997-11-28", gold("1997-11-27", "date", tolerance_days=1))["correct"]
rig = gold("MÆRSK INSPIRER", "string")
assert t4.score("Mærsk Inspirer.", rig)["correct"] and not t4.score("Byford Dolphin", rig)["correct"]
wb = gold("15/9-F-1 B", "enumeration", choices=["15/9-F-1", "15/9-F-1 B"])
assert t4.score("NO 15/9-F-1 B", wb)["correct"] and t4.score("15_9_F_1_B", wb)["correct"]
assert not t4.score("15/9-F-1", wb)["correct"]
code = gold("interruption -- fish", "enumeration")
assert t4.score("Interruption - fish", code)["correct"] and not t4.score("interruption -- repair", code)["correct"]
yes, no = gold(True, "boolean"), gold(False, "boolean")
assert t4.score("Yes, on 2008-11-14.", yes)["correct"] and t4.score(True, yes)["correct"]
assert not t4.score("no", yes)["correct"] and not t4.score("maybe", yes)["correct"]
s = t4.score("No such activity is recorded.", no) # a 'no', not an abstention
assert s["correct"] and not s["abstained"]
assert t4.score("n/a", no)["abstained"] and not t4.score("n/a", no)["correct"]
def test_score_list():
q = gold([36.0, 26.0, 17.5], "list", item_type="number", unit="in", tolerance_abs=0.01)
s = t4.score([17.5, 36, 26], q)
assert s["correct"] and s["list_precision"] == s["list_recall"] == 1.0
assert t4.score('36", 26", 17 1/2"', q)["correct"]
s = t4.score([36, 26], q)
assert not s["correct"] and s["list_precision"] == 1.0 and s["list_recall"] == pytest.approx(2 / 3)
s = t4.score([36, 26, 17.5, 12.25], q)
assert not s["correct"] and s["list_precision"] == 0.75 and s["list_recall"] == 1.0
assert not t4.score([36, 36, 26], q)["correct"] # a gold element is matched once
def test_score_unanswerable():
q = gold(t4.NOT_REPORTED, "date", answerable=False)
for pred in (None, "", "Not reported", "N/A", "no such activity in the reports", "unknown"):
s = t4.score(pred, q)
assert s["correct"] and s["abstained"] and not s["fabricated"]
s = t4.score("1997-11-27", q)
assert not s["correct"] and s["fabricated"] and not s["abstained"]
answerable = gold(3520.0, "number", unit="m", tolerance_abs=1.0)
s = t4.score("not reported", answerable)
assert not s["correct"] and s["abstained"] and not s["fabricated"]
def test_score_citations():
def rows(*specs):
return [{"table": t, "report_id": r, "seq": s, "group": g} for t, r, s, g in specs]
rid = "15_9_F_4_2008_02_19"
need_all = rows(("activities", rid, 10, 0), ("activities", rid, 11, 1), ("reports", rid, None, 2))
s = t4.score_citations([f"activities:{rid}:10", f"{rid}:011", {"table": "reports", "report_id": rid}], need_all)
assert s == {"n_cited": 3, "citation_precision": 1.0, "citation_recall": 1.0}
s = t4.score_citations([f"activities:{rid}:10", f"activities:{rid}:99"], need_all)
assert s["citation_precision"] == 0.5 and s["citation_recall"] == pytest.approx(1 / 3)
any_one = rows(("reports", rid, None, 0), ("reports", "15_9_F_4_2008_02_20", None, 0))
assert t4.score_citations([f"reports:{rid}"], any_one)["citation_recall"] == 1.0
assert t4.score_citations([rid], any_one)["citation_precision"] == 1.0 # a bare report id
grouped = rows(("casings", rid, 0, 0), ("casings", rid, 1, 0), ("casings", rid, 2, 1))
assert t4.score_citations([f"casings:{rid}:1"], grouped)["citation_recall"] == 0.5
none = t4.score_citations([], need_all)
assert none == {"n_cited": 0, "citation_precision": None, "citation_recall": 0.0}
assert t4.score_citations([f"reports:{rid}"], [])["citation_precision"] == 0.0
assert t4.score_citations([f"reports:{rid}"], [])["citation_recall"] is None
assert t4.score_citations(["not a citation"], need_all)["citation_precision"] == 0.0
# report level: any row of the report counts
s = t4.score_citations([f"fluids:{rid}:0"], need_all, level="report")
assert s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0
q = gold(3245.0, "number", evidence=need_all[:1], unit="m", tolerance_abs=1.0)
s = t4.score({"answer": "3245 m", "citations": [f"{rid}:010"]}, q)
assert s["correct"] and s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0
# ----------------------------------------------------------------------------------------------------------------------
# The configuration, and the build on the DDR tables
# ----------------------------------------------------------------------------------------------------------------------
def test_config_is_valid():
from volve_dia import t4_pandas
cfg = t4.load_config(CONFIG)
ids = [t["id"] for t in cfg["templates"]]
assert len(ids) == len(set(ids)) == 39
assert {t["family"] for t in cfg["templates"]} == set(t4.FAMILIES)
assert {t["answer"]["type"] for t in cfg["templates"]} == set(t4.ANSWER_TYPES)
assert set(ids) == set(t4_pandas.TEMPLATES) # every template has its pandas twin
assert [t["id"] for t in cfg["disabled"]] == [
"W01_rop_section_witsml", "W02_max_inclination_trajectory", "W03_formation_at_first_event_picks",
"W04_best_bha_run", "W05_parameters_in_formation"]
for t in cfg["templates"]:
assert t["tadi"].get("fit") in ("direct", "partial", "none") and t.get("caveats")
assert t["tadi"].get("category") in (None, 1, 2, 3, 4, 5, 6)
@pytest.fixture(scope="module")
def built():
from volve_dia import t4_pandas
cfg = t4.load_config(CONFIG)
with t4.connect(DDR / "volve_ddr.duckdb") as con:
questions, outcomes, summary = t4.build(con, cfg)
return cfg, questions, outcomes, summary, t4_pandas.Tables(DDR)
def script():
spec = importlib.util.spec_from_file_location("t4_questions", paths.REPO_ROOT / "scripts" / "08_t4_questions.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.data
@needs_db
def test_locked_counts(built):
_, questions, _, summary, _ = built
expected = script().EXPECTED
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()}
assert got == expected
assert len(questions) == 1662 and len({q["id"] for q in questions}) == 1662
assert len({q["question"] for q in questions}) == 1662
@pytest.mark.data
@needs_db
def test_questions_are_well_formed(built):
_, questions, _, _, _ = built
for q in questions:
if q["scope"] != "field":
assert q["well"] == well_of(q["wellbore"]) and q["wellbore"] in q["wellbores"]
assert q["wells"] == sorted({well_of(w) for w in q["wellbores"]})
assert "{" not in q["question"] and "$" not in q["sql"] and "$" not in q["evidence_sql"]
if not q["answerable"]:
assert q["answer"] == t4.NOT_REPORTED and not q["evidence"]
elif not (q["answer_type"] == "boolean" and q["answer"] is False):
assert q["evidence"], q["id"]
if q["answer_type"] == "enumeration" and q["answerable"]:
assert q["answer"] in q["choices"]
assert sum(q["scope"] == "pair" for q in questions) == 92
assert all(len(q["wells"]) == 1 for q in questions if q["scope"] == "pair") # same-well pairs only
assert all(len(q["wells"]) == 11 and len(q["wellbores"]) == 26 for q in questions if q["scope"] == "field")
assert sum(not q["printed_in_render"] for q in questions) == 215
@pytest.mark.data
@needs_db
def test_stored_sql_reproduces_answers(built):
cfg, questions, _, _, _ = built
specs = {t["id"]: t for t in cfg["templates"]}
with t4.connect(DDR / "volve_ddr.duckdb") as con:
for q in questions[::7]:
o = t4.run_instance(con, specs[q["template_id"]], q["slots"])
assert o.sql == q["sql"] and o.answer == q["answer"] and o.evidence == q["evidence"]
@pytest.mark.data
@needs_db
def test_sql_agrees_with_pandas(built):
from volve_dia import t4_pandas
cfg, _, outcomes, _, tables = built
check = t4_pandas.crosscheck(cfg, outcomes, tables)
assert check["total"]["instances"] == 3915 and check["total"]["agree"] == 3915
assert check["total"]["slot_differences"] == 0 and check["total"]["templates_in_full_agreement"] == 39
@pytest.mark.data
@needs_db
def test_crosscheck_detects_a_wrong_template(built):
"""The comparison is not vacuous: a template whose SQL takes the shallowest depth, or whose evidence SQL misses
rows, disagrees with the pandas implementation."""
from volve_dia import t4_pandas
cfg, _, _, _, tables = built
wrong = copy.deepcopy(next(t for t in cfg["templates"] if t["id"] == "L03_deepest_md"))
wrong["answer_sql"] = wrong["answer_sql"].replace("max(md)", "min(md)")
loose = copy.deepcopy(next(t for t in cfg["templates"] if t["id"] == "A06_hours_per_code"))
loose["evidence_sql"] += " AND seq > 0"
with t4.connect(DDR / "volve_ddr.duckdb") as con:
outcomes = {t["id"]: t4.run_template(con, t) for t in (wrong, loose)}
check = t4_pandas.crosscheck({"templates": [wrong, loose]}, outcomes, tables)
assert check["per_template"]["L03_deepest_md"]["answer"] > 0
assert check["per_template"]["A06_hours_per_code"]["evidence"] > 0
assert check["per_template"]["A06_hours_per_code"]["answer"] == 0
@pytest.mark.data
@needs_db
def test_gold_answers_score_as_correct(built):
_, questions, _, _, _ = built
result = script().self_score(questions)
assert result == {"questions": 1662, "correct": 1662, "wrong": []}
@pytest.mark.data
@needs_db
def test_outputs_match_the_build(built):
_, questions, _, summary, _ = built
out = paths.REPO_ROOT / "outputs" / "t4"
if not (out / "questions.jsonl").is_file():
pytest.skip("outputs/t4 not built: run scripts/08_t4_questions.py")
stored = t4.read_jsonl(out / "questions.jsonl")
assert stored == json.loads(json.dumps(questions))
assert json.loads((out / "summary.json").read_text(encoding="utf-8"))["questions"] == summary["questions"]

457
tests/test_witsml.py Normal file
View File

@@ -0,0 +1,457 @@
"""volve_dia.witsml and volve_dia.tops: synthetic WITSML snippets (null values, sentinels, time and depth index,
duplicates), then the Volve files and the tables of scripts/06_parse_witsml.py (skipped without them)."""
import importlib.util
import io
import json
import xml.etree.ElementTree as ET
import numpy as np
import pandas as pd
import pyarrow.parquet as pq
import pytest
from volve_dia import paths, tops, witsml
from volve_dia.witsml import Curve, Flat, LongWriter, ParsedLog, dedup_curve, merge_curve, read_log_file
NSURI = "http://www.witsml.org/schemas/1series"
def log_xml(index_type: str, index_curve: str, curves: list[tuple], rows: list[str], units: str | None = None,
null_value: str | None = None, uid: str = "L1", name_wellbore: str = "NO 15/9-F-11 T2") -> io.BytesIO:
"""A `<logs>` document. `curves`: (mnemonic, unit, typeLogData, nullValue or None)."""
info = "".join(
f'<logCurveInfo uid="{m}"><mnemonic>{m}</mnemonic><unit>{u}</unit>'
+ (f"<nullValue>{nv}</nullValue>" if nv is not None else "") + f"<typeLogData>{t}</typeLogData></logCurveInfo>"
for m, u, t, nv in curves)
names = ",".join([index_curve] + [c[0] for c in curves if c[0] != index_curve])
units = units if units is not None else ",".join(["m" if index_type == "measured depth" else ""]
+ [c[1] for c in curves if c[0] != index_curve])
data = "".join(f"<data>{r}</data>" for r in rows)
return io.BytesIO((
f'<?xml version="1.0" encoding="UTF-8"?><logs xmlns="{NSURI}" version="1.4.1.1">'
f'<log uidWell="W1" uidWellbore="B1" uid="{uid}"><nameWell>NO 15/9-F-11</nameWell>'
f"<nameWellbore>{name_wellbore}</nameWellbore><name>GenTime</name><indexType>{index_type}</indexType>"
f"<direction>increasing</direction><indexCurve>{index_curve}</indexCurve>"
+ (f"<nullValue>{null_value}</nullValue>" if null_value is not None else "") + info
+ f"<logData><mnemonicList>{names}</mnemonicList><unitList>{units}</unitList>{data}</logData>"
"<commonData><sourceName>X</sourceName><priv_userOwner>someone</priv_userOwner></commonData></log></logs>"
).encode())
TIME_CURVES = [("Time", "", "date time", None), ("HKLD", "N", "double", "-999.25"), ("RPM", "c/s", "double", None),
("PASS", "unitless", "string", None), ("ARR", "unitless", "double", None)]
def time_log(rows: list[str], **kw) -> io.BytesIO:
return log_xml("date time", "Time", TIME_CURVES, rows, **kw)
def parsed(*chunks: io.BytesIO) -> ParsedLog:
log = ParsedLog()
for i, c in enumerate(chunks, 1):
log.add(read_log_file(c), i)
return log
def by_name(log: ParsedLog, log_id: int = 0) -> dict[str, Curve]:
return {c.mnemonic: c for c in log.curves(log_id)}
# ---------------------------------------------------------------------------------------------------------------
# logs
# ---------------------------------------------------------------------------------------------------------------
def test_read_log_file_header_and_curves():
lf = read_log_file(time_log(["2013-04-08T01:45:28.000Z,1,2,Drilling,"], null_value="-999.25"))
assert lf.header["uid"] == "L1" and lf.header["uidWellbore"] == "B1" and lf.header["indexType"] == "date time"
assert lf.header["nullValue"] == "-999.25" and lf.header["commonData_sourceName"] == "X"
assert "commonData_priv_userOwner" not in lf.header # people of the operator are not copied
assert lf.mnemonics == ["Time", "HKLD", "RPM", "PASS", "ARR"] and lf.units[1:3] == ["N", "c/s"]
assert [c["mnemonic"] for c in lf.curves] == lf.mnemonics and lf.curves[1]["nullValue"] == "-999.25"
assert lf.rows == ["2013-04-08T01:45:28.000Z,1,2,Drilling,"]
head = read_log_file(time_log(["2013-04-08T01:45:28.000Z,1,2,Drilling,"]), header_only=True)
assert head.header["nameWellbore"] == "NO 15/9-F-11 T2" and not head.rows and not head.curves
def test_time_log_nulls_sentinels_text():
log = parsed(time_log([
"2013-04-08T01:45:28.000Z,100.5,-9999,Drilling,1 2 3", # RPM: TADI sentinel; ARR: an array, not a number
"2013-04-08T01:45:31.000Z,-999.25,2.5,,", # HKLD: its nullValue; PASS and ARR: empty
"2013-04-08T01:45:34.500Z,,-999.25,TripIn,7", # HKLD: empty; RPM: the log-level null value
"2013-04-08T01:45:37.000Z,9999,-999,Drilling,8", # suspect values are kept
], null_value="-999.25"))
assert log.kind == "time" and log.counts["rows"] == 4 and log.counts["bad_rows"] == 0
c = by_name(log)
t0 = pd.Timestamp("2013-04-08T01:45:28Z").value // 10**6
assert c["HKLD"].index.tolist() == [t0, t0 + 9000] and c["HKLD"].value.tolist() == [100.5, 9999.0]
assert c["HKLD"].stats["n_null_value"] == 1 and c["HKLD"].stats["suspect:9999"] == 1
assert c["RPM"].value.tolist() == [2.5, -999.0]
assert c["RPM"].stats["sentinel:-9999"] == 1 and c["RPM"].stats["n_null_value"] == 1
assert c["RPM"].stats["suspect:-999"] == 1
assert c["PASS"].text.tolist() == ["Drilling", "TripIn", "Drilling"] and np.isnan(c["PASS"].value).all()
assert c["PASS"].index.tolist() == [t0, t0 + 6500, t0 + 9000] # milliseconds are kept
assert c["ARR"].stats["n_not_number"] == 1 and c["ARR"].stats["n_text"] == 1
assert c["ARR"].text.tolist() == ["1 2 3", None, None] and c["ARR"].value.tolist()[1:] == [7.0, 8.0]
st = log.index_stats()
assert (st["n_index_values"], st["n_index_distinct"], st["step_median"]) == (4, 4, 3.0)
def test_time_index_must_be_utc():
with pytest.raises(ValueError, match="does not end in 'Z'"):
parsed(time_log(["2013-04-08T01:45:28.000+01:00,1,2,Drilling,"]))
def test_chunk_boundary_duplicates_are_dropped_once():
a = time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,", "2013-04-08T01:45:31.000Z,2,20,Drilling,"])
b = time_log(["2013-04-08T01:45:31.000Z,2,21,Drilling,", "2013-04-08T01:45:34.000Z,3,30,Drilling,"])
c = by_name(parsed(a, b))
assert c["HKLD"].value.tolist() == [1.0, 2.0, 3.0] and c["HKLD"].chunk.tolist() == [1, 2, 2]
assert (c["HKLD"].stats["n_dup_same"], c["HKLD"].stats["n_dup_conflict"]) == (1, 0)
assert c["RPM"].value.tolist() == [10.0, 21.0, 30.0] # a conflict: the later file wins
assert (c["RPM"].stats["n_dup_same"], c["RPM"].stats["n_dup_conflict"]) == (0, 1)
assert c["PASS"].stats["n_dup_same"] == 1 and c["PASS"].text.tolist() == ["Drilling"] * 3
def test_log_must_stay_one_log():
a = time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,"])
with pytest.raises(ValueError, match="uid changes"):
parsed(a, time_log(["2013-04-08T01:45:31.000Z,1,10,Drilling,"], uid="L2"))
with pytest.raises(ValueError, match="2 log elements"):
doc = time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,"]).getvalue().decode()
one = doc[doc.index("<log "):doc.index("</logs>")]
read_log_file(io.BytesIO(doc.replace("</logs>", one + "</logs>").encode()))
def test_bad_rows_are_counted_not_guessed():
log = parsed(time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,", "2013-04-08T01:45:31.000Z,2,20,a,b,"]))
assert log.counts["rows"] == 2 and log.counts["bad_rows"] == 1 and by_name(log)["HKLD"].value.tolist() == [1.0]
def depth_log(rows: list[str], **kw) -> io.BytesIO:
curves = [("Depth", "m", "double", None), ("GR", "gAPI", "double", "-999.25"),
("Time", "unitless", "date time", None), ("CODE", "unitless", "long", None)]
return log_xml("measured depth", "Depth", curves, rows, **kw)
def test_depth_log_sorted_by_depth():
log = parsed(depth_log(["231.5,40.1,2013-03-22T21:53:39.000Z,111", "231.2,-999.25,2013-03-22T21:50:00.000Z,112",
"231.9,41,,113"]))
assert log.kind == "depth" and log.index_unit == "m" and log.index_stats()["n_index_backwards"] == 1
c = by_name(log)
assert c["GR"].index.tolist() == [231.5, 231.9] and c["GR"].stats["n_null_value"] == 1
assert c["CODE"].index.tolist() == [231.2, 231.5, 231.9] and c["CODE"].value.tolist() == [112.0, 111.0, 113.0]
assert c["CODE"].stats["n_out_of_order"] == 2
assert c["Time"].text.tolist() == ["2013-03-22T21:50:00.000Z", "2013-03-22T21:53:39.000Z"]
with pytest.raises(ValueError, match="expected metres"):
parsed(depth_log(["231.5,40.1,,111"], units="ft,gAPI,unitless,unitless"))
with pytest.raises(ValueError, match="unsupported indexType"):
parsed(log_xml("vertical depth", "Depth", [("Depth", "m", "double", None)], ["1"]))
def test_dedup_curve_keeps_the_last_row():
index = np.array([10, 20, 20, 30, 30, 30], dtype=np.int64)
value = np.array([1.0, 2.0, 2.0, 3.0, 4.0, 4.0])
chunk = np.array([1, 1, 2, 2, 3, 4], dtype=np.int16)
i, v, t, c, n = dedup_curve(index, value, None, chunk)
assert i.tolist() == [10, 20, 30] and v.tolist() == [1.0, 2.0, 4.0] and c.tolist() == [1, 2, 4] and t is None
assert n == {"n_dup_same": 2, "n_dup_conflict": 1, "n_out_of_order": 0}
text = np.array(["a", "b", "c", None, None, None], dtype=object)
i, v, t, c, n = dedup_curve(index, np.full(6, np.nan), text, chunk) # NaN == NaN for text rows
assert t.tolist() == ["a", "c", None] and n["n_dup_conflict"] == 1 and n["n_dup_same"] == 2
def curve(log_id: int, index: list, value: list, text: list | None = None) -> Curve:
return Curve(log_id, "BITDEP", np.array(index, dtype=np.int64), np.array(value, dtype=float),
None if text is None else np.array(text, dtype=object), np.full(len(index), 1, dtype=np.int16), {})
def test_merge_curve_ranks_and_keeps_every_row():
main = curve(7, [10, 20, 30, 40, 45], [1.0, 2.0, 3.0, 4.0, 4.5]) # most values: the preferred log
other = curve(3, [20, 30, 40, 50], [2.0, 3.00001, 9.0, 5.0]) # same, rounding, conflict, alone
third = curve(9, [20], [2.0])
log_id, index, value, text, chunk, rank, pairs = merge_curve([third, other, main])
assert index.tolist() == [10, 20, 20, 20, 30, 30, 40, 40, 45, 50]
assert log_id.tolist() == [7, 7, 3, 9, 7, 3, 7, 3, 7, 3] and rank.tolist() == [0, 0, 1, 2, 0, 1, 0, 1, 0, 0]
assert value[rank == 0].tolist() == [1.0, 2.0, 3.0, 4.0, 4.5, 5.0] # one value per index, none lost
p = {(r["log_id"], r["other_log_id"]): r for r in pairs}
assert (p[(7, 3)]["n"], p[(7, 3)]["n_same"], p[(7, 3)]["n_rounding"], p[(7, 3)]["n_conflict"]) == (3, 1, 1, 1)
assert p[(7, 3)]["max_abs_diff"] == 5.0 and p[(7, 9)]["n_same"] == 1
# equal sizes: the lower log_id is preferred; a single log has no pairs
assert merge_curve([curve(5, [1], [1.0]), curve(2, [1], [1.0])])[0].tolist() == [2, 5]
assert merge_curve([main])[6] == [] and merge_curve([main, curve(1, [99], [0.0])])[6] == []
def test_long_writer_round_trip(tmp_path):
w = LongWriter(tmp_path / "time_log" / "15_9_F_11_T2.parquet", "time", "15/9-F-11 T2", ["HKLD", "PASS"])
t0 = 1365385528000
w.write("HKLD", np.array([1, 1, 2], dtype=np.int32), np.array([t0, t0 + 3000, t0 + 3000]),
np.array([1.5, 2.5, 2.5]), None, np.array([1, 1, 4], dtype=np.int16), np.array([0, 0, 1], dtype=np.int8))
w.write("PASS", np.array([1], dtype=np.int32), np.array([t0]), np.array([np.nan]),
np.array(["Drilling"], dtype=object), np.array([1], dtype=np.int16), np.array([0], dtype=np.int8))
w.close()
df = pq.read_table(w.path).to_pandas()
assert w.rows == 4 and list(df.columns) == ["wellbore", "log_id", "mnemonic", "time", "value", "text", "chunk",
"dup_rank"]
assert set(df["wellbore"]) == {"15/9-F-11 T2"} and df["mnemonic"].tolist() == ["HKLD"] * 3 + ["PASS"]
assert df["time"].iloc[1] == pd.Timestamp("2013-04-08T01:45:31Z") and df["dup_rank"].tolist() == [0, 0, 1, 0]
assert df["value"].isna().tolist() == [False, False, False, True] and df["text"].iloc[3] == "Drilling"
assert not list(tmp_path.rglob("*.tmp"))
# ---------------------------------------------------------------------------------------------------------------
# wellbore names and the object tables
# ---------------------------------------------------------------------------------------------------------------
@pytest.mark.parametrize("name_well, name_wellbore, uid, expected", [
("NO 15/9-F-11", "NO 15/9-F-11 T2", "31f506a6", ("15/9-F-11 T2", "nameWellbore")),
("15/9-F-15B", "15/9-F-15B - Main Wellbore", "B-854763", ("15/9-F-15 B", "nameWellbore")),
("15/9-F-4", "EcoScope_Customer_Run5", "B-613073", ("15/9-F-4", "nameWell")),
("15/9-F-15S", "15/9-F-15S - Main Wellbore", "B-744206", ("15/9-F-15", "uidWellbore")),
("15/9-F-15", "15/9-F-15 - Main Wellbore", "B-826806", ("15/9-F-15 A", "uidWellbore")),
("15/9-F-15A", "15/9-F-15A - Main Wellbore", "B-861401", ("15/9-F-15 C", "uidWellbore")),
("NO 15/9-F-15", "NO 15/9-F-15 C", "9ab4989d", ("15/9-F-15 C", "nameWellbore")),
])
def test_wellbore_name(name_well, name_wellbore, uid, expected):
assert witsml.wellbore_name(name_well, name_wellbore, uid) == expected
def test_published_name_is_kept():
assert witsml.published_wellbore("15/9-F-15S", "15/9-F-15S - Main Wellbore") == ("15/9-F-15 S", "nameWellbore")
assert witsml.wellbore_dir("15/9-F-11 T2") == "15_9_F_11_T2"
def element(xml: str) -> ET.Element:
return ET.fromstring(f'<x xmlns="{NSURI}">{xml}</x>')
def test_flat_sentinels_units_and_nesting():
flat = Flat()
st = element('<md uom="m">-999.25</md><tvd uom="m">145.9</tvd><incl uom="rad">0.5</incl>'
'<dls uom="dega/m">0.1</dls><typeTrajStation>tie in point</typeTrajStation><empty uom="m"></empty>'
'<corUsed><stnGridCorUsed uom="rad">999.25</stnGridCorUsed>'
'<dirSensorOffset uom="m">0</dirSensorOffset></corUsed>'
'<commonData><itemState>actual</itemState><priv_ipOwner>10.0.0.1</priv_ipOwner></commonData>'
'<tubular uidRef="T1">string</tubular><p uid="a"><v>1</v></p><p uid="b"><v>2</v></p>')
row = flat.leaves(st, {}, "trajectory")
assert row["md"] is None and row["tvd"] == 145.9 and row["empty"] is None
assert row["incl"] == pytest.approx(28.6478897565) and row["dls"] == pytest.approx(3.0)
assert row["corUsed_stnGridCorUsed"] is None and row["corUsed_dirSensorOffset"] == 0.0
assert row["commonData_itemState"] == "actual" and "commonData_priv_ipOwner" not in row
assert row["tubular"] == "string" and row["tubular_uidRef"] == "T1"
assert (row["p_uid"], row["p_v"], row["p2_uid"], row["p2_v"]) == ("a", "1", "b", "2")
assert flat.sentinels == {("trajectory", "md", -999.25): 1, ("trajectory", "corUsed_stnGridCorUsed", 999.25): 1}
units = witsml.units_table(flat).set_index("column")
assert (units.loc["incl", "uom"], units.loc["incl", "uom_stored"]) == ("rad", "dega")
assert units.loc["dls", "uom_stored"] == "dega/30m" and units.loc["dls", "factor"] == 30.0
assert "md" not in units.index # a sentinel is not a value in a unit
assert witsml.sentinels_table(flat)["n"].sum() == 2
with pytest.raises(ValueError, match="repeated leaf"):
Flat().leaves(element('<md uom="m">1</md><md uom="m">2</md>'), {}, "trajectory")
# 999.25 is a sentinel only where it cannot be a value; -999 only in the mudLog gas readings
assert Flat().leaves(element('<md uom="m">999.25</md>'), {}, "trajectory")["md"] == 999.25
gas = Flat().leaves(element('<chromatograph><methAv uom="ppm">-999</methAv><methMx uom="ppm">999</methMx>'
'</chromatograph><ropAv uom="m/s">-999</ropAv>'), {}, "mudlog_intervals")
assert gas == {"chromatograph_methAv": None, "chromatograph_methMx": 999.0, "ropAv": -999.0}
def test_units_table_refuses_two_stored_units():
flat = Flat()
flat.units.update({("trajectory", "md", "m"): 1, ("trajectory", "md", "ft"): 1})
with pytest.raises(ValueError, match="more than one unit"):
witsml.units_table(flat)
def test_view_sql_names_the_depth_channels(tmp_path):
views = witsml.view_sql(tmp_path)
assert list(views) == ["time_log", "time_log_dedup", "depth_log", "depth_log_dedup", "drill_depth"]
assert f"{tmp_path.as_posix()}/time_log/*.parquet" in views["time_log"]
assert "dup_rank = 0" in views["depth_log_dedup"]
assert "(d.mnemonic = 'DMEA') OR (d.mnemonic = 'Depth' AND c.name = 'GenTime')" in views["drill_depth"]
assert "(d.mnemonic = 'DBTM') OR (d.mnemonic = 'BITDEP' AND c.name = 'GenTime')" in views["drill_depth"]
def test_tadi_filters_only_flag():
df = pd.DataFrame({"ropAv": [0.01, 0.06, None], "rpmAv": [2.0, 2.0, 6.0], "wobAv": [1e5, 1e5, 1e5]})
assert witsml.tadi_implausible(df).tolist() == [False, True, True] # 0.06 m/s = 216 m/h; 6 c/s = 360 rpm
# ---------------------------------------------------------------------------------------------------------------
# formation tops
# ---------------------------------------------------------------------------------------------------------------
WIDTHS = [24, 40, 5, 3, 8, 8, 8, 8, 6, 6, 9, 9, 5] # the dash line of the picks file
def picks_line(*cells) -> str:
return " " + " ".join(str(c).ljust(w) for c, w in zip(cells, WIDTHS))
def picks_block(well: str, rows: list[tuple]) -> str:
head = [f"Well {well}", picks_line(*tops.COLUMNS), picks_line(*("-" * w for w in WIDTHS))]
return "\n".join(head + [picks_line(well, *r, "STAT") for r in rows]) + "\n\n"
PICKS = "# Qlf column\n# NL: Not logged\n\n" + picks_block("NO 15/9-19 SR", [
("Seabed", 1, "", "106.00", "106.00", "-81.00", "81.08", "", "", "437506.0", "6477887.5"),
("HORDALAND GP. Top", 1, "NL", "1107.50", "1057.14", "-1032.14", "998.00", "", "", "437313.9", "6477939.3"),
("Hugin Fm. VOLVE Base", 2, "", "4340.00", "2904.66", "-2879.66", "2566.01", "1.27", "3.00", "434734.9",
"6478413.8"),
]) + picks_block("NO 15/9-F-12 pilot", [
("Utsira Fm. Top", 1, "", "882.45", "882.42", "-827.52", "900.57", "", "", "435055.3", "6478564.5"),
]) + picks_block("NO 15/5-7 A", [("Sleipner Fm. Top", 1, "", "4098.10", "", "", "", "", "", "", "")])
def test_parse_picks(tmp_path):
f = tmp_path / "picks.dat"
f.write_text(PICKS, encoding="ascii")
p = tops.parse_picks(f, {"15/9-19 S", "15/9-19 ST2", "15/9-F-12"})
assert len(p) == 5 and p["wellbore_picks"].tolist() == ["15/9-19 SR"] * 3 + ["15/9-F-12 pilot", "15/5-7 A"]
assert p["wellbore"].tolist()[:4] == ["15/9-19 ST2"] * 3 + ["15/9-F-12"] and pd.isna(p["wellbore"].iloc[4])
assert p["track"].tolist() == ["main"] * 3 + ["pilot", "main"]
hugin = p.iloc[2]
assert (hugin["surface"], hugin["unit"], hugin["boundary"], hugin["obs"]) == (
"Hugin Fm. VOLVE Base", "Hugin Fm. VOLVE", "Base", 2)
assert (hugin["md"], hugin["tvdss"], hugin["dip"], hugin["azi"], hugin["northing"]) == (
4340.0, -2879.66, 1.27, 3.0, 6478413.8)
assert p.iloc[0]["boundary"] is None or pd.isna(p.iloc[0]["boundary"]) # "Seabed" has no Top/Base
assert p.iloc[1]["qlf"] == "NL" and pd.isna(p.iloc[0]["qlf"]) and pd.isna(p.iloc[4]["tvd"])
assert p["line"].tolist() == [7, 8, 9, 14, 19]
shared = tops.shared_trunk_picks(p) # above the kick-off at 1493 m
assert shared["wellbore"].tolist() == ["15/9-19 S"] * 2 and shared["md"].tolist() == [106.0, 1107.5]
assert set(shared["inherited_from"]) == {"15/9-19 SR"} and set(shared["md_kickoff"]) == {1493.0}
def test_parse_picks_rejects_a_broken_file(tmp_path):
f = tmp_path / "picks.dat"
f.write_text(PICKS.replace("NO 15/9-F-12 pilot Utsira", "NO 15/9-F-12 Utsira"),
encoding="ascii")
with pytest.raises(ValueError, match="in the block of"):
tops.parse_picks(f)
f.write_text(PICKS.replace(" NL 1107.50", " XX 1107.50"), encoding="ascii")
with pytest.raises(ValueError, match="unknown qualifiers"):
tops.parse_picks(f)
# ---------------------------------------------------------------------------------------------------------------
# the Volve files
# ---------------------------------------------------------------------------------------------------------------
ROOT = paths.witsml_dir()
OUT = paths.outputs_dir() / "witsml"
needs_data = pytest.mark.skipif(not ROOT.is_dir(), reason="missing the WITSML folder")
needs_picks = pytest.mark.skipif(not paths.well_picks_file().is_file(), reason="missing the well picks file")
needs_tables = pytest.mark.skipif(not (OUT / "summary.json").is_file(),
reason="missing outputs/witsml: run scripts/06_parse_witsml.py")
@pytest.mark.data
@needs_data
def test_find_logs_and_wellbores():
logs = witsml.find_logs(ROOT)
assert len(logs) == 2047 and sum(len(files) for *_, files in logs) == 7150
assert sum(1 for _ in ROOT.rglob("log/**/*.xml")) == 7150 # no log file outside the layout
names = {}
for folder, wb_dir, directory, files in logs:
h = read_log_file(files[0], header_only=True).header
wellbore, _ = witsml.wellbore_name(h["nameWell"], h["nameWellbore"], h["uidWellbore"])
names.setdefault((folder, wb_dir), (h["uidWellbore"], h["nameWellbore"], wellbore))
assert len(names) == 33 # wellbore folders with logs
wellbores = {wb for *_, wb in names.values()}
assert len(wellbores) == 21 and "15/9-F-15 S" not in wellbores
assert names[("Norway-StatoilHydro-15_$47$_9-F-15S", "1")] == (
"B-744206", "15/9-F-15S - Main Wellbore", "15/9-F-15")
assert names[("Norway-StatoilHydro-15_$47$_9-F-15", "1")][2] == "15/9-F-15 A"
assert names[("Norway-StatoilHydro-15_$47$_9-F-15A", "1")][2] == "15/9-F-15 C"
assert names[("Norway-StatoilHydro-15_$47$_9-F-15B", "1")][2] == "15/9-F-15 B"
# a well folder holds several wellbores: the folder name is not the wellbore
assert {names[("Norway-Statoil-NO 15_$47$_9-F-11", n)][2] for n in "1234"} == {
"15/9-F-11", "15/9-F-11 A", "15/9-F-11 B", "15/9-F-11 T2"}
assert {names[("Norway-Statoil-NO 15_$47$_9-F-15", n)][2] for n in "12"} == {"15/9-F-15 C", "15/9-F-15 D"}
@pytest.mark.data
@needs_data
def test_parse_one_log():
directory = ROOT / "Norway-StatoilHydro-15_$47$_9-F-15B" / "1" / "log" / "2" / "1" / "1"
log = witsml.parse_log(sorted(directory.glob("*.xml")))
curves = log.curves()
assert (log.header["uid"], log.header["name"], log.kind) == ("L-854765-MD", "8.5in section - MD Log", "depth")
assert log.counts["rows"] == 650 and log.counts["bad_rows"] == 0 and len(log.curve_info) == 386
assert len(curves) == 385 and sum(len(c.index) for c in curves) == 12898
assert all((np.diff(c.index) > 0).all() for c in curves)
@pytest.mark.data
@needs_data
def test_parse_objects_counts():
t, flat = witsml.parse_objects(ROOT)
assert {k: len(v) for k, v in t.items()} == {
"trajectory_catalog": 63, "trajectory": 5561, "messages": 11134, "bha_runs": 161, "mudlog_catalog": 8,
"mudlog_intervals": 2882, "mudlog_lithology": 3617, "mudlog_qualifiers": 2951}
assert sum(flat.sentinels.values()) == 3703
assert flat.sentinels[("trajectory", "corUsed_stnGridCorUsed", 999.25)] == 2123
traj = t["trajectory"]
assert traj["incl"].between(0, 180).all() and traj["azi"].dropna().between(0, 360).all() # degrees
assert set(t["trajectory_catalog"].loc[t["trajectory_catalog"]["wellbore_source"] == "uidWellbore",
"wellbore"]) == {"15/9-F-15", "15/9-F-15 A", "15/9-F-15 C"}
assert t["mudlog_intervals"]["wellbore"].nunique() == 8 and t["messages"]["wellbore"].nunique() == 16
assert witsml.units_table(flat).groupby(["table", "column"])["uom_stored"].nunique().max() == 1
@pytest.mark.data
@needs_picks
def test_well_picks():
p = tops.parse_picks(paths.well_picks_file())
assert len(p) == 409 and p["wellbore_picks"].nunique() == 35 and p["md"].notna().all()
assert set(p.loc[p["wellbore_picks"] == "15/9-19 SR", "wellbore"]) == {"15/9-19 ST2"}
assert set(p.loc[p["wellbore_picks"] == "15/9-F-12 pilot", "wellbore"]) == {"15/9-F-12"}
assert (p["wellbore_picks"] == "15/9-19 SR").sum() == 15 and (p["track"] == "pilot").sum() == 3
shared = tops.shared_trunk_picks(p)
assert shared.groupby("wellbore").size().to_dict() == {"15/9-19 S": 4, "15/9-F-9 A": 2}
assert shared["md"].max() == 1107.5
def _script():
spec = importlib.util.spec_from_file_location("parse_witsml", paths.REPO_ROOT / "scripts" / "06_parse_witsml.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.data
@needs_tables
def test_locked_counts():
summary = json.loads((OUT / "summary.json").read_text(encoding="utf-8"))
assert summary["counts"] == _script().EXPECTED
assert summary["checks"]["wellbore_identity_wrong"] == []
assert summary["duplicates"]["in_log_conflict"] == {"depth": 0, "time": 0}
assert summary["counts"]["log_bad_rows"] == 0
@pytest.mark.data
@needs_tables
def test_tables_keys_and_mapping():
with witsml.connect(OUT) as con:
def one(sql: str):
return con.execute(sql).fetchone()[0]
assert one("SELECT count(*) FROM log_catalog") == 2047
assert one("SELECT count(DISTINCT wellbore) FROM log_catalog") == 21
assert one("SELECT count(*) FROM log_catalog WHERE wellbore = '15/9-F-15 S'") == 0
assert con.execute("SELECT DISTINCT wellbore_witsml, wellbore FROM log_catalog WHERE wellbore_source = "
"'uidWellbore' ORDER BY 1").fetchall() == [
("15/9-F-15", "15/9-F-15 A"), ("15/9-F-15 A", "15/9-F-15 C"), ("15/9-F-15 S", "15/9-F-15")]
# the long table of a small wellbore: values = catalog, one row per (log, mnemonic, time), dedup view unique
wb = "15/9-F-15 B"
n = one(f"SELECT count(*) FROM time_log WHERE wellbore = '{wb}'")
assert n == one(f"SELECT sum(n_values) FROM log_catalog WHERE wellbore = '{wb}' AND kind = 'time'")
assert n == one(f"SELECT count(*) FROM (SELECT DISTINCT log_id, mnemonic, time FROM time_log "
f"WHERE wellbore = '{wb}')")
kept = one(f"SELECT count(*) FROM time_log_dedup WHERE wellbore = '{wb}'")
assert kept == one(f"SELECT count(*) FROM (SELECT DISTINCT mnemonic, time FROM time_log "
f"WHERE wellbore = '{wb}')")
assert n - kept == one(f"SELECT sum(n_ranked) FROM log_curves WHERE wellbore = '{wb}' AND kind = 'time'")
assert one("SELECT count(*) FROM formation_tops") == 409
assert one("SELECT count(*) FROM formation_tops_all") == 415
assert one("SELECT count(DISTINCT wellbore) FROM formation_tops_all WHERE wellbore IS NOT NULL") == 26

98
volve_dia/audit.py Normal file
View File

@@ -0,0 +1,98 @@
"""Blind audit of the activity labels: stratified sample, masked rating sheet, agreement.
The rater sees what a model sees (the masked input view `t2_inputs`, plus the comments of the activities before and
after in the same report) and never the codes or the labels. The key (item -> act_id, stratum, weight, labels) is
written to a separate file. Agreement is Cohen's kappa, unweighted and weighted back to the population by the
inverse inclusion probability of each stratum.
"""
from __future__ import annotations
import math
import numpy as np
import pandas as pd
#: Values the rater may choose (labels.yaml t2.cause_groups without hse, t1.op_classes without interruption).
CAUSES = ("equipment", "weather", "waiting", "stuck_fishing", "lost_circulation", "well_control", "sidetrack",
"operation_failed", "unspecified")
OP_CLASSES = ("drill_ream", "trip", "casing_cement", "circulate", "bop_wellhead", "formation_evaluation", "completion",
"perforate", "wireline", "plug_abandon", "rig_move", "rig_up_down", "wait", "other")
def allocate(sizes: dict[str, int], k: int, minimum: int) -> dict[str, int]:
"""Split k items over strata: `minimum` each (or the whole stratum if smaller), the rest proportional to the
square root of the stratum size, by largest remainder, never more than a stratum holds."""
sizes = {s: int(n) for s, n in sizes.items() if n > 0}
out = {s: min(minimum, n) for s, n in sizes.items()}
if sum(out.values()) > k:
raise ValueError(f"{len(sizes)} strata x minimum {minimum} > {k} items")
while sum(out.values()) < k:
room = {s: n - out[s] for s, n in sizes.items() if n > out[s]}
if not room:
break
left = k - sum(out.values())
w = {s: math.sqrt(sizes[s]) for s in room}
share = {s: left * w[s] / sum(w.values()) for s in room}
add = {s: min(room[s], int(share[s])) for s in room}
if sum(add.values()) == 0: # hand out single items by largest remainder
for s in sorted(room, key=lambda s: (-(share[s] - int(share[s])), s))[:left]:
add[s] = 1
for s, a in add.items():
out[s] += a
return out
def spread_sample(frame: pd.DataFrame, k: int, by: str, rng: np.random.Generator) -> pd.DataFrame:
"""k rows of `frame`, spread over the values of `by` (round robin over a random order of the groups)."""
if k >= len(frame):
return frame
f = frame.sample(frac=1.0, random_state=rng.integers(2**31))
order = {g: i for i, g in enumerate(rng.permutation(f[by].unique()))}
f = f.assign(_rank=f.groupby(by).cumcount(), _g=f[by].map(order))
return f.sort_values(["_rank", "_g"]).head(k).drop(columns=["_rank", "_g"])
def zone(npt_a: pd.Series, npt_b: pd.Series) -> pd.Series:
"""a = NPT under both definitions, b_only = only under the union, none = neither."""
return pd.Series(np.where(npt_a, "a", np.where(npt_b, "b_only", "none")), index=npt_a.index)
def draw(frame: pd.DataFrame, plan: dict[str, int], minimum: int, seed: int) -> pd.DataFrame:
"""Stratified sample. `frame` has act_id, well, zone, stratum (zone/class). `plan` gives the items per zone.
Returns the sampled rows with n_stratum, k_stratum and weight = n_stratum / k_stratum."""
rng = np.random.default_rng(seed)
parts = []
for z, k in plan.items():
fz = frame[frame["zone"] == z]
alloc = allocate(fz["stratum"].value_counts().to_dict(), k, minimum)
for s, ks in sorted(alloc.items()):
fs = fz[fz["stratum"] == s]
parts.append(spread_sample(fs, ks, "well", rng).assign(n_stratum=len(fs), k_stratum=ks))
out = pd.concat(parts, ignore_index=True)
out["weight"] = out["n_stratum"] / out["k_stratum"]
return out.sample(frac=1.0, random_state=seed).reset_index(drop=True)
def cohen_kappa(a: pd.Series, b: pd.Series, weight: pd.Series | None = None) -> float | None:
"""Cohen's kappa of two label series (optionally with item weights). None if undefined."""
m = a.notna() & b.notna()
a, b = a[m].astype(str), b[m].astype(str)
w = pd.Series(1.0, index=a.index) if weight is None else weight[m].astype(float)
if w.sum() == 0:
return None
po = float(w[a == b].sum() / w.sum())
pa = w.groupby(a).sum() / w.sum()
pb = w.groupby(b).sum() / w.sum()
pe = float(sum(pa.get(c, 0.0) * pb.get(c, 0.0) for c in set(pa.index) | set(pb.index)))
return None if pe >= 1.0 else (po - pe) / (1.0 - pe)
def agreement(a: pd.Series, b: pd.Series, weight: pd.Series | None = None) -> dict:
m = a.notna() & b.notna()
w = pd.Series(1.0, index=a.index) if weight is None else weight.astype(float)
k = cohen_kappa(a, b, weight)
return {"n": int(m.sum()),
"agreement": (round(float(w[m & (a.astype(str) == b.astype(str))].sum() / w[m].sum()), 4)
if m.any() else None),
"kappa": None if k is None else round(k, 4)}

768
volve_dia/labels.py Normal file
View File

@@ -0,0 +1,768 @@
"""Deterministic labels T1-T3 of Volve-DIA, from the DDR XML tables (volve_dia.ddr.xml) and configs/labels.yaml.
Every function is pure: DataFrames in, a label table out, no file access except `load_config`. Every label row
carries its provenance: the source row (`report_id` or `act_id`), the rule (`*_rule`, ids below) and the source
columns. Nothing here reads HTML, PDF or OCR text, and no label is taken from free text.
Sources (tables of outputs/ddr/): `reports` (diaHole, diaPilot, mdDiaHoleStart, mdCsgLast, md, dTimSpud, waterDepth,
elevKelly, sum24Hr, forecast24Hr), `activities` (proprietaryCode, code_main, code_sub, state, stateDetailActivity,
md, comments, start_utc, end_utc, duration_h), `bits` (diaBit) and `casings` (od, mdBottom); the last two are used
only by candidate fill rules.
Rules
T1.S1 section = reports.diaHole of the report itself.
T1.S2 no diaHole: forward fill, the last known diaHole of an earlier report of the same wellbore.
T1.S3 no earlier known diaHole: the first known diaHole of the wellbore (`bfill_leading`).
T1.P1 phase = nominal phase of the hole size (labels.yaml t1.hole_sizes); T1.P2: `pilot` when diaPilot is set.
T1.O1 operation class = op_class of the proprietaryCode (labels.yaml codes).
T2.Na NPT (a) = interruption group. T2.Nb NPT (b) = (a) or state == fail or stateDetailActivity != success.
T2.C1 cause named by the interruption sub-code. T2.C2 cause from stateDetailActivity. T2.C3 unspecified.
T3.D1 depth class of activities.md against the mud line. T3.G1 cell = floor(md / grid).
T3.E1 episode = run of consecutive NPT activities in time. T3.M1 interval = run of touching positive cells.
Activity codes are label sources, so they are masked in model inputs: `t2_inputs` builds the masked view and raises
if a column of `MASKED` is in it. The free text is the legitimate input; `text_rates` only measures how often it
names the label.
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Callable
import numpy as np
import pandas as pd
import yaml
from .names import stem, well_of
from .paths import REPO_ROOT
#: Columns a model must never read for T2 and T3 (they are the label sources).
MASKED = ("proprietaryCode", "code_main", "code_sub", "state", "stateDetailActivity")
NPT_DEFINITIONS = ("a", "b")
MASK_SCHEMES = ("single", "tail_half", "head_half", "whole_run")
# ---------------------------------------------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------------------------------------------
def load_config(path: Path | None = None) -> dict:
"""configs/labels.yaml, checked for internal consistency (classes used are classes declared)."""
cfg = yaml.safe_load((path or REPO_ROOT / "configs" / "labels.yaml").read_text(encoding="utf-8"))
if cfg.get("version") != 1:
raise ValueError(f"labels.yaml version {cfg.get('version')!r}, expected 1")
ops, causes = set(cfg["t1"]["op_classes"]), set(cfg["t2"]["cause_groups"])
for code, row in cfg["codes"].items():
if " -- " not in code:
raise ValueError(f"not a proprietaryCode: {code!r}")
if row["op_class"] not in ops:
raise ValueError(f"{code}: op_class {row['op_class']!r} is not declared in t1.op_classes")
if row["cause"] != "detail" and row["cause"] not in causes:
raise ValueError(f"{code}: cause {row['cause']!r} is not declared in t2.cause_groups")
if row["cause"] != "detail" and not code.startswith("interruption -- "):
raise ValueError(f"{code}: only interruption codes may name a cause")
for detail, row in cfg["t2"]["cause_from_detail"].items():
if row["cause"] is not None and row["cause"] not in causes:
raise ValueError(f"stateDetailActivity {detail!r}: cause {row['cause']!r} is not declared")
if cfg["t2"]["default_cause"] not in causes:
raise ValueError("t2.default_cause is not declared in t2.cause_groups")
if set(cfg["t2"]["masked_columns"]) != set(MASKED):
raise ValueError("t2.masked_columns differs from labels.MASKED")
if cfg["t1"]["fill"]["rule"] not in FILL_RULES or cfg["t1"]["fill"]["leading"] not in FILL_RULES:
raise ValueError("t1.fill names an unknown rule")
return cfg
def check_code_counts(activities: pd.DataFrame, cfg: dict) -> dict:
"""Differences between the counts written in labels.yaml and the data: {} when the file matches the source."""
diff: dict = {}
got = activities["proprietaryCode"].value_counts().to_dict()
want = {code: row["n"] for code, row in cfg["codes"].items()}
for code in sorted(set(got) | set(want)):
if got.get(code) != want.get(code):
diff[code] = (want.get(code), got.get(code))
for column, table in (("stateDetailActivity", cfg["t2"]["cause_from_detail"]), ("state", cfg["t2"]["state"])):
got = activities[column].value_counts().to_dict()
for value in sorted(set(got) | set(table)):
if got.get(value) != table.get(value, {}).get("n"):
diff[f"{column}={value}"] = (table.get(value, {}).get("n"), got.get(value))
return diff
# ---------------------------------------------------------------------------------------------------------------
# Report timeline
# ---------------------------------------------------------------------------------------------------------------
def timeline(reports: pd.DataFrame, activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""One row per report, ordered by wellbore and time, with `well`, the activity counts and `status`:
`ok`, `no_activities` (a real day without activity rows) or `placeholder_date` (see labels.yaml reports)."""
r = reports.copy()
r["well"] = r["wellbore"].map(well_of)
a = activities.assign(_drill=activities["code_main"].eq("drilling"))
per = a.groupby("report_id").agg(n_activities=("act_id", "size"), n_drilling_activities=("_drill", "sum"),
hours_activities=("duration_h", "sum"))
r = r.merge(per, on="report_id", how="left")
r[["n_activities", "n_drilling_activities"]] = r[["n_activities", "n_drilling_activities"]].fillna(0).astype(int)
r["hours_activities"] = r["hours_activities"].fillna(0.0)
spud = pd.to_datetime(r["dTimSpud"], utc=True, format="ISO8601")
days = pd.Timedelta(days=cfg["reports"]["placeholder_days_before_spud"])
placeholder = r["n_activities"].eq(0) & spud.notna() & (r["end_utc"] < spud - days)
r["status"] = np.select([placeholder, r["n_activities"].eq(0)], ["placeholder_date", "no_activities"], "ok")
return r.sort_values(["wellbore", "start_utc", "report_id"], kind="stable").reset_index(drop=True)
# ---------------------------------------------------------------------------------------------------------------
# T1: hole size in the text (cross-check only) and candidate fill rules
# ---------------------------------------------------------------------------------------------------------------
_FRACTIONS = {"½": 0.5, "¼": 0.25, "¾": 0.75}
_HOLE_SIZE = re.compile(
r"(?<![\d/.,])(\d{1,2})(?:\s*[- ]\s*(\d)\s*/\s*(\d)|[.,](\d{1,3})|\s*([½¼¾]))?"
r"\s*(?:\"|''|”|in\b\.?|inch(?:es)?\b)\s*(?:pilot\s*)?(?:hole|section|open\s*hole|pilothole|oh\b)", re.I)
def hole_sizes_in_text(text: str | None, sizes: tuple[float, ...]) -> list[float]:
"""Hole sizes named in `text` as '<size>" hole|section|pilot hole|open hole' (12 1/4", 12.25", 12¼", 8-1/2in),
kept only when they are one of `sizes`. One entry per mention."""
out = []
for whole, num, den, dec, glyph in _HOLE_SIZE.findall(text or ""):
v = float(whole)
if num and den and den != "0":
v += int(num) / int(den)
elif dec:
v += float("0." + dec)
elif glyph:
v += _FRACTIONS[glyph]
if any(abs(v - s) < 1e-6 for s in sizes):
out.append(v)
return out
def _most_frequent(values: list[float]) -> float:
"""The most frequent value; NaN when there is none or the top count is tied."""
if not values:
return np.nan
counts = pd.Series(values).value_counts()
if len(counts) > 1 and counts.iloc[0] == counts.iloc[1]:
return np.nan
return float(counts.index[0])
def fill_features(tl: pd.DataFrame, activities: pd.DataFrame, bits: pd.DataFrame, casings: pd.DataFrame,
cfg: dict) -> pd.DataFrame:
"""`tl` (from `timeline`) plus the columns the candidate fill rules read:
`dia` (reports.diaHole; unknown on placeholder reports), `bit_dia` (largest valid bits.diaBit of the report),
`casing_hole` (next hole size after the last casing, from casings.od at the shoe nearest to mdCsgLast) and
`text_dia` (hole size named most often in sum24Hr and the drilling-group comments; cross-check only)."""
f = tl.copy()
f["dia"] = f["diaHole"].where(f["status"].ne("placeholder_date"))
sizes = tuple(float(s) for s in cfg["t1"]["hole_sizes"])
valid = bits[bits["diaBit"] > 0] if len(bits) else bits
f["bit_dia"] = f["report_id"].map(valid.groupby("report_id")["diaBit"].max() if len(valid) else {}).astype(float)
fill = cfg["t1"]["fill"]
next_hole = {round(float(k), 3): float(v) for k, v in fill["casing_od_to_next_hole"].items()}
shoes: dict[str, np.ndarray] = {}
if len(casings):
c = casings.dropna(subset=["od", "mdBottom"]).assign(well=lambda d: d["wellbore"].map(well_of))
shoes = {w: g[["mdBottom", "od"]].to_numpy(float) for w, g in c.groupby("well")}
casing_hole = np.full(len(f), np.nan)
for i, (w, shoe) in enumerate(zip(f["well"], f["mdCsgLast"])):
if w in shoes and pd.notna(shoe):
dist = np.abs(shoes[w][:, 0] - shoe)
j = int(dist.argmin())
if dist[j] <= fill["casing_shoe_tolerance_m"]:
casing_hole[i] = next_hole.get(round(float(shoes[w][j, 1]), 3), np.nan)
f["casing_hole"] = casing_hole
drill = activities[activities["code_main"].eq("drilling")]
comments = drill.groupby("report_id")["comments"].agg(lambda s: "\n".join(s.dropna()))
text = f["sum24Hr"].fillna("") + "\n" + f["report_id"].map(comments).fillna("")
f["text_dia"] = [_most_frequent(hole_sizes_in_text(t, sizes)) for t in text]
return f
def _ffill(g: pd.DataFrame) -> np.ndarray:
return g["dia"].ffill().to_numpy(float)
def _bfill(g: pd.DataFrame) -> np.ndarray:
return g["dia"].bfill().to_numpy(float)
def _ffill_bfill(g: pd.DataFrame) -> np.ndarray:
return g["dia"].ffill().bfill().to_numpy(float)
def _nearest(g: pd.DataFrame) -> np.ndarray:
"""Known diaHole of the report nearest in time; the earlier one on a tie."""
t = g["start_utc"].astype("int64").astype(float)
known = g["dia"].notna()
before, after = t.where(known).ffill(), t.where(known).bfill()
prev, nxt = g["dia"].ffill(), g["dia"].bfill()
use_prev = nxt.isna() | (prev.notna() & ((t - before) <= (after - t)))
return np.where(use_prev, prev, nxt).astype(float)
def _by_key(column: str) -> Callable[[pd.DataFrame], np.ndarray]:
"""diaHole that the known reports of the wellbore with the same value of `column` carry most often (ties: the
smaller size)."""
def rule(g: pd.DataFrame) -> np.ndarray:
k = g.loc[g["dia"].notna() & g[column].notna(), [column, "dia"]]
if k.empty:
return np.full(len(g), np.nan)
table = k.groupby(column)["dia"].agg(lambda s: s.value_counts().sort_index().idxmax())
return g[column].map(table).to_numpy(float)
return rule
def _depth_range(g: pd.DataFrame) -> np.ndarray:
"""Section whose depth range [min md, max md] over the known reports of the wellbore contains the report md
(1 m tolerance); the smaller size when several do."""
k = g.loc[g["dia"].notna() & g["md"].notna()]
out = np.full(len(g), np.nan)
if k.empty:
return out
spans = k.groupby("dia")["md"].agg(["min", "max"]).sort_index()
for i, md in enumerate(g["md"].to_numpy(float)):
if not np.isnan(md):
hit = spans.index[(spans["min"] - 1 <= md) & (md <= spans["max"] + 1)]
if len(hit):
out[i] = hit[0]
return out
#: Candidate fill rules: frame of one wellbore in time order (columns of `fill_features`, `dia` NaN where unknown
#: or masked) -> predicted hole size per report (NaN = no answer).
FILL_RULES: dict[str, Callable[[pd.DataFrame], np.ndarray]] = {
"ffill": _ffill,
"bfill": _bfill,
"ffill_bfill": _ffill_bfill,
"nearest": _nearest,
"hole_start": _by_key("mdDiaHoleStart"),
"csg_last": _by_key("mdCsgLast"),
"depth_range": _depth_range,
"bit_report": lambda g: g["bit_dia"].to_numpy(float),
"bit_ffill": lambda g: g["bit_dia"].ffill().to_numpy(float),
"casing_program": lambda g: g["casing_hole"].to_numpy(float),
"text": lambda g: g["text_dia"].to_numpy(float),
}
#: Rules that do not read `dia`: masking cannot change their answer.
_DIA_FREE = ("bit_report", "bit_ffill", "casing_program", "text")
def known_runs(dia: np.ndarray) -> list[np.ndarray]:
"""Maximal runs of consecutive reports with the same known hole size, as position arrays."""
runs, start = [], None
for i in range(len(dia) + 1):
same = i < len(dia) and start is not None and not np.isnan(dia[i]) and dia[i] == dia[start]
if start is not None and not same:
runs.append(np.arange(start, i))
start = None
if start is None and i < len(dia) and not np.isnan(dia[i]):
start = i
return runs
def fill_masks(dia: np.ndarray, scheme: str) -> list[np.ndarray]:
"""Sets of positions to mask together under `scheme`. `single`: every known report alone; `tail_half` /
`head_half`: the last / first n // 2 reports of every run of n >= 2; `whole_run`: every run."""
runs = known_runs(dia)
if scheme == "single":
return [np.array([i]) for run in runs for i in run]
if scheme == "whole_run":
return runs
if scheme == "tail_half":
return [run[len(run) - len(run) // 2:] for run in runs if len(run) >= 2]
if scheme == "head_half":
return [run[:len(run) // 2] for run in runs if len(run) >= 2]
raise ValueError(f"unknown masking scheme {scheme!r}")
def evaluate_fill_rules(feat: pd.DataFrame, rules: tuple[str, ...] | None = None,
schemes: tuple[str, ...] = MASK_SCHEMES) -> pd.DataFrame:
"""Mask known hole sizes and count how often each rule recovers them.
One row per (rule, scheme, wellbore): `n_masked`, `n_answered` (the rule gave a value) and `n_correct`.
Each mask set is evaluated alone, with every other known value visible."""
rules = rules or tuple(FILL_RULES)
rows = []
live = feat[feat["status"].ne("placeholder_date")]
for wellbore, g in live.groupby("wellbore", sort=True):
g = g.reset_index(drop=True)
truth = g["dia"].to_numpy(float)
fixed = {name: FILL_RULES[name](g) for name in rules if name in _DIA_FREE}
for scheme in schemes:
tally = {name: np.zeros(3, dtype=int) for name in rules}
for mask in fill_masks(truth, scheme):
masked = g.assign(dia=g["dia"].mask(g.index.isin(mask)))
for name in rules:
pred = (fixed[name] if name in fixed else FILL_RULES[name](masked))[mask]
tally[name] += (len(mask), int(np.sum(~np.isnan(pred))), int(np.sum(pred == truth[mask])))
rows += [{"rule": name, "scheme": scheme, "wellbore": wellbore, "n_masked": int(t[0]),
"n_answered": int(t[1]), "n_correct": int(t[2])} for name, t in tally.items()]
return pd.DataFrame(rows)
def summarise_fill_eval(ev: pd.DataFrame, by_wellbore: bool = False) -> pd.DataFrame:
"""`recovered` = correct / masked, `coverage` = answered / masked, `precision` = correct / answered."""
keys = ["rule", "scheme"] + (["wellbore"] if by_wellbore else [])
s = ev.groupby(keys, sort=False)[["n_masked", "n_answered", "n_correct"]].sum().reset_index()
s["recovered"] = (s["n_correct"] / s["n_masked"]).round(4)
s["coverage"] = (s["n_answered"] / s["n_masked"]).round(4)
s["precision"] = (s["n_correct"] / s["n_answered"].where(s["n_answered"] > 0)).round(4)
return s
def fill_on_missing(feat: pd.DataFrame, rules: tuple[str, ...] | None = None) -> pd.DataFrame:
"""The rules on the reports that really lack diaHole (nothing masked): how many they answer, and how often the
answer agrees with two independent readings of the same report where those exist: the hole size named in the
text (`text_dia`) and the bit record of the report (`bit_dia`). Rows: (rule, subset) for `all_missing` and
`missing_drilling_day` (at least one drilling-group activity)."""
rules = rules or tuple(FILL_RULES)
live = feat[feat["status"].ne("placeholder_date")]
preds = {name: [] for name in rules}
parts = []
for _, g in live.groupby("wellbore", sort=True):
g = g.reset_index(drop=True)
parts.append(g)
for name in rules:
preds[name].append(FILL_RULES[name](g))
allr = pd.concat(parts, ignore_index=True)
missing = allr["dia"].isna().to_numpy()
subsets = {"all_missing": missing, "missing_drilling_day": missing & (allr["n_drilling_activities"] > 0).to_numpy()}
text, bit = allr["text_dia"].to_numpy(float), allr["bit_dia"].to_numpy(float)
rows = []
for name in rules:
pred = np.concatenate(preds[name])
for subset, sel in subsets.items():
answered = sel & ~np.isnan(pred)
with_text, with_bit = answered & ~np.isnan(text), answered & ~np.isnan(bit)
rows.append({"rule": name, "subset": subset, "n": int(sel.sum()), "n_answered": int(answered.sum()),
"n_text": int((sel & ~np.isnan(text)).sum()), "n_both": int(with_text.sum()),
"n_agree_text": int((with_text & (pred == text)).sum()),
"n_bit": int((sel & ~np.isnan(bit)).sum()), "n_both_bit": int(with_bit.sum()),
"n_agree_bit": int((with_bit & (pred == bit)).sum())})
return pd.DataFrame(rows)
# ---------------------------------------------------------------------------------------------------------------
# T1 labels
# ---------------------------------------------------------------------------------------------------------------
def operation_classes(activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""T1 operation label of every activity: `op_group` (main code), `op_sub` (sub-code), `op_class` (labels.yaml)."""
codes = cfg["codes"]
unknown = sorted(set(activities["proprietaryCode"].dropna()) - set(codes))
if unknown or activities["proprietaryCode"].isna().any():
raise ValueError(f"proprietaryCode missing or not in labels.yaml: {unknown}")
out = activities[["act_id", "report_id", "wellbore"]].copy()
out["well"] = out["wellbore"].map(well_of)
out["op_group"] = activities["code_main"].to_numpy()
out["op_sub"] = activities["code_sub"].to_numpy()
out["op_class"] = activities["proprietaryCode"].map({c: row["op_class"] for c, row in codes.items()}).to_numpy()
out["op_rule"] = "T1.O1"
out["op_source"] = "activities.proprietaryCode"
return out
def _seconds(times: pd.Series) -> np.ndarray:
"""UTC timestamps as seconds since 1970 (float), whatever the resolution of the column."""
return (times - pd.Timestamp("1970-01-01", tz="UTC")).dt.total_seconds().to_numpy(float)
def _section_name(cfg: dict) -> tuple[dict, dict]:
sizes = cfg["t1"]["hole_sizes"]
return ({float(k): str(v["section"]) for k, v in sizes.items()},
{float(k): str(v["phase"]) for k, v in sizes.items()})
def _dominant(frame: pd.DataFrame, column: str) -> pd.DataFrame:
"""Per report: the value of `column` with the most hours (ties: alphabetical) and its share of the hours."""
h = frame.groupby(["report_id", column])["duration_h"].sum().reset_index()
h = h.sort_values(["report_id", "duration_h", column], ascending=[True, False, True], kind="stable")
top = h.drop_duplicates("report_id").set_index("report_id")
total = h.groupby("report_id")["duration_h"].sum()
return pd.DataFrame({column: top[column], "share": (top["duration_h"] / total).round(4)})
def t1_reports(feat: pd.DataFrame, ops: pd.DataFrame, activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""T1 per report-day: hole section and phase (published, or filled with provenance), scope, day-level operation.
`scope`: `drilling_day` (at least one drilling-group activity), `other_day`, `no_activities`, `excluded`.
`feat` is `fill_features` (or `timeline` with a `dia` column). `filled_by` is `diaHole` (published), `ffill` or
`bfill_leading`; `fill_source_report_id` is the report the value comes from (the report itself when published),
`fill_gap_reports` and `fill_gap_days` the distance to it."""
fill = cfg["t1"]["fill"]
if fill["rule"] != "ffill" or fill["leading"] != "bfill":
raise ValueError("t1_reports implements t1.fill.rule = ffill with leading = bfill")
names, phases = _section_name(cfg)
parts = []
for _, g in feat.groupby("wellbore", sort=False):
g = g.reset_index(drop=True)
live = g["status"].ne("placeholder_date").to_numpy()
dia = g["dia"].to_numpy(float) if "dia" in g else g["diaHole"].where(live).to_numpy(float)
pos = np.arange(len(g), dtype=float)
known = ~np.isnan(dia)
src_main = pd.Series(np.where(known, pos, np.nan)).ffill().to_numpy()
src_lead = pd.Series(np.where(known, pos, np.nan)).bfill().to_numpy()
src = np.where(np.isnan(src_main), src_lead, src_main)
by = np.select([known, ~np.isnan(src_main), ~np.isnan(src_lead)], ["diaHole", "ffill", "bfill_leading"], "none")
src[~live], by[~live] = np.nan, "none"
has = ~np.isnan(src)
idx = src[has].astype(int)
section_in = np.full(len(g), np.nan)
section_in[has] = dia[idx]
pilot = np.zeros(len(g), dtype=bool)
pilot[has] = g["diaPilot"].notna().to_numpy()[idx]
source_id = np.full(len(g), None, dtype=object)
source_id[has] = g["report_id"].to_numpy()[idx]
gap_reports = np.full(len(g), np.nan)
gap_reports[has] = np.abs(pos[has] - idx)
gap_days = np.full(len(g), np.nan)
start = _seconds(g["start_utc"])
gap_days[has] = np.abs(start[has] - start[idx]) / 86400.0
out = g[["report_id", "wellbore", "well", "file_date", "start_utc", "end_utc", "status", "diaHole", "diaPilot",
"n_activities", "n_drilling_activities", "hours_activities"]].copy()
out["section_in"] = section_in
out["is_pilot"] = pilot
out["filled_by"] = by
out["fill_source_report_id"] = source_id
out["fill_gap_reports"] = gap_reports
out["fill_gap_days"] = np.round(gap_days, 3)
parts.append(out)
t = pd.concat(parts, ignore_index=True)
t["section"] = t["section_in"].map(names)
t["phase"] = t["section_in"].map(phases).mask(t["is_pilot"] & t["section_in"].notna(), cfg["t1"]["pilot_phase"])
t["section_rule"] = t["filled_by"].map({"diaHole": "T1.S1", "ffill": "T1.S2", "bfill_leading": "T1.S3"})
t["phase_rule"] = np.where(t["section_in"].isna(), None, np.where(t["is_pilot"], "T1.P2", "T1.P1"))
t["section_source"] = np.where(t["section_in"].isna(), None, "reports.diaHole,reports.diaPilot")
t["scope"] = np.select([t["status"].eq("placeholder_date"), t["status"].eq("no_activities"),
t["n_drilling_activities"] > 0], ["excluded", "no_activities", "drilling_day"], "other_day")
hours = ops[["report_id", "op_group", "op_class"]].assign(duration_h=activities["duration_h"].to_numpy())
for column, name in (("op_group", "day_op_group"), ("op_class", "day_op_class")):
top = _dominant(hours, column)
t[name] = t["report_id"].map(top[column])
t[name + "_share"] = t["report_id"].map(top["share"])
t["section_witsml"] = pd.Series(np.nan, index=t.index, dtype=float)
t["section_agree"] = pd.Series(pd.NA, index=t.index, dtype="boolean")
return t
def attach_witsml_section(t1: pd.DataFrame, witsml_sections: pd.DataFrame | None) -> pd.DataFrame:
"""Hook for a hole section derived from WITSML (labels.yaml t1.witsml_section).
`witsml_sections` has one row per (wellbore, time interval): `wellbore`, `start_utc`, `end_utc`, `section_in`.
A report-day takes the section with the longest overlap with its period; `section_agree` compares it with the
DDR section. With None the table is returned unchanged (both columns stay NULL)."""
if witsml_sections is None or witsml_sections.empty:
return t1
t = t1.copy()
best = np.full(len(t), np.nan)
day_start, day_end = _seconds(t["start_utc"]), _seconds(t["end_utc"])
for wellbore, w in witsml_sections.groupby("wellbore"):
w_start, w_end, w_size = _seconds(w["start_utc"]), _seconds(w["end_utc"]), w["section_in"].to_numpy(float)
for i in np.flatnonzero((t["wellbore"] == wellbore).to_numpy()):
overlap = np.minimum(w_end, day_end[i]) - np.maximum(w_start, day_start[i])
if len(overlap) and overlap.max() > 0:
best[i] = w_size[int(overlap.argmax())]
t["section_witsml"] = best
agree = pd.Series(best == t["section_in"].to_numpy(float), index=t.index, dtype="boolean")
t["section_agree"] = agree.mask(np.isnan(best) | t["section_in"].isna().to_numpy())
return t
def t1_activities(ops: pd.DataFrame, t1: pd.DataFrame) -> pd.DataFrame:
"""T1 per activity: its operation label and the section label of its report-day."""
day = t1[["report_id", "section_in", "section", "phase", "is_pilot", "filled_by", "section_rule", "scope"]]
return ops.merge(day, on="report_id", how="left", validate="many_to_one")
# ---------------------------------------------------------------------------------------------------------------
# T2 labels, masked inputs, text rates
# ---------------------------------------------------------------------------------------------------------------
def _snake(s: pd.Series) -> pd.Series:
return s.str.replace(r"\W+", "_", regex=True).str.strip("_")
def t2_labels(activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""T2 per activity: NPT under definitions (a) and (b), cause group with both candidate sources and the rule."""
t2 = cfg["t2"]
a = activities
out = a[["act_id", "report_id", "wellbore"]].copy()
out["well"] = out["wellbore"].map(well_of)
out["duration_h"] = a["duration_h"].to_numpy()
out["is_interruption"] = a["code_main"].eq("interruption").to_numpy()
out["is_state_fail"] = a["state"].map({k: v["npt"] for k, v in t2["state"].items()}).astype(bool).to_numpy()
out["is_detail_nonsuccess"] = a["stateDetailActivity"].ne("success").to_numpy()
out["npt_a"] = out["is_interruption"]
out["npt_b"] = out["is_interruption"] | out["is_state_fail"] | out["is_detail_nonsuccess"]
code_cause = {c: (None if r["cause"] == "detail" else r["cause"]) for c, r in cfg["codes"].items()}
detail_cause = {d: r["cause"] for d, r in t2["cause_from_detail"].items()}
from_code = np.array([code_cause[c] for c in a["proprietaryCode"]], dtype=object)
from_detail = np.array([detail_cause[d] for d in a["stateDetailActivity"]], dtype=object)
has_code = np.array([c is not None for c in from_code])
has_detail = np.array([d is not None for d in from_detail])
order = {"code": (has_code, from_code, "T2.C1"), "detail": (has_detail, from_detail, "T2.C2")}
cause = np.full(len(a), t2["default_cause"], dtype=object)
rule = np.full(len(a), "T2.C3", dtype=object)
for source in reversed([s for s in t2["precedence"] if s != "default"]):
has, values, rule_id = order[source]
cause[has], rule[has] = values[has], rule_id
npt = out["npt_b"].to_numpy()
out["cause_from_code"] = np.where(npt, from_code, None)
out["cause_from_detail"] = np.where(npt, from_detail, None)
out["cause_group"] = np.where(npt, cause, "none")
out["cause_rule"] = np.where(npt, rule, None)
fine = np.where(rule == "T2.C1", _snake(a["code_sub"]).to_numpy(object),
np.where(rule == "T2.C2", _snake(a["stateDetailActivity"]).to_numpy(object), t2["default_cause"]))
out["cause_fine"] = np.where(npt, fine, "none")
out["cause_conflict"] = npt & has_code & has_detail & (from_code != from_detail)
out["cause_a"] = np.where(out["npt_a"], out["cause_group"], "none")
out["cause_b"] = out["cause_group"]
out["wait_code_outside_interruption"] = (a["code_sub"].eq("wait") & ~a["code_main"].eq("interruption")).to_numpy()
out["npt_rule_a"], out["npt_rule_b"] = "T2.Na", "T2.Nb"
out["source_columns"] = "activities.proprietaryCode,activities.state,activities.stateDetailActivity"
return out
def t2_inputs(activities: pd.DataFrame, reports: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""The masked model-input view for T2 and T3: activity text and depth, report text and header metadata, and no
activity-code column. Raises if a column of `MASKED` would be in the view."""
t2 = cfg["t2"]
acts = activities[t2["input_activity_columns"]].rename(columns={"phase": "rig_phase"})
rep = reports[["report_id"] + t2["input_report_columns"]].rename(
columns={c: f"report_{c}" for c in ("md", "tvd", "distDrill", "diaHole", "mdDiaHoleStart", "mdCsgLast")})
view = acts.merge(rep, on="report_id", how="left", validate="many_to_one")
view.insert(3, "well", view["wellbore"].map(well_of))
leaked = sorted(set(view.columns) & set(MASKED))
if leaked:
raise ValueError(f"masked columns in the model-input view: {leaked}")
return view
def text_rates(activities: pd.DataFrame, reports: pd.DataFrame, labels: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""How often the free text names the label, for the lexicon of labels.yaml (analysis only).
One row per (target, definition, scope): scope `comment` searches activities.comments, `comment+sum24Hr` adds
the 24 h summary of the report. `recall` = share of positive rows the lexicon hits, `fpr` = share of negative
rows it hits, `precision` = positives among the hits."""
lex = {k: re.compile("|".join(f"(?:{alt})" for alt in v), re.I) for k, v in cfg["text_lexicon"].items()}
comment = activities["comments"].fillna("")
summary = activities["report_id"].map(reports.set_index("report_id")["sum24Hr"]).fillna("")
texts = {"comment": comment, "comment+sum24Hr": comment + "\n" + summary.where(summary.ne("None"), "")}
rows = []
for scope, text in texts.items():
hits = {k: np.fromiter((rx.search(s) is not None for s in text), dtype=bool, count=len(text))
for k, rx in lex.items()}
for d in NPT_DEFINITIONS:
npt = labels[f"npt_{d}"].to_numpy()
cause = labels[f"cause_{d}"].to_numpy()
for target, hit in hits.items():
pos = npt if target == "npt" else cause == target
n_pos, n_neg = int(pos.sum()), int((~pos).sum())
tp, fp = int((hit & pos).sum()), int((hit & ~pos).sum())
rows.append({"target": target, "definition": d, "scope": scope, "n_pos": n_pos, "hit_pos": tp,
"n_neg": n_neg, "hit_neg": fp,
"recall": round(tp / n_pos, 4) if n_pos else None,
"fpr": round(fp / n_neg, 4) if n_neg else None,
"precision": round(tp / (tp + fp), 4) if tp + fp else None})
return pd.DataFrame(rows)
def code_sub_literal(activities: pd.DataFrame) -> pd.DataFrame:
"""Per sub-code: the share of its rows whose comment contains the sub-code literally (case-insensitive), and
the share of all other rows that do (so "drill" in "drill pipe" is visible as a high background rate)."""
comment = activities["comments"].fillna("").str.lower()
rows = []
for sub, n in activities["code_sub"].value_counts().items():
hit = comment.str.contains(sub.lower(), regex=False).to_numpy()
own = activities["code_sub"].eq(sub).to_numpy()
rows.append({"code_sub": sub, "n": int(n), "hit": int((hit & own).sum()),
"rate": round(float((hit & own).sum() / n), 4),
"rate_other_rows": round(float((hit & ~own).sum() / max(int((~own).sum()), 1)), 4)})
return pd.DataFrame(rows)
# ---------------------------------------------------------------------------------------------------------------
# T3: depth classes, episodes, cells, intervals
# ---------------------------------------------------------------------------------------------------------------
def mudline(reports: pd.DataFrame) -> pd.Series:
"""Mud line per wellbore in m MD: median of waterDepth + elevKelly over the reports with elevKelly > 0."""
ok = reports[reports["elevKelly"] > 0]
return (ok["waterDepth"] + ok["elevKelly"]).groupby(ok["wellbore"]).median().rename("mudline_md")
def own_hole_top(reports: pd.DataFrame) -> pd.Series:
"""Top of the hole a wellbore drilled itself: the smallest mdDiaHoleStart among its reports with a diaHole."""
ok = reports[reports["diaHole"].notna() & reports["mdDiaHoleStart"].notna()]
return ok.groupby("wellbore")["mdDiaHoleStart"].min().rename("own_hole_top_md")
def t3_activities(activities: pd.DataFrame, labels: pd.DataFrame, reports: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""Per activity: depth class (T3.D1), grid cell (T3.G1, in-hole rows only), NPT flags and episode ids (T3.E1).
Rows are in time order within the wellbore."""
grid = float(cfg["t3"]["grid_m"])
t = activities[["act_id", "report_id", "wellbore", "seq", "start_utc", "end_utc", "duration_h", "md"]].copy()
t = t.merge(labels[["act_id", "well", "npt_a", "npt_b", "cause_group"]], on="act_id", validate="one_to_one")
t["mudline_md"] = t["wellbore"].map(mudline(reports))
if t["mudline_md"].isna().any():
raise ValueError("no mud line for: " + ", ".join(sorted(t.loc[t["mudline_md"].isna(), "wellbore"].unique())))
md = t["md"]
t["depth_class"] = np.select([md.isna(), md <= 0, md < t["mudline_md"]], ["missing", "zero", "above_mudline"],
"in_hole")
t["cell"] = np.floor(md / grid).where(t["depth_class"].eq("in_hole")).astype("Int64")
t = t.sort_values(["wellbore", "start_utc", "end_utc", "report_id", "seq"], kind="stable").reset_index(drop=True)
max_gap = pd.Timedelta(hours=float(cfg["t3"]["episode_max_gap_h"]))
same = t["wellbore"].eq(t["wellbore"].shift())
near = (t["start_utc"] - t["end_utc"].shift()) <= max_gap
for d in NPT_DEFINITIONS:
npt = t[f"npt_{d}"]
first = npt & ~(npt.shift(fill_value=False) & same & near)
number = first.groupby(t["wellbore"]).cumsum()
ids = t["wellbore"].map(stem) + f":{d}:E" + number.astype(str).str.zfill(4)
t[f"episode_{d}"] = ids.where(npt, None)
return t
def t3_episodes(t3a: pd.DataFrame, definition: str) -> pd.DataFrame:
"""One row per NPT episode under `definition`: time span, hours, depth span of its in-hole rows, causes, rows."""
col = f"episode_{definition}"
e = t3a[t3a[col].notna()]
hole = e["md"].where(e["depth_class"].eq("in_hole"))
g = e.assign(_md=hole).groupby(col, sort=False)
out = g.agg(wellbore=("wellbore", "first"), well=("well", "first"), n_activities=("act_id", "size"),
start_utc=("start_utc", "min"), end_utc=("end_utc", "max"), hours=("duration_h", "sum"),
n_in_hole=("_md", "count"), md_min=("_md", "min"), md_max=("_md", "max"),
causes=("cause_group", lambda s: "|".join(sorted(set(s)))),
n_reports=("report_id", "nunique"), act_ids=("act_id", list)).reset_index()
out = out.rename(columns={col: "episode_id"})
out.insert(1, "definition", definition)
out["rule"] = "T3.E1"
return out
def _cell_universe(t3a: pd.DataFrame, reports: pd.DataFrame, grid: float) -> pd.DataFrame:
hole = t3a[t3a["depth_class"].eq("in_hole")]
deepest = pd.concat([hole.groupby("wellbore")["md"].max(), reports.groupby("wellbore")["md"].max()],
axis=1).max(axis=1)
mud = mudline(reports)
frames = []
for wellbore in sorted(deepest.index):
if pd.isna(deepest[wellbore]) or deepest[wellbore] < mud[wellbore]:
continue
cells = np.arange(int(np.floor(mud[wellbore] / grid)), int(np.floor(deepest[wellbore] / grid)) + 1)
frames.append(pd.DataFrame({"wellbore": wellbore, "cell": cells}))
return pd.concat(frames, ignore_index=True)
def t3_cells(t3a: pd.DataFrame, reports: pd.DataFrame, cfg: dict) -> pd.DataFrame:
"""One row per (wellbore, cell) from the mud line to the deepest depth of the wellbore: exposure (all in-hole
activities in the cell), NPT counts, hours, label, first NPT time, causes and source rows under (a) and (b)."""
grid = float(cfg["t3"]["grid_m"])
cells = _cell_universe(t3a, reports, grid)
cells["well"] = cells["wellbore"].map(well_of)
cells["md_top"] = cells["cell"] * grid
cells["md_bottom"] = (cells["cell"] + 1) * grid
top = cells["wellbore"].map(own_hole_top(reports)).fillna(cells["wellbore"].map(mudline(reports)))
cells["own_hole_top_md"] = top
cells["in_own_hole"] = cells["md_bottom"] > top
hole = t3a[t3a["depth_class"].eq("in_hole")].assign(cell=lambda d: d["cell"].astype(int))
keys = ["wellbore", "cell"]
exposure = hole.groupby(keys).agg(n_activities=("act_id", "size"), hours=("duration_h", "sum")).reset_index()
cells = cells.merge(exposure, on=keys, how="left")
for d in NPT_DEFINITIONS:
npt = hole[hole[f"npt_{d}"]]
agg = npt.groupby(keys).agg(**{
f"n_npt_{d}": ("act_id", "size"), f"hours_npt_{d}": ("duration_h", "sum"),
f"first_npt_start_{d}": ("start_utc", "min"),
f"causes_{d}": ("cause_group", lambda s: "|".join(sorted(set(s)))),
f"act_ids_{d}": ("act_id", list)}).reset_index()
cells = cells.merge(agg, on=keys, how="left")
cells[f"label_{d}"] = cells[f"n_npt_{d}"].notna()
for c in ["n_activities"] + [f"n_npt_{d}" for d in NPT_DEFINITIONS]:
cells[c] = cells[c].fillna(0).astype(int)
for c in ["hours"] + [f"hours_npt_{d}" for d in NPT_DEFINITIONS]:
cells[c] = cells[c].fillna(0.0)
cells["rule"] = "T3.D1,T3.G1"
cells["source_columns"] = "activities.md,reports.waterDepth,reports.elevKelly"
return cells.sort_values(keys, kind="stable").reset_index(drop=True)
def t3_intervals(cells: pd.DataFrame, t3a: pd.DataFrame, definition: str, cfg: dict,
merge_gap_cells: int | None = None) -> pd.DataFrame:
"""Trouble intervals under `definition` (T3.M1): runs of positive cells of one wellbore with at most
`merge_gap_cells` negative cells between two positive ones, as [md_top, md_bottom) with the NPT rows inside."""
grid = float(cfg["t3"]["grid_m"])
gap = cfg["t3"]["merge_gap_cells"] if merge_gap_cells is None else merge_gap_cells
pos = cells.loc[cells[f"label_{definition}"], ["wellbore", "well", "cell"]].sort_values(["wellbore", "cell"])
new = pos["wellbore"].ne(pos["wellbore"].shift()) | (pos["cell"].diff() > gap + 1)
pos = pos.assign(number=new.groupby(pos["wellbore"]).cumsum())
pos["interval_id"] = pos["wellbore"].map(stem) + f":{definition}:I" + pos["number"].astype(str).str.zfill(3)
out = pos.groupby("interval_id", sort=False).agg(
wellbore=("wellbore", "first"), well=("well", "first"), cell_first=("cell", "min"), cell_last=("cell", "max"),
n_positive_cells=("cell", "size")).reset_index()
out.insert(1, "definition", definition)
out["md_top"] = out["cell_first"] * grid
out["md_bottom"] = (out["cell_last"] + 1) * grid
out["length_m"] = out["md_bottom"] - out["md_top"]
npt = t3a[t3a[f"npt_{definition}"] & t3a["depth_class"].eq("in_hole")].assign(cell=lambda d: d["cell"].astype(int))
npt = npt.merge(pos[["wellbore", "cell", "interval_id"]], on=["wellbore", "cell"], validate="many_to_one")
agg = npt.groupby("interval_id").agg(
n_activities=("act_id", "size"), hours=("duration_h", "sum"), first_start_utc=("start_utc", "min"),
last_end_utc=("end_utc", "max"), causes=("cause_group", lambda s: "|".join(sorted(set(s)))),
n_episodes=(f"episode_{definition}", "nunique"), act_ids=("act_id", list)).reset_index()
out = out.merge(agg, on="interval_id", validate="one_to_one")
out["merge_gap_cells"] = gap
out["rule"] = "T3.M1"
return out
def attach_intervals(cells: pd.DataFrame, intervals: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Add `interval_id_a` / `interval_id_b` to the cell table (NULL outside an interval)."""
out = cells.copy()
for d, iv in intervals.items():
ids = np.full(len(out), None, dtype=object)
index = {w: g for w, g in out.groupby("wellbore").indices.items()}
cell = out["cell"].to_numpy()
for row in iv.itertuples():
rows = index[row.wellbore]
inside = rows[(cell[rows] >= row.cell_first) & (cell[rows] <= row.cell_last)]
ids[inside] = row.interval_id
out[f"interval_id_{d}"] = ids
return out
# ---------------------------------------------------------------------------------------------------------------
# Analysis for the protocol
# ---------------------------------------------------------------------------------------------------------------
def class_coverage(frame: pd.DataFrame, column: str, rare: int = 20) -> pd.DataFrame:
"""Per class of `column`: instances, number of wellbores and wells that contain it, the largest share held by
one wellbore and by one well, and the flags `rare` (fewer than `rare` instances), `single_wellbore` and
`single_well` (a class in one group can never be in both the training and the test side of a grouped split)."""
f = frame[frame[column].notna()]
rows = []
for value, g in f.groupby(column, sort=True):
by_wellbore, by_well = g["wellbore"].value_counts(), g["well"].value_counts()
rows.append({"label": column, "class": str(value), "n": len(g),
"n_wellbores": len(by_wellbore), "n_wells": len(by_well),
"top_wellbore": by_wellbore.index[0], "top_wellbore_share": round(by_wellbore.iloc[0] / len(g), 4),
"top_well": by_well.index[0], "top_well_share": round(by_well.iloc[0] / len(g), 4),
"rare": len(g) < rare, "single_wellbore": len(by_wellbore) == 1, "single_well": len(by_well) == 1})
return pd.DataFrame(rows)
def distribution(frame: pd.DataFrame, column: str, by: str) -> dict:
"""{group: {class: n}} of `column` per value of `by` (wellbore or well)."""
f = frame[frame[column].notna()]
table = f.groupby([by, column]).size()
return {str(g): {str(k): int(v) for k, v in table[g].items()} for g in table.index.get_level_values(0).unique()}

281
volve_dia/ocr_hub.py Normal file
View File

@@ -0,0 +1,281 @@
"""Import an OCR of the Volve PDF pages that was run outside this repository and exported from the internal Dataset
Hub as one COCO file (`configs/ocr_hub.yaml`).
The export holds one PNG per distinct page image and, per image, chandra's blocks: category (= chandra's own label),
pixel box ``[x, y, w, h]``, inner HTML (`text`) and `attributes.reading_order`. It does not say which PDF and page an
image is: images are named by the sha256 of the PNG, identical PNGs are stored once (a blank page, or a second page
that holds the same rows in two reports), and the renderer is not PyMuPDF, so no pixel or hash matches ours.
Each PDF page is therefore matched to an image by content, in two stages:
1. text: the PDF text layer and the OCR text are split into tokens (dates and depths kept whole), every image is
scored by a hashed TF-IDF cosine, and the best `prefilter` images are re-scored by an idf-weighted token F1. The
best `top_k` are the candidates. A page with no text layer gets the images with no text as candidates;
2. image: the page is rendered at `thumb_dpi` in grey and correlated with each candidate image shrunk by
2**`thumb_shrink`. A candidate shows the page if the correlation reaches `min_corr`; among those within `tie_eps`
of the best correlation the highest text F1 wins (`select`), because two reports that differ only in a date
correlate equally. A DDR page with no such candidate (short pages whose OCR text differs from the text layer) is
searched by image against every image of the export (coarse correlation, best `fallback_top_k` re-scored) and
is `missing` if that fails too.
A check that does not take part in the choice: every ISO date of the page's text layer (the period of page 1) must
occur in the chosen OCR text.
The winner is written in chandra's page format (``<div data-bbox="x0 y0 x1 y1" data-label="...">``, box normalised
to 0-1000) to ``outputs/ocr/hub/pages/<doc sha256[:16]>/pNNNN.json`` with its provenance and match scores, so the
blocks parse with `ocr.html_blocks` exactly as a page read through the service. Hub pages are kept apart from the
service cache because the prompt, renderer and settings that produced them are not recorded in the export.
"""
from __future__ import annotations
import collections
import hashlib
import json
import re
import zlib
from dataclasses import dataclass
from html import unescape
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from . import ocr
from .paths import REPO_ROOT, outputs_dir
CONFIG = REPO_ROOT / "configs" / "ocr_hub.yaml"
_TAG = re.compile(r"<[^>]+>")
_TOKEN = re.compile(r"[A-Za-z0-9]+(?:[-:./][A-Za-z0-9]+)*")
_DATE = re.compile(r"\b(?:19|20)\d\d-[01]\d-[0-3]\d\b")
_DIM = 1 << 14
@dataclass(frozen=True)
class HubConfig:
dir: Path
prefilter: int
top_k: int
thumb_dpi: int
thumb_shrink: int
min_corr: float
tie_eps: float
fallback_top_k: int
min_text_f1: float
f1_min_tokens: int
def load_config(path: Path = CONFIG) -> HubConfig:
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
raw["dir"] = REPO_ROOT / raw["dir"]
return HubConfig(**raw)
# --------------------------------------------------------------------------- the export
@dataclass
class Export:
file: Path # the COCO json
sha256: str
images: dict[int, dict] # id -> {file_name, width, height}
blocks: dict[int, list[dict]] # image id -> annotations in reading order
categories: dict[int, str]
orphans: list[str] # PNG files with no image record
def load_export(hub_dir: Path) -> Export:
files = sorted((hub_dir / "annotations").rglob("*.json"))
if len(files) != 1:
raise FileNotFoundError(f"expected one COCO json under {hub_dir / 'annotations'}, found {len(files)}")
data = json.loads(files[0].read_text(encoding="utf-8"))
cats = {c["id"]: c["name"] for c in data["categories"]}
images = {im["id"]: im for im in data["images"]}
blocks: dict[int, list[dict]] = collections.defaultdict(list)
for a in data["annotations"]:
blocks[a["image_id"]].append(a)
for v in blocks.values():
v.sort(key=lambda a: ((a.get("attributes") or {}).get("reading_order", 0), a["id"]))
named = {im["file_name"] for im in images.values()}
orphans = sorted(f"images/{p.name}" for p in (hub_dir / "images").glob("*.png") if f"images/{p.name}" not in named)
return Export(files[0], ocr.sha256_file(files[0]), images, dict(blocks), cats, orphans)
def page_content(anns: list[dict], cats: dict[int, str], width: float, height: float) -> str:
"""chandra's page answer for the blocks of one image: one ``<div>`` per block, box normalised to 0-1000."""
out = []
for a in anns:
x, y, w, h = a["bbox"]
box = " ".join(str(round(v)) for v in (1000 * x / width, 1000 * y / height,
1000 * (x + w) / width, 1000 * (y + h) / height))
out.append(f'<div data-bbox="{box}" data-label="{cats[a["category_id"]]}">\n{a.get("text") or ""}\n</div>')
return "\n".join(out)
# --------------------------------------------------------------------------- text stage
def tokens(text: str) -> list[str]:
return _TOKEN.findall(unescape(_TAG.sub(" ", text)).lower())
def iso_dates(text: str) -> set[str]:
return set(_DATE.findall(text))
def _hashed_tfidf(docs: list[list[str]], idf: np.ndarray) -> np.ndarray:
m = np.zeros((len(docs), _DIM), np.float32)
for i, toks in enumerate(docs):
for h, n in collections.Counter(zlib.crc32(t.encode()) % _DIM for t in toks).items():
m[i, h] = (1 + np.log(n)) * idf[h]
norm = np.linalg.norm(m, axis=1)
norm[norm == 0] = 1
return m / norm[:, None]
class TextIndex:
"""Token statistics of the pages (document frequencies) and the images, for the text stage."""
def __init__(self, page_toks: list[list[str]], image_toks: list[list[str]]):
n = self.n = len(page_toks)
df_hash = collections.Counter()
self.df_tok = collections.Counter()
for toks in page_toks:
df_hash.update({zlib.crc32(t.encode()) % _DIM for t in toks})
self.df_tok.update(set(toks))
idf = np.full(_DIM, np.log(n + 1) + 1, np.float32)
for h, c in df_hash.items():
idf[h] = np.log((n + 1) / (c + 1)) + 1
self.sim = _hashed_tfidf(page_toks, idf) @ _hashed_tfidf(image_toks, idf).T
self.page_counts = [collections.Counter(t) for t in page_toks]
self.img_counts = [collections.Counter(t) for t in image_toks]
self.page_weight = [self._weight(c) for c in self.page_counts]
self.img_weight = [self._weight(c) for c in self.img_counts]
self.empty = [i for i, t in enumerate(image_toks) if not t]
def _weight(self, c: collections.Counter) -> float:
return sum(k * (np.log((self.n + 1) / (self.df_tok.get(t, 0) + 1)) + 1) for t, k in c.items())
def f1(self, j: int, i: int) -> float:
"""idf-weighted token-multiset F1 of page j and image i (1 if both have no text)."""
den = self.page_weight[j] + self.img_weight[i]
return 2 * self._weight(self.page_counts[j] & self.img_counts[i]) / den if den else 1.0
def candidates(self, j: int, prefilter: int, top_k: int) -> list[tuple[int, float]]:
if not self.page_counts[j]:
return [(i, 1.0) for i in self.empty][:top_k]
scored = [(int(i), self.f1(j, int(i))) for i in np.argsort(-self.sim[j])[:prefilter]]
scored.sort(key=lambda s: -s[1])
return scored[:top_k]
def text_candidates(page_toks: list[list[str]], image_toks: list[list[str]], prefilter: int,
top_k: int) -> list[list[tuple[int, float]]]:
"""For every page, up to `top_k` (image index, idf-weighted token F1), best first."""
ix = TextIndex(page_toks, image_toks)
return [ix.candidates(j, prefilter, top_k) for j in range(len(page_toks))]
def select(scored: list[tuple[float, float, int]], min_corr: float, tie_eps: float,
min_f1: float = 0.0) -> tuple[float, float, int] | None:
"""Pick the image of a page from its candidates (corr, text F1, image index).
The image correlation decides whether a candidate shows the page at all; it cannot tell apart two reports that
differ only in a date or a number (their thumbnails correlate equally). So among the candidates that reach
`min_corr` and `min_f1` and lie within `tie_eps` of the best correlation, the one with the highest text F1 wins
(then the higher correlation). `min_f1` keeps a page with a text layer from taking the image of another report
with the same layout (a first page of another day). None if no candidate passes."""
ok = [s for s in scored if s[0] >= min_corr and s[1] >= min_f1]
if not ok:
return None
top = max(s[0] for s in ok)
return max((s for s in ok if s[0] >= top - tie_eps), key=lambda s: (s[1], s[0]))
# --------------------------------------------------------------------------- image stage
def _grey(pix) -> np.ndarray:
import pymupdf
if pix.n != 1 or pix.alpha:
pix = pymupdf.Pixmap(pymupdf.csGRAY, pix)
return np.frombuffer(pix.samples, np.uint8).reshape(pix.h, pix.stride)[:, : pix.w].copy()
def image_thumb(path: Path, shrink: int) -> np.ndarray:
import pymupdf
pix = pymupdf.Pixmap(str(path))
if pix.alpha:
pix = pymupdf.Pixmap(pix, 0)
pix.shrink(shrink)
return _grey(pix)
def page_thumb(doc, page: int, dpi: int) -> np.ndarray:
import pymupdf
return _grey(doc[page - 1].get_pixmap(dpi=dpi, colorspace=pymupdf.csGRAY))
COARSE = (146, 103) # a 50 dpi A4 page, or a 1653 x 2339 image shrunk by 4, averaged over 4 x 4 blocks
def coarse(a: np.ndarray, f: int = 4) -> np.ndarray:
"""A thumbnail averaged over f x f blocks into the fixed shape COARSE (cropped or padded with white), flattened,
centred and scaled to unit norm, so that a dot product of two is their correlation."""
h, w = COARSE[0] * f, COARSE[1] * f
b = np.full((h, w), 255, np.float32)
b[: min(h, a.shape[0]), : min(w, a.shape[1])] = a[:h, :w]
v = b.reshape(COARSE[0], f, COARSE[1], f).mean(axis=(1, 3)).ravel()
v -= v.mean()
n = float(np.linalg.norm(v))
return v / n if n > 0 else v
def correlation(a: np.ndarray, b: np.ndarray) -> float:
"""Pearson correlation of two grey thumbnails over their common top-left area (sizes differ by a pixel)."""
h, w = min(a.shape[0], b.shape[0]), min(a.shape[1], b.shape[1])
x = a[:h, :w].astype(np.float32).ravel()
y = b[:h, :w].astype(np.float32).ravel()
x -= x.mean()
y -= y.mean()
den = float(np.sqrt((x @ x) * (y @ y)))
return float(x @ y / den) if den > 0 else float(np.array_equal(a[:h, :w], b[:h, :w]))
# --------------------------------------------------------------------------- page records
def cache_dir() -> Path:
return outputs_dir() / "ocr" / "hub" / "pages"
def page_file(doc_sha256: str, page: int) -> Path:
return cache_dir() / doc_sha256[:16] / f"p{page:04d}.json"
def write_page(rec: dict) -> None:
f = page_file(rec["doc_sha256"], rec["page"])
f.parent.mkdir(parents=True, exist_ok=True)
tmp = f.with_suffix(".tmp")
tmp.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(f)
def load_blocks(doc_sha256: str, n_pages: int) -> tuple[list[ocr.Block], list[dict]]:
"""Blocks of a document from the hub import, in page and reading order, like `ocr.load_blocks`."""
blocks: list[ocr.Block] = []
records = []
for page in range(1, n_pages + 1):
f = page_file(doc_sha256, page)
if not f.is_file():
records.append({"page": page, "status": "missing"})
continue
rec = json.loads(f.read_text(encoding="utf-8"))
records.append({k: v for k, v in rec.items() if k != "content"})
if rec["status"] == "ok":
blocks += ocr.html_blocks(rec["content"], page)
return blocks, records
def content_sha256(content: str) -> str:
return hashlib.sha256(content.encode("utf-8")).hexdigest()

View File

@@ -55,3 +55,8 @@ def outputs_dir() -> Path:
p = Path(env) if env else REPO_ROOT / "outputs"
p.mkdir(parents=True, exist_ok=True)
return p
def well_picks_file() -> Path:
"""Formation tops of the Volve wells (409 picks, 35 wellbores), fixed-width text."""
return volve_root() / "Geophysical_Interpretations" / "Wells" / "Well_picks_Volve_v1.dat"

791
volve_dia/t4.py Normal file
View File

@@ -0,0 +1,791 @@
"""T4: evidence-grounded question answering over the Volve daily drilling reports (DDR).
Source of every answer: the DDR tables that `scripts/02_parse_ddr.py` builds from the DDR XML files
(`outputs/ddr/volve_ddr.duckdb`). Nothing is taken from the HTML or PDF renders, and no language model is involved.
Rules (plan §4.3, AGENTS.md):
* a question is a deterministic template (`configs/t4_templates.yaml`) filled with slot values that a SQL query
enumerates from the data;
* the gold answer is the result of the template's answer SQL, and the evidence is the set of rows (table, report_id,
seq) that the template's evidence SQL returns. Both queries are stored with the question, with the slot values
written in as literals, so each can be re-run as is;
* an instance is dropped, and counted with its reason, when the answer is missing, ambiguous (several published
values, a tie) or flagged by the template itself (`drop_reason` column of the answer SQL). A template with
`on_null: not_reported` keeps instances without an answer as unanswerable questions (gold answer "not reported");
* trouble and NPT questions are phrased on the published codes (`proprietaryCode`, `stateDetailActivity`), never on
the NPT definition of T2, which is not locked yet;
* each question carries its wellbore(s) and well(s), the groups of the evaluation split.
Evidence modes. `all`: every row is needed (sums, counts). `any`: every row states the answer by itself (a header
value repeated in each report). `group`: the rows fall into groups and one row per group is enough (a list answer:
one group per element). Citation recall is the share of groups with at least one cited row; citation precision is
the share of cited rows that are evidence rows.
`score(prediction, gold)` compares a predicted answer with the gold answer by answer type, within the tolerance of
the template, and computes citation precision and recall. An independent pandas implementation of every template is
in `volve_dia/t4_pandas.py`; `scripts/08_t4_questions.py` compares the two on every candidate instance.
"""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import math
import re
import unicodedata
from dataclasses import dataclass, field
from fractions import Fraction
from pathlib import Path
from typing import Any
import yaml
from .names import canonical, well_of
NOT_REPORTED = "not reported"
ANSWER_TYPES = ("number", "date", "string", "enumeration", "boolean", "list")
EVIDENCE_MODES = ("all", "any", "group")
SLOT_TYPES = ("wellbore", "inch", "number", "date", "string")
FAMILIES = ("lookup", "aggregation", "temporal_event", "comparison", "multi_hop")
SCOPES = ("single", "pair", "field")
#: Reasons the engine itself assigns; a template may add its own through the `drop_reason` column.
DROP_NULL, DROP_DUPLICATE, DROP_NO_EVIDENCE = "null_answer", "duplicate", "no_evidence"
_PARAM = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)")
_FIELD = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")
# ----------------------------------------------------------------------------------------------------------------------
# Templates
# ----------------------------------------------------------------------------------------------------------------------
class TemplateError(ValueError):
"""A template of the configuration is malformed, or its SQL returned something the rules do not allow."""
def load_config(path: Path | str) -> dict:
"""Read and validate `configs/t4_templates.yaml`. Returns the configuration with only the enabled templates in
`templates`; disabled ones (the WITSML and formation-tops proposals) are kept in `disabled`."""
cfg = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
templates = cfg.get("templates") or []
ids = [t.get("id") for t in templates]
if len(set(ids)) != len(ids):
raise TemplateError(f"duplicate template ids: {sorted(i for i in set(ids) if ids.count(i) > 1)}")
for t in templates:
validate_template(t)
cfg["disabled"] = [t for t in templates if not t.get("enabled", True)] + list(cfg.get("planned") or [])
cfg["templates"] = [t for t in templates if t.get("enabled", True)]
return cfg
def validate_template(t: dict) -> None:
tid = t.get("id", "?")
def need(cond: bool, msg: str) -> None:
if not cond:
raise TemplateError(f"template {tid}: {msg}")
for key in ("id", "family", "tadi", "questions", "slots", "slots_sql", "answer_sql", "evidence_sql",
"evidence_mode", "answer", "source"):
need(key in t, f"missing key {key!r}")
need(t["family"] in FAMILIES, f"unknown family {t['family']!r}")
need(t.get("scope", "single") in SCOPES, f"unknown scope {t.get('scope')!r}")
need(t["evidence_mode"] in EVIDENCE_MODES, f"unknown evidence_mode {t['evidence_mode']!r}")
need(t.get("on_null", "drop") in ("drop", "not_reported"), "on_null must be drop or not_reported")
need(isinstance(t["questions"], list) and t["questions"], "questions must be a non-empty list")
answer = t["answer"]
need(answer.get("type") in ANSWER_TYPES, f"unknown answer type {answer.get('type')!r}")
if answer["type"] == "list":
need(answer.get("item_type") in ("number", "string"), "a list answer needs item_type number or string")
if answer["type"] == "number" or answer.get("item_type") == "number":
tol = answer.get("tolerance") or {}
need("unit" in answer, "a numeric answer needs a unit (null for a pure count is not allowed: name what "
"is counted)")
need("abs" in tol or "rel" in tol, "a numeric answer needs tolerance.abs and/or tolerance.rel")
slots = t["slots"]
for name, spec in slots.items():
need(spec.get("type") in SLOT_TYPES, f"slot {name}: unknown type {spec.get('type')!r}")
if t.get("scope", "single") != "field":
need(any(s["type"] == "wellbore" for s in slots.values()), "a single or pair template needs a wellbore slot")
for pattern in t["questions"]:
unknown = set(_FIELD.findall(pattern)) - set(slots)
need(not unknown, f"question uses undeclared slots {sorted(unknown)}")
for key in ("answer_sql", "evidence_sql"):
unknown = set(_PARAM.findall(t[key])) - set(slots)
need(not unknown, f"{key} uses undeclared parameters {sorted(unknown)}")
for spec_key in ("sample", "negatives"):
if spec_key in t:
cap = t[spec_key]
need(isinstance(cap.get("n"), int) and cap["n"] > 0, f"{spec_key}.n must be a positive int")
need(set(cap.get("by", [])) <= set(slots) | {"answer"}, f"{spec_key}.by must name slots or 'answer'")
need("negatives" not in t or t.get("on_null") == "not_reported", "negatives needs on_null: not_reported")
# ----------------------------------------------------------------------------------------------------------------------
# Rendering
# ----------------------------------------------------------------------------------------------------------------------
def sql_literal(value: Any) -> str:
if value is None:
return "NULL"
if isinstance(value, bool):
return "TRUE" if value else "FALSE"
if isinstance(value, (int, float)):
if isinstance(value, float) and not math.isfinite(value):
raise TemplateError(f"not a finite number: {value!r}")
return repr(value)
return "'" + str(value).replace("'", "''") + "'"
def render_sql(sql: str, slots: dict) -> str:
"""The SQL with every `$slot` replaced by the literal of its value: what is executed and what is stored."""
return _PARAM.sub(lambda m: sql_literal(slots[m.group(1)]), sql).strip()
def format_number(x: float, decimals: int | None = None) -> str:
"""'3520' for 3520.0, '1.48' for 1.48: how a number is written in a question or an answer text."""
if decimals is not None:
x = round(x, decimals)
return str(int(x)) if float(x).is_integer() else repr(float(x))
def format_inch(x: float) -> str:
"""Hole, bit and casing sizes as the reports write them, with the decimal value: 12.25 -> '12 1/4" (12.25 in)'."""
frac = Fraction(x).limit_denominator(16)
if abs(float(frac) - x) > 1e-9:
return f"{format_number(x)} in"
whole, rest = divmod(frac, 1)
if rest == 0:
return f'{whole}"'
return f'{whole} {rest.numerator}/{rest.denominator}" ({format_number(x)} in)'
def display(slot_type: str, value: Any) -> str:
if slot_type == "inch":
return format_inch(float(value))
if slot_type == "number":
return format_number(float(value))
return str(value)
def render_question(pattern: str, slot_specs: dict, slots: dict) -> str:
return pattern.format(**{k: display(slot_specs[k]["type"], v) for k, v in slots.items()})
def evidence_id(table: str, report_id: str, seq: int | None = None) -> str:
"""'activities:15_9_F_4_2008_02_19:10', 'reports:15_9_F_4_2008_02_19' (a report row has no sequence number)."""
return f"{table}:{report_id}" if seq is None else f"{table}:{report_id}:{int(seq)}"
def slot_key(template_id: str, slots: dict) -> str:
return template_id + "|" + json.dumps(slots, sort_keys=True, ensure_ascii=False)
def _rank(seed: int, key: str) -> str:
return hashlib.sha256(f"{seed}|{key}".encode()).hexdigest()
# ----------------------------------------------------------------------------------------------------------------------
# Instantiation
# ----------------------------------------------------------------------------------------------------------------------
@dataclass
class Outcome:
"""What one candidate instance (one row of the slot enumeration) of a template came to."""
template_id: str
slots: dict
status: str # "ok", "not_reported" or "drop"
reason: str | None = None # the drop reason
answer: Any = None
evidence: list[dict] = field(default_factory=list) # {"table", "report_id", "seq", "group"}
sql: str = ""
evidence_sql: str = ""
@property
def key(self) -> str:
return slot_key(self.template_id, self.slots)
def evidence_partition(self) -> frozenset[frozenset[str]]:
"""The evidence as a set of groups of row ids: the form in which two implementations are compared."""
groups: dict[int, set[str]] = {}
for e in self.evidence:
groups.setdefault(e["group"], set()).add(evidence_id(e["table"], e["report_id"], e["seq"]))
return frozenset(frozenset(g) for g in groups.values())
def _py(value: Any) -> Any:
"""DuckDB and numpy scalars as plain Python values (None for NULL and NaN)."""
if value is None:
return None
if hasattr(value, "item"):
value = value.item()
if isinstance(value, float) and math.isnan(value):
return None
if isinstance(value, (dt.datetime, dt.date)):
return value.isoformat()[:10]
return value
def coerce_answer(spec: dict, values: list[Any]) -> Any:
"""The answer SQL's `answer` column as the gold answer of the template's type."""
kind = spec["type"]
def one(v: Any, item_kind: str) -> Any:
if item_kind == "number":
v = float(v)
return round(v, spec["round"]) if "round" in spec else v
if item_kind == "boolean":
return bool(v)
return str(v)
if kind == "list":
return [one(v, spec["item_type"]) for v in values]
return one(values[0], kind if kind in ("number", "boolean") else "string")
def group_evidence(mode: str, rows: list[dict]) -> list[dict]:
"""Evidence rows with their group number: one group per row (`all`), one group (`any`) or the `grp` column."""
rows = sorted(rows, key=lambda r: (r["table"], r["report_id"], -1 if r["seq"] is None else r["seq"]))
seen, out = set(), []
labels: dict[Any, int] = {}
for r in rows:
rid = evidence_id(r["table"], r["report_id"], r["seq"])
if (rid, r.get("grp")) in seen:
continue
seen.add((rid, r.get("grp")))
if mode == "all":
group = len(out)
elif mode == "any":
group = 0
else:
group = labels.setdefault(r["grp"], len(labels))
out.append({"table": r["table"], "report_id": r["report_id"], "seq": r["seq"], "group": group})
return out
def _rows(con, sql: str) -> list[dict]:
cur = con.execute(sql)
cols = [d[0] for d in cur.description]
return [dict(zip(cols, (_py(v) for v in row))) for row in cur.fetchall()]
def run_instance(con, tpl: dict, slots: dict) -> Outcome:
"""Run the answer SQL and the evidence SQL of one candidate instance and apply the drop rules."""
spec = tpl["answer"]
sql, ev_sql = render_sql(tpl["answer_sql"], slots), render_sql(tpl["evidence_sql"], slots)
out = Outcome(tpl["id"], slots, "drop", sql=sql, evidence_sql=ev_sql)
rows = _rows(con, sql)
if rows and "answer" not in rows[0]:
raise TemplateError(f"template {tpl['id']}: the answer SQL has no `answer` column")
reasons = [r["drop_reason"] for r in rows if r.get("drop_reason")]
if reasons:
out.reason = reasons[0]
return out
values = [r["answer"] for r in rows if r["answer"] is not None]
if spec["type"] != "list" and len(rows) > 1:
raise TemplateError(f"template {tpl['id']}: {len(rows)} answer rows for {slots} (a scalar answer needs one)")
if not values:
if tpl.get("on_null", "drop") == "not_reported":
out.status, out.answer = "not_reported", NOT_REPORTED
else:
out.reason = DROP_NULL
return out
out.answer = coerce_answer(spec, values)
ev_rows = _rows(con, ev_sql)
for r in ev_rows:
r.setdefault("seq", None)
if tpl["evidence_mode"] == "group" and "grp" not in r:
raise TemplateError(f"template {tpl['id']}: evidence_mode group needs a `grp` column")
out.evidence = group_evidence(tpl["evidence_mode"], ev_rows)
if not out.evidence and not (spec["type"] == "boolean" and out.answer is False):
out.reason = DROP_NO_EVIDENCE # an answer that no row supports is not a benchmark item
return out
out.status = "ok"
return out
def run_template(con, tpl: dict) -> list[Outcome]:
"""Every candidate instance of a template, in the order of its slot enumeration."""
slot_names = list(tpl["slots"])
cur = con.execute(tpl["slots_sql"])
cols = [d[0] for d in cur.description]
if cols != slot_names:
raise TemplateError(f"template {tpl['id']}: slots_sql returns {cols}, the template declares {slot_names}")
outcomes, seen = [], set()
for row in cur.fetchall():
slots = dict(zip(cols, (_py(v) for v in row)))
if any(v is None for v in slots.values()):
raise TemplateError(f"template {tpl['id']}: NULL slot value in {slots}")
o = run_instance(con, tpl, slots)
if o.key in seen:
o.status, o.reason = "drop", DROP_DUPLICATE
seen.add(o.key)
outcomes.append(o)
return outcomes
def _sample(outcomes: list[Outcome], spec: dict | None, seed: int) -> tuple[list[Outcome], int]:
"""At most `n` outcomes per group of `by` (slot names or 'answer'), chosen by a seeded hash of the instance key,
so the choice does not depend on the order of the enumeration."""
if not spec:
return outcomes, 0
groups: dict[tuple, list[Outcome]] = {}
for o in outcomes:
key = tuple(json.dumps(o.answer if b == "answer" else o.slots[b], sort_keys=True) for b in spec.get("by", []))
groups.setdefault(key, []).append(o)
kept = [o for g in groups.values() for o in sorted(g, key=lambda o: _rank(seed, o.key))[:spec["n"]]]
return kept, len(outcomes) - len(kept)
def select(tpl: dict, outcomes: list[Outcome], seed: int) -> tuple[list[Outcome], dict]:
"""The instances that become questions: answerable ones (capped by `sample`) and, for `on_null: not_reported`,
unanswerable ones (capped by `negatives`)."""
ok, n_ok = _sample([o for o in outcomes if o.status == "ok"], tpl.get("sample"), seed)
neg, n_neg = _sample([o for o in outcomes if o.status == "not_reported"], tpl.get("negatives"), seed)
return ok + neg, {"answerable": n_ok, "unanswerable": n_neg}
def _choices(con, tpl: dict, slots: dict) -> list[str] | None:
spec = tpl["answer"].get("choices")
if not spec:
return None
if "slots" in spec:
return [str(slots[s]) for s in spec["slots"]]
if "_choices" not in tpl:
tpl["_choices"] = [str(r[0]) for r in con.execute(spec["sql"]).fetchall()]
return tpl["_choices"]
def answer_text(spec: dict, answer: Any) -> str:
"""The gold answer as a reader would write it: '3520 m', '2007-08-26', '36, 26, 17.5 in', 'yes'."""
unit = f" {spec['unit']}" if spec.get("unit") else ""
if answer == NOT_REPORTED:
return NOT_REPORTED
if spec["type"] == "number":
return format_number(answer) + unit
if spec["type"] == "boolean":
return "yes" if answer else "no"
if spec["type"] == "list":
items = [format_number(v) if spec["item_type"] == "number" else str(v) for v in answer]
return ", ".join(items) + unit
return str(answer)
def make_question(con, tpl: dict, o: Outcome, all_wellbores: list[str], seed: int) -> dict:
spec, tol = tpl["answer"], tpl["answer"].get("tolerance") or {}
scope = tpl.get("scope", "single")
if scope == "field":
wellbores = list(all_wellbores)
else:
wellbores = [canonical(o.slots[k]) for k, s in tpl["slots"].items() if s["type"] == "wellbore"]
wells = sorted({well_of(w) for w in wellbores})
pattern_index = int(_rank(seed, "pattern|" + o.key), 16) % len(tpl["questions"])
digest = hashlib.sha256(o.key.encode()).hexdigest()[:10]
return {
"id": f"T4-{tpl['id']}-{digest}",
"template_id": tpl["id"],
"family": tpl["family"],
"tadi_category": tpl["tadi"].get("category"),
"tadi_subcategory": tpl["tadi"].get("subcategory"),
"scope": scope,
"wellbore": None if scope == "field" else wellbores[0],
"well": None if scope == "field" else well_of(wellbores[0]),
"wellbores": wellbores,
"wells": wells,
"question": render_question(tpl["questions"][pattern_index], tpl["slots"], o.slots),
"pattern_index": pattern_index,
"slots": o.slots,
"answer": o.answer,
"answer_text": answer_text(spec, o.answer),
"answer_type": spec["type"],
"item_type": spec.get("item_type"),
"unit": spec.get("unit"),
"tolerance_abs": tol.get("abs"),
"tolerance_rel": tol.get("rel"),
"tolerance_days": tol.get("days", 0) if spec["type"] == "date" else None,
"choices": _choices(con, tpl, o.slots),
"answerable": o.status == "ok",
"sql": o.sql,
"evidence_sql": o.evidence_sql,
"evidence": o.evidence,
"evidence_mode": tpl["evidence_mode"],
"printed_in_render": bool((tpl.get("render") or {}).get("printed", True)),
"n_evidence": len(o.evidence),
"n_evidence_groups": len({e["group"] for e in o.evidence}),
"source": list(tpl["source"]),
"caveats": list(tpl.get("caveats") or []),
}
def build(con, cfg: dict) -> tuple[list[dict], dict[str, list[Outcome]], dict]:
"""All questions, the outcome of every candidate instance per template (for the cross-check) and the summary."""
seed = int(cfg.get("seed", 0))
all_wellbores = [r[0] for r in con.execute("SELECT DISTINCT wellbore FROM reports ORDER BY 1").fetchall()]
questions, outcomes, per_template = [], {}, {}
texts: dict[str, str] = {}
for tpl in cfg["templates"]:
outs = run_template(con, tpl)
outcomes[tpl["id"]] = outs
kept, not_sampled = select(tpl, outs, seed)
drops: dict[str, int] = {}
for o in outs:
if o.status == "drop":
drops[o.reason] = drops.get(o.reason, 0) + 1
n_q = {"answerable": 0, "unanswerable": 0}
for o in sorted(kept, key=lambda o: o.key):
q = make_question(con, tpl, o, all_wellbores, seed)
if q["question"] in texts: # the same text from two instances: keep the first only
drops[DROP_DUPLICATE] = drops.get(DROP_DUPLICATE, 0) + 1
continue
texts[q["question"]] = q["id"]
questions.append(q)
n_q["answerable" if q["answerable"] else "unanswerable"] += 1
per_template[tpl["id"]] = {
"family": tpl["family"], "answer_type": tpl["answer"]["type"], "candidates": len(outs),
"dropped": dict(sorted(drops.items())), "not_sampled": not_sampled,
"questions": n_q["answerable"] + n_q["unanswerable"], **n_q,
}
if len({q["id"] for q in questions}) != len(questions):
raise TemplateError("question ids are not unique")
return questions, outcomes, summarise(questions, per_template)
def summarise(questions: list[dict], per_template: dict) -> dict:
def count(key) -> dict:
out: dict[str, int] = {}
for q in questions:
k = key(q)
out[k] = out.get(k, 0) + 1
return dict(sorted(out.items()))
drops: dict[str, int] = {}
for t in per_template.values():
for reason, n in t["dropped"].items():
drops[reason] = drops.get(reason, 0) + n
sizes = sorted(q["n_evidence"] for q in questions if q["answerable"] and q["n_evidence"])
return {
"questions": len(questions),
"answerable": sum(q["answerable"] for q in questions),
"unanswerable": sum(not q["answerable"] for q in questions),
"templates": len(per_template),
"candidates": sum(t["candidates"] for t in per_template.values()),
"dropped": dict(sorted(drops.items())),
"dropped_total": sum(drops.values()),
"not_sampled": {k: sum(t["not_sampled"][k] for t in per_template.values())
for k in ("answerable", "unanswerable")},
"per_family": count(lambda q: q["family"]),
"per_answer_type": count(lambda q: q["answer_type"]),
"per_scope": count(lambda q: q["scope"]),
"per_tadi_category": count(lambda q: str(q["tadi_category"])),
"per_wellbore": count(lambda q: q["wellbore"] or "(field)"),
"per_well": count(lambda q: q["well"] or "(field)"),
"evidence_rows": {"min": sizes[0], "median": sizes[len(sizes) // 2], "max": sizes[-1],
"over_50": sum(s > 50 for s in sizes)} if sizes else {},
"per_template": per_template,
}
def connect(db_path: Path | str):
"""The DDR database, read-only, with the session time zone fixed so no result depends on the machine."""
import duckdb
con = duckdb.connect(str(db_path), read_only=True)
con.execute("SET TimeZone = 'UTC'")
return con
def write(questions: list[dict], out_dir: Path) -> None:
"""questions.jsonl (native values) and questions.parquet (answer and slots as JSON text; evidence as a list of
{table, report_id, seq, group} structs, seq NULL for a row of `reports`)."""
import pyarrow as pa
import pyarrow.parquet as pq
out_dir.mkdir(parents=True, exist_ok=True)
with (out_dir / "questions.jsonl").open("w", encoding="utf-8") as f:
for q in questions:
f.write(json.dumps(q, ensure_ascii=False) + "\n")
strings = pa.list_(pa.string())
types = {
"tadi_category": pa.int8(), "pattern_index": pa.int16(), "n_evidence": pa.int32(),
"n_evidence_groups": pa.int32(), "tolerance_abs": pa.float64(), "tolerance_rel": pa.float64(),
"tolerance_days": pa.int16(), "answerable": pa.bool_(), "printed_in_render": pa.bool_(),
"wellbores": strings, "wells": strings, "choices": strings, "source": strings, "caveats": strings,
"evidence": pa.list_(pa.struct([("table", pa.string()), ("report_id", pa.string()), ("seq", pa.int32()),
("group", pa.int32())])),
}
as_json = ("answer", "slots")
columns = list(questions[0]) if questions else []
arrays = []
for col in columns:
values = [q[col] for q in questions]
if col in as_json:
values = [json.dumps(v, ensure_ascii=False, sort_keys=True) for v in values]
arrays.append(pa.array(values, type=types.get(col, pa.string())))
pq.write_table(pa.Table.from_arrays(arrays, names=columns), out_dir / "questions.parquet")
def read_jsonl(path: Path | str) -> list[dict]:
with Path(path).open(encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
# ----------------------------------------------------------------------------------------------------------------------
# Scoring
# ----------------------------------------------------------------------------------------------------------------------
#: Factor from a unit to the reference unit of its dimension. A prediction in another unit of the same dimension is
#: converted before the tolerance is applied; a unit of another dimension, or an unknown one, is a wrong answer.
UNITS = {
"m": ("length", 1.0), "ft": ("length", 0.3048), "km": ("length", 1000.0), "metres": ("length", 1.0),
"meters": ("length", 1.0), "feet": ("length", 0.3048),
"h": ("time", 1.0), "hr": ("time", 1.0), "hrs": ("time", 1.0), "hour": ("time", 1.0), "hours": ("time", 1.0),
"min": ("time", 1 / 60), "d": ("time", 24.0), "day": ("time", 24.0), "days": ("time", 24.0),
"g/cm3": ("density", 1.0), "sg": ("density", 1.0), "kg/l": ("density", 1.0), "kg/m3": ("density", 0.001),
"ppg": ("density", 0.119826427),
"m/h": ("rate", 1.0), "m/hr": ("rate", 1.0), "ft/h": ("rate", 0.3048), "ft/hr": ("rate", 0.3048),
"deg": ("angle", 1.0), "dega": ("angle", 1.0), "degrees": ("angle", 1.0), "°": ("angle", 1.0),
"in": ("size", 1.0), "inch": ("size", 1.0), "inches": ("size", 1.0), '"': ("size", 1.0),
}
_ABSTAIN = re.compile(r"^\W*(not\s+(reported|available|recorded|stated|found|applicable)|no\s+(such\s+)?(record|data|"
r"information|event|activity|value)\w*(\s.*)?|unknown|n/?a|none|null|unanswerable|"
r"cannot\s+be\s+(determined|answered).*)\W*$", re.I)
_NUMBER = re.compile(r"[-+]?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?|[-+]?\.\d+")
_REPORT_ID = re.compile(r"\d+_\d+_.+_\d{4}_\d{2}_\d{2}")
_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%d-%m-%Y", "%d %B %Y", "%d %b %Y", "%B %d, %Y", "%b %d, %Y",
"%B %d %Y", "%b %d %Y", "%Y/%m/%d")
def is_abstention(answer: Any) -> bool:
"""None, an empty string or a phrase such as 'not reported', 'N/A', 'no such event'."""
if answer is None:
return True
if isinstance(answer, (list, tuple)):
return len(answer) == 0
if isinstance(answer, str):
return not answer.strip() or bool(_ABSTAIN.match(answer.strip()))
return False
def parse_number(value: Any) -> float | None:
"""A number from a number or from text ('3,520 m', '1,48', '12 1/4"'). The first number of the text is used;
'1,48' is read as a decimal comma, '3,520' as a thousands separator."""
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return float(value) if math.isfinite(value) else None
if not isinstance(value, str):
return None
mixed = re.match(r'^\s*(\d+)\s+(\d+)/(\d+)\s*("|in\b|inch)?', value) # 12 1/4"
if mixed and int(mixed.group(3)):
return int(mixed.group(1)) + int(mixed.group(2)) / int(mixed.group(3))
m = _NUMBER.search(value)
if not m:
return None
text = m.group(0).rstrip(",")
if "," in text:
if re.fullmatch(r"[-+]?\d{1,3}(,\d{3})+(\.\d+)?", text):
text = text.replace(",", "")
elif text.count(",") == 1 and "." not in text:
text = text.replace(",", ".")
else:
text = text.replace(",", "")
try:
return float(text)
except ValueError:
return None
def parse_date(value: Any) -> dt.date | None:
if isinstance(value, dt.datetime):
return value.date()
if isinstance(value, dt.date):
return value
if not isinstance(value, str):
return None
text = value.strip()
m = re.match(r"\d{4}-\d{2}-\d{2}", text)
if m:
text = m.group(0)
for fmt in _DATE_FORMATS:
try:
return dt.datetime.strptime(text, fmt).date()
except ValueError:
continue
return None
def parse_boolean(value: Any) -> bool | None:
if isinstance(value, bool):
return value
if isinstance(value, (int, float)) and value in (0, 1):
return bool(value)
if isinstance(value, str):
m = re.match(r"^\W*(yes|true|no|false)\b", value.strip(), re.I)
if m:
return m.group(1).lower() in ("yes", "true")
return None
def normalise_text(value: Any) -> str:
"""Case, accents, punctuation and spacing removed: 'Mærsk Inspirer.' and 'MÆRSK INSPIRER' compare equal."""
text = unicodedata.normalize("NFKD", str(value)).casefold()
text = "".join(c for c in text if not unicodedata.combining(c))
return re.sub(r"[^0-9a-zæøå]+", " ", text).strip()
def _same_text(pred: Any, gold: str) -> bool:
if normalise_text(pred) == normalise_text(gold):
return True
try: # wellbore names: 'NO 15/9-F-1 B', '15_9_F_1_B'
return canonical(str(pred)) == canonical(gold)
except ValueError:
return False
def convert_unit(value: float, unit: str | None, gold_unit: str | None) -> float | None:
"""`value` in `unit` expressed in `gold_unit`; None if the two are not of the same known dimension. A prediction
without a unit is taken to be in the gold unit. A gold unit that names what is counted ('reports', 'entries')
is a label, not a physical unit: the predicted unit is then ignored."""
if not unit or not gold_unit:
return value
u, g = unit.strip().lower().replace(" ", ""), gold_unit.strip().lower()
if u == g or g not in UNITS:
return value
if u not in UNITS or UNITS[u][0] != UNITS[g][0]:
return None
return value * UNITS[u][1] / UNITS[g][1]
def within_tolerance(pred: float, gold: float, abs_tol: float | None = None, rel_tol: float | None = None) -> bool:
"""|pred - gold| <= max(abs_tol, rel_tol * |gold|), with a small allowance for floating-point noise."""
limit = max(abs_tol or 0.0, (rel_tol or 0.0) * abs(gold))
return abs(pred - gold) <= limit + 1e-9 * max(1.0, abs(gold))
def inline_unit(text: Any) -> str | None:
"""The unit written after the first number of a text answer ('11548.6 ft' -> 'ft'), if it is a known unit."""
if not isinstance(text, str):
return None
m = _NUMBER.search(text)
if not m:
return None
u = re.match(r"\s*([A-Za-z°\"][A-Za-z0-9/]*)", text[m.end():])
return u.group(1).lower() if u and u.group(1).lower() in UNITS else None
def _match_value(pred: Any, gold: Any, kind: str, q: dict, unit: str | None) -> bool:
if kind == "number":
p = parse_number(pred)
if p is None:
return False
unit = unit or inline_unit(pred)
p = convert_unit(p, unit, q.get("unit"))
return p is not None and within_tolerance(p, float(gold), q.get("tolerance_abs"), q.get("tolerance_rel"))
if kind == "date":
p = parse_date(pred)
return p is not None and abs((p - parse_date(gold)).days) <= (q.get("tolerance_days") or 0)
if kind == "boolean":
p = parse_boolean(pred)
return p is not None and p == bool(gold)
return _same_text(pred, gold)
def parse_citation(c: Any) -> str | None:
"""A citation as an evidence id. Accepted: {'table', 'report_id', 'seq'}, 'table:report_id:seq',
'reports:report_id', an activity id as the DDR tables write it ('15_9_F_4_2008_02_19:010') and a bare report
id ('15_9_F_4_2008_02_19', read as the row of `reports`)."""
if isinstance(c, dict):
if "act_id" in c and "table" not in c:
return parse_citation(c["act_id"])
if not c.get("table") or not c.get("report_id"):
return None
return evidence_id(c["table"], c["report_id"], c.get("seq"))
if not isinstance(c, str):
return None
parts = c.strip().split(":")
try:
if len(parts) == 1 and _REPORT_ID.fullmatch(parts[0]):
return evidence_id("reports", parts[0])
if len(parts) == 3:
return evidence_id(parts[0], parts[1], int(parts[2]))
if len(parts) == 2 and parts[1].isdigit() and _REPORT_ID.fullmatch(parts[0]):
return evidence_id("activities", parts[0], int(parts[1]))
if len(parts) == 2:
return evidence_id(parts[0], parts[1])
except ValueError:
return None
return None
def _report_level(eid: str) -> str:
return "report:" + eid.split(":")[1]
def score_citations(citations: list | None, evidence: list[dict], level: str = "row") -> dict:
"""Citation precision (cited rows that are evidence rows / cited rows) and recall (evidence groups with a cited
row / evidence groups). None where the ratio has no denominator: precision without citations, recall for a
question without evidence rows. With `level="report"` a citation and an evidence row match when they are in the
same report, whatever the table and row: the lenient reading for answers that cite a report rather than a row.
A citation that cannot be parsed counts as a cited row that is not evidence."""
if level not in ("row", "report"):
raise ValueError(f"level must be 'row' or 'report', not {level!r}")
parsed = [parse_citation(c) for c in (citations or [])]
n_invalid = sum(c is None for c in parsed)
cited = {c for c in parsed if c is not None}
if level == "report":
cited = {_report_level(c) for c in cited}
groups: dict[int, set[str]] = {}
for e in evidence:
eid = evidence_id(e["table"], e["report_id"], e["seq"])
groups.setdefault(e["group"], set()).add(_report_level(eid) if level == "report" else eid)
gold_ids = set().union(*groups.values()) if groups else set()
n_cited = len(cited) + n_invalid
return {
"n_cited": n_cited,
"citation_precision": len(cited & gold_ids) / n_cited if n_cited else None,
"citation_recall": sum(bool(g & cited) for g in groups.values()) / len(groups) if groups else None,
}
def score(prediction: Any, gold: dict, citation_level: str = "row") -> dict:
"""Score one prediction against one question record (a row of questions.jsonl).
`prediction` is {"answer": ..., "unit": optional, "citations": optional list} or the bare answer. Returns
`correct` (type-aware match within the tolerance of the template), `abstained` (the prediction gives no answer),
`fabricated` (a concrete answer to a question whose gold answer is "not reported"), the citation scores and, for
a list answer, `list_precision` and `list_recall`. An abstention is correct only for an unanswerable question.
"""
if not (isinstance(prediction, dict) and ("answer" in prediction or "citations" in prediction)):
prediction = {"answer": prediction}
pred, unit = prediction.get("answer"), prediction.get("unit")
kind = gold["answer_type"]
answerable = gold.get("answerable", True)
abstained = is_abstention(pred)
if answerable and kind == "boolean" and parse_boolean(pred) is not None:
abstained = False # "No such activity is recorded" answers a yes/no question
out = {"correct": False, "abstained": abstained, "fabricated": False}
out.update(score_citations(prediction.get("citations"), gold.get("evidence") or [], citation_level))
if not answerable:
out["correct"] = out["abstained"]
out["fabricated"] = not out["abstained"]
return out
if out["abstained"]:
return out
if kind == "list":
items = pred if isinstance(pred, (list, tuple)) else re.split(r"\s*[;,]\s*|\s+and\s+", str(pred))
items = [i for i in items if not (isinstance(i, str) and not i.strip())]
left = list(gold["answer"])
hits = 0
for item in items:
for g in left:
if _match_value(item, g, gold["item_type"], gold, unit):
left.remove(g)
hits += 1
break
out["list_precision"] = hits / len(items) if items else 0.0
out["list_recall"] = hits / len(gold["answer"])
out["correct"] = hits == len(items) == len(gold["answer"])
return out
out["correct"] = _match_value(pred, gold["answer"], kind, gold, unit)
return out

728
volve_dia/t4_pandas.py Normal file
View File

@@ -0,0 +1,728 @@
"""Second, independent implementation of every T4 template, in pandas on the parquet copies of the DDR tables.
Purpose: a gold answer that two code paths agree on. `volve_dia/t4.py` computes answers and evidence rows with the
SQL of `configs/t4_templates.yaml` on DuckDB; this module computes the same things with pandas on
`outputs/ddr/*.parquet`, from the published columns only. The columns that the DDR parser derives are derived again
here, in another way:
wellbore of a row NPD wellbore alias of its report, joined on report_id (parser: `wellbore`)
report date last ten characters of report_id (parser: `file_date`)
activity start, end `dTimStart`, `dTimEnd` parsed with their UTC offsets (parser: `start_utc`, `end_utc`)
activity duration end - start in hours (parser: `duration_h`)
main code text before ' -- ' in `proprietaryCode` (parser: `code_main`)
well text before the first space of the wellbore name (SQL: split_part)
Each template has `enumerate(tables) -> list of slot dicts` and `answer(tables, **slots) -> Result`. `crosscheck`
compares, for every candidate instance, the slot enumeration, the status (answer, missing answer, drop reason), the
answer and the evidence rows with their grouping. The rules themselves (what is a tie, what is dropped) are taken
from the template definitions, so an error in a rule is not caught here; an error in its SQL is.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable
import pandas as pd
from .t4 import Outcome, evidence_id, slot_key
TABLES = ("reports", "activities", "bits", "casings", "surveys", "strat", "fluids", "equip_failures")
EVENT_DETAILS = ("stuck equipment", "circulation loss", "mud loss")
WOW, DRILL = "interruption -- waiting on weather", "drilling -- drill"
PAIR_CODES = (WOW, "interruption -- repair")
PRESENCE_CODES = ("interruption -- well control", "interruption -- lost circulation", "interruption -- sidetrack",
"interruption -- fish")
EXTRA_CODES = (DRILL, "drilling -- trip", "drilling -- casing")
@dataclass
class Result:
status: str # "ok", "null" (no answer) or "drop"
answer: Any = None
evidence: frozenset = frozenset() # set of groups, each a frozenset of evidence ids
reason: str | None = None
NULL = Result("null")
def dropped(reason: str) -> Result:
return Result("drop", reason=reason)
class Tables:
"""The DDR tables with the derived columns of this module, split by wellbore."""
def __init__(self, ddr_dir: Path | str):
ddr_dir = Path(ddr_dir)
raw = {name: pd.read_parquet(ddr_dir / f"{name}.parquet") for name in TABLES}
reports = raw["reports"].copy()
reports["wb"] = reports["wellboreAlias_NPD_code"].astype(str)
reports["date"] = reports["report_id"].str[-10:].str.replace("_", "-")
wb_of, date_of = reports.set_index("report_id")["wb"], reports.set_index("report_id")["date"]
self.all: dict[str, pd.DataFrame] = {"reports": reports}
for name in TABLES[1:]:
df = raw[name].copy()
df["wb"] = df["report_id"].map(wb_of)
df["date"] = df["report_id"].map(date_of)
self.all[name] = df
acts = self.all["activities"]
acts["t0"] = pd.to_datetime(acts["dTimStart"], utc=True, format="ISO8601")
acts["t1"] = pd.to_datetime(acts["dTimEnd"], utc=True, format="ISO8601")
acts["dur"] = (acts["t1"] - acts["t0"]).dt.total_seconds() / 3600
acts["main"] = acts["proprietaryCode"].str.split(" -- ").str[0]
self.all["activities"] = acts.sort_values(["wb", "t0"]).reset_index(drop=True)
self.wellbores = sorted(reports["wb"].unique())
self._by_wb = {name: {wb: g for wb, g in df.groupby("wb", sort=False)} for name, df in self.all.items()}
def wb(self, table: str, wellbore: str) -> pd.DataFrame:
"""The rows of one wellbore (an empty frame if it has none)."""
return self._by_wb[table].get(wellbore, self.all[table].iloc[0:0])
# ----------------------------------------------------------------------------------------------------------------------
# Helpers
# ----------------------------------------------------------------------------------------------------------------------
def ids(df: pd.DataFrame, table: str) -> list[str]:
if table == "reports":
return [evidence_id(table, r) for r in df["report_id"]]
return [evidence_id(table, r, s) for r, s in zip(df["report_id"], df["seq"])]
def ev_all(*id_lists: list[str]) -> frozenset:
return frozenset(frozenset([i]) for lst in id_lists for i in lst)
def ev_any(id_list: list[str]) -> frozenset:
return frozenset([frozenset(id_list)]) if id_list else frozenset()
def ev_groups(groups: dict[Any, list[str]]) -> frozenset:
return frozenset(frozenset(v) for v in groups.values() if v)
def well(wellbore: str) -> str:
return wellbore.split(" ")[0]
def unique_values(series: pd.Series) -> list:
return sorted(series.dropna().unique().tolist())
def single_value(df: pd.DataFrame, column: str, table: str, reason: str = "ambiguous_multiple_values") -> Result:
"""The one published value of `column` in `df`; evidence: every row that states it (any one is enough)."""
values = unique_values(df[column])
if len(values) > 1:
return dropped(reason)
if not values:
return NULL
return Result("ok", values[0], ev_any(ids(df[df[column].notna()], table)))
def density(rows: pd.DataFrame) -> Result:
rows = rows[rows["density"].notna()]
values = unique_values(rows["density"])
if len(values) > 1:
return dropped("ambiguous_multiple_values")
if not values:
return NULL
if values[0] < 0.5 or values[0] > 3:
return dropped("implausible_value")
return Result("ok", values[0], ev_any(ids(rows, "fluids")))
def first_event(t: Tables, wellbore: str, detail: str) -> pd.DataFrame:
"""The activity (or activities, if tied) of a wellbore with the earliest start among those with the state
detail."""
e = t.wb("activities", wellbore)
e = e[e["stateDetailActivity"] == detail]
return e[e["t0"] == e["t0"].min()] if len(e) else e
def section_rop(t: Tables, wellbore: str, hole: float) -> tuple[float | None, bool, list[str]]:
"""Metres per hour coded 'drilling -- drill' over the reports of a hole size that state metres drilled.
Returns (rop or None, True if a report has metres without drill hours, evidence ids)."""
r = t.wb("reports", wellbore)
r = r[(r["diaHole"] == hole) & (r["distDrill"] > 0)]
if r.empty:
return None, False, []
a = t.wb("activities", wellbore)
a = a[(a["proprietaryCode"] == DRILL) & a["report_id"].isin(set(r["report_id"]))]
bad = bool(set(r["report_id"]) - set(a["report_id"]))
hours = a["dur"].sum()
rop = float(r["distDrill"].sum() / hours) if hours > 0 else None
return rop, bad, ids(r, "reports") + ids(a, "activities")
def code_hours(t: Tables, wellbore: str, code: str) -> tuple[float, pd.DataFrame]:
a = t.wb("activities", wellbore)
a = a[a["proprietaryCode"] == code]
return round(float(a["dur"].sum()), 4), a
def slots(df: pd.DataFrame, columns: dict[str, str]) -> list[dict]:
"""Distinct rows of `df[columns]` as slot dicts, with the slot names of the template."""
out = df[list(columns)].drop_duplicates().rename(columns=columns)
return [{k: (v.item() if hasattr(v, "item") else v) for k, v in row.items()} for row in out.to_dict("records")]
def every_wellbore(t: Tables) -> list[dict]:
return [{"wellbore": w} for w in t.wellbores]
def hole_slots(t: Tables) -> list[dict]:
r = t.all["reports"]
return slots(r[r["diaHole"].notna()], {"wb": "wellbore", "diaHole": "hole"})
def event_slots(t: Tables) -> list[dict]:
a = t.all["activities"]
return slots(a[a["stateDetailActivity"].isin(EVENT_DETAILS)], {"wb": "wellbore", "stateDetailActivity": "detail"})
def all_event_slots(t: Tables) -> list[dict]:
return [{"wellbore": w, "detail": d} for w in t.wellbores for d in EVENT_DETAILS]
def same_well_pairs(wellbores: list[str]) -> list[tuple[str, str]]:
return [(a, b) for a in wellbores for b in wellbores if a < b and well(a) == well(b)]
# ----------------------------------------------------------------------------------------------------------------------
# Lookup
# ----------------------------------------------------------------------------------------------------------------------
def L01_spud_date(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore).assign(spud=lambda d: d["dTimSpud"].str[:10])
return single_value(r, "spud", "reports")
def L02_drill_complete_date(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore).assign(done=lambda d: d["dateDrillComplete"].str[:10])
return single_value(r, "done", "reports")
def L03_deepest_md(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore)
deepest = r["md"].max()
if pd.isna(deepest):
return NULL
return Result("ok", float(deepest), ev_any(ids(r[r["md"] == deepest], "reports")))
def L04_deepest_md_date(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore)
at_depth = r[r["md"] == r["md"].max()].sort_values("date")
if at_depth.empty:
return NULL
return Result("ok", at_depth["date"].iloc[0], ev_all(ids(at_depth.iloc[:1], "reports")))
def L05_enumerate(t: Tables) -> list[dict]:
return slots(t.all["casings"], {"wb": "wellbore", "od": "od"})
def L05_casing_bottom_md(t: Tables, wellbore: str, od: float) -> Result:
c = t.wb("casings", wellbore)
c = c[c["od"] == od]
deepest = c["mdBottom"].max()
if pd.isna(deepest):
return NULL
return Result("ok", float(deepest), ev_any(ids(c[c["mdBottom"] == deepest], "casings")))
def L06_casing_sizes(t: Tables, wellbore: str) -> Result:
c = t.wb("casings", wellbore)
sizes = sorted(unique_values(c["od"]), reverse=True)
if not sizes:
return NULL
return Result("ok", sizes, ev_groups({s: ids(c[c["od"] == s], "casings") for s in sizes}))
def L07_hole_sizes(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore)
sizes = sorted(unique_values(r["diaHole"]), reverse=True)
if not sizes:
return NULL
return Result("ok", sizes, ev_groups({s: ids(r[r["diaHole"] == s], "reports") for s in sizes}))
def L08_hole_section_start_md(t: Tables, wellbore: str, hole: float) -> Result:
r = t.wb("reports", wellbore)
return single_value(r[r["diaHole"] == hole], "mdDiaHoleStart", "reports")
def L09_hole_section_max_md(t: Tables, wellbore: str, hole: float) -> Result:
r = t.wb("reports", wellbore)
r = r[r["diaHole"] == hole]
deepest = r["md"].max()
if pd.isna(deepest):
return NULL
return Result("ok", float(deepest), ev_any(ids(r[r["md"] == deepest], "reports")))
def L10_enumerate(t: Tables) -> list[dict]:
s = t.all["surveys"]
return slots(s[s["incl"].notna()], {"wb": "wellbore"})
def L10_max_inclination(t: Tables, wellbore: str) -> Result:
s = t.wb("surveys", wellbore)
steepest = s["incl"].max()
if pd.isna(steepest):
return NULL
return Result("ok", float(steepest), ev_any(ids(s[s["incl"] == steepest], "surveys")))
def L11_max_inclination_md(t: Tables, wellbore: str) -> Result:
s = t.wb("surveys", wellbore)
top = s[s["incl"] == s["incl"].max()]
depths = unique_values(top["md"])
if len(depths) > 1:
return dropped("tie")
if not depths:
return NULL
return Result("ok", depths[0], ev_any(ids(top, "surveys")))
def L12_enumerate(t: Tables) -> list[dict]:
f = t.all["fluids"]
return slots(f[f["density"].notna()], {"wb": "wellbore", "date": "date"})
def L12_mud_density_on_date(t: Tables, wellbore: str, date: str) -> Result:
f = t.wb("fluids", wellbore)
return density(f[f["date"] == date])
def L13_enumerate(t: Tables) -> list[dict]:
f = t.all["fluids"]
return slots(f[(f["md"] > 0) & f["density"].notna()], {"wb": "wellbore", "md": "md"})
def L13_mud_density_at_depth(t: Tables, wellbore: str, md: float) -> Result:
f = t.wb("fluids", wellbore)
return density(f[f["md"] == md])
def _formation(name: str) -> str:
return name.rstrip(" .")
def L14_enumerate(t: Tables) -> list[dict]:
s = t.all["strat"].assign(fm=lambda d: d["description"].map(_formation))
return slots(s, {"wb": "wellbore", "fm": "formation"})
def L14_formation_top_md(t: Tables, wellbore: str, formation: str) -> Result:
s = t.wb("strat", wellbore)
return single_value(s[s["description"].map(_formation) == formation], "mdTop", "strat")
def L15_rig_name(t: Tables, wellbore: str) -> Result:
return single_value(t.wb("reports", wellbore), "rigAlias_NPD_Name", "reports")
def L16_kickoff_md(t: Tables, wellbore: str) -> Result:
return single_value(t.wb("reports", wellbore), "mdKickoff", "reports")
# ----------------------------------------------------------------------------------------------------------------------
# Aggregation
# ----------------------------------------------------------------------------------------------------------------------
def A01_reports_per_hole_size(t: Tables, wellbore: str, hole: float) -> Result:
r = t.wb("reports", wellbore)
r = r[r["diaHole"] == hole]
return Result("ok", float(len(r)), ev_all(ids(r, "reports"))) if len(r) else NULL
def A02_enumerate(t: Tables) -> list[dict]:
r = t.all["reports"]
return slots(r[r["distDrill"] > 0], {"wb": "wellbore"})
def A02_metres_drilled(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore)
r = r[r["distDrill"] > 0]
return Result("ok", float(r["distDrill"].sum()), ev_all(ids(r, "reports"))) if len(r) else NULL
def A03_metres_drilled_section(t: Tables, wellbore: str, hole: float) -> Result:
r = t.wb("reports", wellbore)
r = r[(r["diaHole"] == hole) & (r["distDrill"] > 0)]
return Result("ok", float(r["distDrill"].sum()), ev_all(ids(r, "reports"))) if len(r) else NULL
def A04_rop_section(t: Tables, wellbore: str, hole: float) -> Result:
rop, bad, evidence = section_rop(t, wellbore, hole)
if bad:
return dropped("inconsistent_source")
return Result("ok", rop, ev_all(evidence)) if rop is not None else NULL
def A05_enumerate(t: Tables) -> list[dict]:
b = t.all["bits"]
return slots(b[b["diaBit"] > 0], {"wb": "wellbore", "diaBit": "bit"})
def A05_bit_run_rop_max(t: Tables, wellbore: str, bit: float) -> Result:
b = t.wb("bits", wellbore)
b = b[b["diaBit"] == bit]
best = b["bitRun_ropAv"].max()
if pd.isna(best):
return NULL
return Result("ok", float(best), ev_any(ids(b[b["bitRun_ropAv"] == best], "bits")))
def A06_enumerate(t: Tables) -> list[dict]:
a = t.all["activities"]
return slots(a[(a["main"] == "interruption") | a["proprietaryCode"].isin(EXTRA_CODES)],
{"wb": "wellbore", "proprietaryCode": "code"})
def A06_hours_per_code(t: Tables, wellbore: str, code: str) -> Result:
a = t.wb("activities", wellbore)
a = a[a["proprietaryCode"] == code]
return Result("ok", float(a["dur"].sum()), ev_all(ids(a, "activities"))) if len(a) else NULL
def A07_enumerate(t: Tables) -> list[dict]:
return slots(t.all["equip_failures"], {"wb": "wellbore"})
def A07_equip_failure_count(t: Tables, wellbore: str) -> Result:
e = t.wb("equip_failures", wellbore)
return Result("ok", float(len(e)), ev_all(ids(e, "equip_failures"))) if len(e) else NULL
def A08_enumerate(t: Tables) -> list[dict]:
a = t.all["activities"]
return slots(a[a["main"] == "interruption"], {"wb": "wellbore"})
def A08_top_interruption_code(t: Tables, wellbore: str) -> Result:
a = t.wb("activities", wellbore)
a = a[a["main"] == "interruption"]
if a.empty:
return NULL
hours = a.groupby("proprietaryCode")["dur"].sum().round(4)
top = hours[hours == hours.max()].index.tolist()
if len(top) > 1:
return dropped("tie")
return Result("ok", top[0], ev_all(ids(a[a["proprietaryCode"] == top[0]], "activities")))
def wow_enumerate(t: Tables) -> list[dict]:
a = t.all["activities"]
return slots(a[a["proprietaryCode"] == WOW], {"wb": "wellbore"})
def A09_wow_days(t: Tables, wellbore: str) -> Result:
a = t.wb("activities", wellbore)
a = a[a["proprietaryCode"] == WOW]
if a.empty:
return NULL
groups = {rid: ids(g, "activities") for rid, g in a.groupby("report_id")}
return Result("ok", float(len(groups)), ev_groups(groups))
# ----------------------------------------------------------------------------------------------------------------------
# Temporal and event
# ----------------------------------------------------------------------------------------------------------------------
def E01_first_event_date(t: Tables, wellbore: str, detail: str) -> Result:
e = first_event(t, wellbore, detail)
if e.empty:
return NULL
if len(e) > 1:
return dropped("tie")
return Result("ok", e["dTimStart"].iloc[0][:10], ev_all(ids(e, "activities")))
def E02_first_event_md(t: Tables, wellbore: str, detail: str) -> Result:
e = first_event(t, wellbore, detail)
if e.empty or pd.isna(e["md"].iloc[0]):
return NULL
if len(e) > 1:
return dropped("tie")
return Result("ok", float(e["md"].iloc[0]), ev_all(ids(e, "activities")))
def E03_activity_before_first_event(t: Tables, wellbore: str, detail: str) -> Result:
a = t.wb("activities", wellbore).reset_index(drop=True) # in time order
hits = a.index[a["stateDetailActivity"] == detail]
if len(hits) == 0 or hits[0] == 0:
return NULL
event, before = a.loc[hits[0]], a.loc[hits[0] - 1]
if before["t1"] != event["t0"]:
return dropped("not_contiguous")
return Result("ok", before["proprietaryCode"], ev_all(ids(a.loc[[hits[0] - 1, hits[0]]], "activities")))
def E04_first_episode_hours(t: Tables, wellbore: str, detail: str) -> Result:
a = t.wb("activities", wellbore).reset_index(drop=True)
hit = (a["stateDetailActivity"] == detail).tolist()
if True not in hit:
return NULL
start = stop = hit.index(True)
while stop < len(hit) and hit[stop]:
stop += 1
run = a.iloc[start:stop]
return Result("ok", float(run["dur"].sum()), ev_all(ids(run, "activities")))
def E05_max_wow_day(t: Tables, wellbore: str) -> Result:
a = t.wb("activities", wellbore)
a = a[a["proprietaryCode"] == WOW]
if a.empty:
return NULL
per_day = a.groupby("date")["dur"].sum().round(4)
days = per_day[per_day == per_day.max()].index.tolist()
if len(days) > 1:
return dropped("tie")
return Result("ok", days[0], ev_all(ids(a[a["date"] == days[0]], "activities")))
def E06_enumerate(t: Tables) -> list[dict]:
return [{"wellbore": w, "code": c} for w in t.wellbores for c in PRESENCE_CODES]
def E06_code_present(t: Tables, wellbore: str, code: str) -> Result:
a = t.wb("activities", wellbore)
a = a[a["proprietaryCode"] == code]
return Result("ok", bool(len(a)), ev_any(ids(a, "activities")))
# ----------------------------------------------------------------------------------------------------------------------
# Comparison
# ----------------------------------------------------------------------------------------------------------------------
def C01_enumerate(t: Tables) -> list[dict]:
return [{"wellbore_a": a, "wellbore_b": b, "code": c} for a, b in same_well_pairs(t.wellbores) for c in PAIR_CODES]
def C01_more_hours_pair(t: Tables, wellbore_a: str, wellbore_b: str, code: str) -> Result:
(ha, rows_a), (hb, rows_b) = code_hours(t, wellbore_a, code), code_hours(t, wellbore_b, code)
if ha == hb:
return dropped("tie") if ha > 0 else NULL
evidence = ev_all(ids(rows_a, "activities"), ids(rows_b, "activities"))
return Result("ok", wellbore_a if ha > hb else wellbore_b, evidence)
def C02_enumerate(t: Tables) -> list[dict]:
r = t.all["reports"]
have = {(s["wellbore"], s["hole"]) for s in slots(r[r["diaHole"].notna() & (r["distDrill"] > 0)],
{"wb": "wellbore", "diaHole": "hole"})}
return [{"wellbore_a": a, "wellbore_b": b, "hole": h} for a, b in same_well_pairs(t.wellbores)
for h in sorted({h for w, h in have if w == a}) if (b, h) in have]
def C02_faster_rop_pair(t: Tables, wellbore_a: str, wellbore_b: str, hole: float) -> Result:
(ra, bad_a, ev_a), (rb, bad_b, ev_b) = section_rop(t, wellbore_a, hole), section_rop(t, wellbore_b, hole)
if bad_a or bad_b:
return dropped("inconsistent_source")
if ra is None or rb is None:
return NULL
if abs(ra - rb) <= 0.02 * max(ra, rb):
return dropped("tie")
return Result("ok", wellbore_a if ra > rb else wellbore_b, ev_all(ev_a, ev_b))
def C03_enumerate(t: Tables) -> list[dict]:
a = t.all["activities"]
return slots(a[a["main"] == "interruption"], {"proprietaryCode": "code"})
def C03_field_most_hours(t: Tables, code: str) -> Result:
a = t.all["activities"]
a = a[a["proprietaryCode"] == code]
if a.empty:
return NULL
hours = a.groupby("wb")["dur"].sum().round(4)
top = hours[hours == hours.max()].index.tolist()
if len(top) > 1:
return dropped("tie")
return Result("ok", top[0], ev_all(ids(a[a["wb"] == top[0]], "activities")))
# ----------------------------------------------------------------------------------------------------------------------
# Multi-hop
# ----------------------------------------------------------------------------------------------------------------------
def _event_report(t: Tables, wellbore: str, detail: str) -> tuple[pd.DataFrame, pd.DataFrame]:
"""The first activity with the state detail (earliest start; the first row if tied) and the row of its report."""
e = first_event(t, wellbore, detail).iloc[:1]
r = t.wb("reports", wellbore)
return e, r[r["report_id"].isin(e["report_id"])]
def M01_mud_density_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
e, report = _event_report(t, wellbore, detail)
f = t.wb("fluids", wellbore)
res = density(f[f["report_id"].isin(report["report_id"])])
if res.status != "ok":
return res
return Result("ok", res.answer, ev_all(ids(e, "activities")) | res.evidence)
def _report_value(t: Tables, wellbore: str, detail: str, column: str) -> Result:
e, report = _event_report(t, wellbore, detail)
if report.empty or pd.isna(report[column].iloc[0]):
return NULL
return Result("ok", float(report[column].iloc[0]), ev_all(ids(e, "activities"), ids(report, "reports")))
def M02_hole_size_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
return _report_value(t, wellbore, detail, "diaHole")
def M03_formation_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
e, _ = _event_report(t, wellbore, detail)
if e.empty or pd.isna(e["md"].iloc[0]):
return NULL
s = t.wb("strat", wellbore)
above = s[s["mdTop"] <= e["md"].iloc[0]]
if above.empty:
return NULL
top = above[above["mdTop"] == above["mdTop"].max()]
names = sorted({_formation(d) for d in top["description"]})
if len(names) > 1:
return dropped("tie")
return Result("ok", names[0], ev_all(ids(e, "activities")) | ev_any(ids(top, "strat")))
def M04_last_casing_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
return _report_value(t, wellbore, detail, "mdCsgLast")
def M05_days_spud_to_deepest_md(t: Tables, wellbore: str) -> Result:
r = t.wb("reports", wellbore)
spud = unique_values(r["dTimSpud"].str[:10])
at_depth = r[r["md"] == r["md"].max()].sort_values("date").iloc[:1]
if len(spud) > 1:
return dropped("ambiguous_multiple_values")
if not spud or at_depth.empty:
return NULL
days = (pd.Timestamp(at_depth["date"].iloc[0]) - pd.Timestamp(spud[0])).days
if days < 0:
return dropped("implausible_value")
evidence = ev_all(ids(at_depth, "reports")) | ev_any(ids(r[r["dTimSpud"].notna()], "reports"))
return Result("ok", float(days), evidence)
#: template id -> (slot enumeration, answer function)
TEMPLATES: dict[str, tuple[Callable, Callable]] = {
"L01_spud_date": (every_wellbore, L01_spud_date),
"L02_drill_complete_date": (every_wellbore, L02_drill_complete_date),
"L03_deepest_md": (every_wellbore, L03_deepest_md),
"L04_deepest_md_date": (every_wellbore, L04_deepest_md_date),
"L05_casing_bottom_md": (L05_enumerate, L05_casing_bottom_md),
"L06_casing_sizes": (lambda t: slots(t.all["casings"], {"wb": "wellbore"}), L06_casing_sizes),
"L07_hole_sizes": (lambda t: slots(t.all["reports"][t.all["reports"]["diaHole"].notna()], {"wb": "wellbore"}),
L07_hole_sizes),
"L08_hole_section_start_md": (hole_slots, L08_hole_section_start_md),
"L09_hole_section_max_md": (hole_slots, L09_hole_section_max_md),
"L10_max_inclination": (L10_enumerate, L10_max_inclination),
"L11_max_inclination_md": (L10_enumerate, L11_max_inclination_md),
"L12_mud_density_on_date": (L12_enumerate, L12_mud_density_on_date),
"L13_mud_density_at_depth": (L13_enumerate, L13_mud_density_at_depth),
"L14_formation_top_md": (L14_enumerate, L14_formation_top_md),
"L15_rig_name": (every_wellbore, L15_rig_name),
"L16_kickoff_md": (every_wellbore, L16_kickoff_md),
"A01_reports_per_hole_size": (hole_slots, A01_reports_per_hole_size),
"A02_metres_drilled": (A02_enumerate, A02_metres_drilled),
"A03_metres_drilled_section": (hole_slots, A03_metres_drilled_section),
"A04_rop_section": (hole_slots, A04_rop_section),
"A05_bit_run_rop_max": (A05_enumerate, A05_bit_run_rop_max),
"A06_hours_per_code": (A06_enumerate, A06_hours_per_code),
"A07_equip_failure_count": (A07_enumerate, A07_equip_failure_count),
"A08_top_interruption_code": (A08_enumerate, A08_top_interruption_code),
"A09_wow_days": (wow_enumerate, A09_wow_days),
"E01_first_event_date": (all_event_slots, E01_first_event_date),
"E02_first_event_md": (event_slots, E02_first_event_md),
"E03_activity_before_first_event": (event_slots, E03_activity_before_first_event),
"E04_first_episode_hours": (all_event_slots, E04_first_episode_hours),
"E05_max_wow_day": (wow_enumerate, E05_max_wow_day),
"E06_code_present": (E06_enumerate, E06_code_present),
"C01_more_hours_pair": (C01_enumerate, C01_more_hours_pair),
"C02_faster_rop_pair": (C02_enumerate, C02_faster_rop_pair),
"C03_field_most_hours": (C03_enumerate, C03_field_most_hours),
"M01_mud_density_at_first_event": (event_slots, M01_mud_density_at_first_event),
"M02_hole_size_at_first_event": (event_slots, M02_hole_size_at_first_event),
"M03_formation_at_first_event": (event_slots, M03_formation_at_first_event),
"M04_last_casing_at_first_event": (event_slots, M04_last_casing_at_first_event),
"M05_days_spud_to_deepest_md": (every_wellbore, M05_days_spud_to_deepest_md),
}
# ----------------------------------------------------------------------------------------------------------------------
# Comparison of the two implementations
# ----------------------------------------------------------------------------------------------------------------------
def same_answer(spec: dict, sql_answer: Any, pd_answer: Any) -> bool:
"""SQL answers are rounded to `round` decimals, pandas answers are not: a number agrees if it is within half a
unit of the last decimal (1e-9 relative without rounding)."""
def close(a: Any, b: Any) -> bool:
limit = 0.5 * 10 ** -spec["round"] if "round" in spec else 0.0
return abs(float(a) - float(b)) <= limit + 1e-9 * max(1.0, abs(float(a)))
if spec["type"] == "number":
return close(sql_answer, pd_answer)
if spec["type"] == "list":
if len(sql_answer) != len(pd_answer):
return False
if spec["item_type"] == "number":
return all(close(a, b) for a, b in zip(sql_answer, pd_answer))
return list(sql_answer) == list(pd_answer)
if spec["type"] == "boolean":
return bool(sql_answer) == bool(pd_answer)
return str(sql_answer) == str(pd_answer)
def compare(tpl: dict, o: Outcome, res: Result) -> list[str]:
"""What differs between the SQL outcome and the pandas result of one instance: 'status', 'answer', 'evidence'."""
if o.status == "ok":
if res.status != "ok":
return ["status"]
diff = [] if same_answer(tpl["answer"], o.answer, res.answer) else ["answer"]
return diff + ([] if o.evidence_partition() == res.evidence else ["evidence"])
if o.status == "not_reported" or o.reason == "null_answer":
return [] if res.status == "null" else ["status"]
return [] if (res.status, res.reason) == ("drop", o.reason) else ["status"]
def crosscheck(cfg: dict, outcomes: dict[str, list[Outcome]], tables: Tables, examples: int = 5) -> dict:
"""Agreement of the two implementations on every candidate instance of every template (duplicates excluded)."""
per_template, total = {}, {"instances": 0, "agree": 0, "status": 0, "answer": 0, "evidence": 0}
for tpl in cfg["templates"]:
tid = tpl["id"]
enumerate_fn, answer_fn = TEMPLATES[tid]
outs = [o for o in outcomes[tid] if o.reason != "duplicate"]
sql_keys = {o.key for o in outs}
pd_keys = {slot_key(tid, {k: s[k] for k in tpl["slots"]}) for s in enumerate_fn(tables)}
row = {"instances": len(outs), "agree": 0, "status": 0, "answer": 0, "evidence": 0,
"slots_only_sql": len(sql_keys - pd_keys), "slots_only_pandas": len(pd_keys - sql_keys),
"examples": []}
for o in outs:
diff = compare(tpl, o, answer_fn(tables, **o.slots))
row["agree"] += not diff
for d in diff:
row[d] += 1
if diff and len(row["examples"]) < examples:
res = answer_fn(tables, **o.slots)
row["examples"].append({"slots": o.slots, "differs": diff, "sql": [o.status, o.reason, o.answer],
"pandas": [res.status, res.reason, res.answer]})
for k in total:
total[k] += row[k]
per_template[tid] = row
total["slot_differences"] = sum(r["slots_only_sql"] + r["slots_only_pandas"] for r in per_template.values())
total["templates"] = len(per_template)
total["templates_in_full_agreement"] = sum(
r["agree"] == r["instances"] and not r["slots_only_sql"] and not r["slots_only_pandas"]
for r in per_template.values())
total["agreement"] = round(total["agree"] / total["instances"], 6) if total["instances"] else None
return {"total": total, "per_template": per_template}

136
volve_dia/tops.py Normal file
View File

@@ -0,0 +1,136 @@
"""Formation tops of the Volve wells: `Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat` as a table.
The file is fixed-width text. Every well has a block: a `Well NO <name>` line, a header line, a line of dashes
that gives the column positions, and one line per pick. `parse_picks` slices every pick line at the dash columns
and checks it against the block header. The file states no units; depths agree with the DDR in metres.
Published columns: `Well name`, `Surface name`, `Obs#` (a surface crossed more than once is numbered), `Qlf`
(ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached), `MD`, `TVD`, `TVDSS`, `TWT`, `Dip`,
`Azi`, `Easting`, `Northing`, `Intrp`. Added columns: `wellbore_picks` (the published name without "NO "),
`wellbore` (the DDR wellbore the pick belongs to, see `PICKS_TO_DDR`; None when the well has no DDR), `track`,
`unit` and `boundary` (the surface name split at its trailing "Top"/"Base").
"""
from __future__ import annotations
import re
from pathlib import Path
import pandas as pd
from .names import canonical
COLUMNS = ["Well name", "Surface name", "Obs#", "Qlf", "MD", "TVD", "TVDSS", "TWT", "Dip", "Azi", "Easting",
"Northing", "Intrp"]
NUMERIC = ["MD", "TVD", "TVDSS", "TWT", "Dip", "Azi", "Easting", "Northing"]
QUALIFIERS = {"ER": "eroded", "FP": "faulted pick", "FO": "faulted out", "NL": "not logged", "NR": "not reached"}
#: Names of the picks file that are not DDR wellbore names -> (DDR wellbore, track). Evidence:
#:
#: * `15/9-19 SR` is the NPD name of the 1993 re-entry of 15/9-19 S (NPD FactPages, wellbore 2105: entered
#: 17.02.1993, TD 4641 m MD; its lithostratigraphy lists Shetland Gp 3827, Draupne Fm 4304, Skagerrak Fm 4340 m,
#: the MD of the picks). NPD and the DDR cut the same hole differently. NPD: `15/9-19 S` is the first hole plus
#: its technical sidetrack from 1493 m down to 3580 m (FactPages 2043), `15/9-19 SR` deepened it to 4641 m. DDR:
#: `15/9-19 S` is the first hole only (49 reports to 19.12.1992, deepest 3353 m, stuck and plugged back) and
#: `15/9-19 ST2` is everything drilled after the sidetrack (127 reports, 19.12.1992-26.07.1997, to 4641 m). The
#: picks below the sidetrack point (3614-4579 m MD) lie below the deepest point of DDR `15/9-19 S` and inside
#: `15/9-19 ST2`. Both DDR wellbores carry NPD number 2043; the DDR never uses the name SR.
#: * `15/9-F-12 pilot` is the 8 1/2" pilot hole of F-12 (to 1353 m, 23.06-05.07.2007, then plugged). The DDR
#: reports it under `15/9-F-12` (reports with diaPilot = 8.5), so its picks map to that wellbore, track "pilot".
PICKS_TO_DDR = {
"15/9-19 SR": ("15/9-19 ST2", "main"),
"15/9-F-12 pilot": ("15/9-F-12", "pilot"),
}
#: DDR wellbores without a block of their own: (wellbore, block they share the upper hole with, MD of the
#: kick-off in metres). Picks of that block above the kick-off lie in the shared hole and apply to both.
#:
#: * `15/9-19 S`: `15/9-19 ST2` was sidetracked from it at 1493 m (DDR activity 15_9_19_ST2_1992_12_19:000,
#: "SIDETRACKED ... FROM 1493M"; NPD FactPages 2043: "plugging back and sidetracking from 1493 m").
#: * `15/9-F-9 A` left F-9 through a window in the 13 3/8" casing; the DDR records parameters "above 13 3/8"
#: casing window at 395 m" (activity 15_9_F_9_A_2009_07_05:011) and the WITSML trajectory of F-9 A starts at
#: 420.4 m. The picks of F-9 are at 146, 146, 885 and 1071.2 m, so any kick-off between 146 and 885 m gives the
#: same two shared picks; the DDR itself puts the Utsira Fm of F-9 A at 959 m against 885 m in F-9.
SHARED_TRUNK = [
("15/9-19 S", "15/9-19 SR", 1493.0),
("15/9-F-9 A", "15/9-F-9", 395.0),
]
_WELL = re.compile(r"^Well (NO .+?)\s*$")
_BOUNDARY = re.compile(r"^(.*?)\s+(Top|Base)$")
def picks_wellbore(name: str) -> str:
"""'NO 15/9-F-12 pilot' -> '15/9-F-12 pilot'; names without a suffix word go through `canonical`."""
s = re.sub(r"\s+", " ", name.strip())
try:
return canonical(s)
except ValueError:
return re.sub(r"^NO\s+", "", s)
def parse_picks(path: Path, ddr_wellbores: set[str] | None = None) -> pd.DataFrame:
"""One row per pick, in file order. `ddr_wellbores` (canonical names) decides the `wellbore` column: a pick
gets a DDR wellbore only if its mapped name is one; with None every mapped name is kept."""
rows = []
well = spans = None
lines = path.read_text(encoding="ascii").splitlines()
for no, line in enumerate(lines, 1):
m = _WELL.match(line)
if m:
well, spans = m.group(1), None
continue
if not line.strip() or line.startswith("#"):
continue
if well is None:
raise ValueError(f"{path.name}:{no}: text before the first well block")
if line.strip().startswith("Well name"):
header = line
continue
if set(line.strip()) <= {"-", " "}:
starts = [m.start() for m in re.finditer(r"-+", line)]
if len(starts) != len(COLUMNS):
raise ValueError(f"{path.name}:{no}: {len(starts)} columns, expected {len(COLUMNS)}")
spans = list(zip(starts, starts[1:] + [None]))
got = [header[a:b].strip() for a, b in spans]
if got != COLUMNS:
raise ValueError(f"{path.name}:{no}: header {got}")
continue
if spans is None:
raise ValueError(f"{path.name}:{no}: pick line before the column line")
cells = [line[a:b].strip() for a, b in spans]
row = dict(zip(COLUMNS, cells))
if row["Well name"] != well:
raise ValueError(f"{path.name}:{no}: pick of {row['Well name']!r} in the block of {well!r}")
row["line"] = no
rows.append(row)
df = pd.DataFrame(rows)
for c in NUMERIC:
df[c] = pd.to_numeric(df[c].replace("", None)) # raises on anything that is not a number
df["Obs#"] = df["Obs#"].astype(int)
df["Qlf"] = df["Qlf"].replace("", None)
unknown = set(df["Qlf"].dropna()) - set(QUALIFIERS)
if unknown:
raise ValueError(f"unknown qualifiers: {unknown}")
df["wellbore_picks"] = df["Well name"].map(picks_wellbore)
mapped = df["wellbore_picks"].map(lambda w: PICKS_TO_DDR.get(w, (w, "main")))
df["wellbore"] = [w if ddr_wellbores is None or w in ddr_wellbores else None for w, _ in mapped]
df["track"] = [t for _, t in mapped]
split = df["Surface name"].str.extract(_BOUNDARY)
df["unit"] = split[0].fillna(df["Surface name"])
df["boundary"] = split[1]
return df[["wellbore", "wellbore_picks", "track", "Surface name", "unit", "boundary", "Obs#", "Qlf", "MD",
"TVD", "TVDSS", "TWT", "Dip", "Azi", "Easting", "Northing", "Intrp", "line"]].rename(
columns={"Surface name": "surface", "Obs#": "obs", "Qlf": "qlf", "MD": "md", "TVD": "tvd", "TVDSS": "tvdss",
"TWT": "twt", "Dip": "dip", "Azi": "azi", "Easting": "easting", "Northing": "northing",
"Intrp": "intrp"})
def shared_trunk_picks(picks: pd.DataFrame) -> pd.DataFrame:
"""Picks that a DDR wellbore without a block of its own shares with its mother bore (`SHARED_TRUNK`): the
published rows above the kick-off, re-labelled with that wellbore and `inherited_from`."""
out = []
for wellbore, block, kickoff in SHARED_TRUNK:
part = picks[(picks["wellbore_picks"] == block) & (picks["md"] < kickoff)].copy()
part["wellbore"], part["inherited_from"], part["md_kickoff"] = wellbore, block, kickoff
out.append(part)
return pd.concat(out, ignore_index=True)

826
volve_dia/witsml.py Normal file
View File

@@ -0,0 +1,826 @@
"""WITSML 1.4.1.1 real-time objects of Volve (`WITSML Realtime drilling data/`) as flat tables.
Layout of the source. A top folder is a *well* on one of two servers (Schlumberger-era folders such as
`Norway-StatoilHydro-15_$47$_9-F-15A`, Baker-Hughes-era folders such as `Norway-Statoil-NO 15_$47$_9-F-11`); its
numbered subfolders are the *wellbores* of that well (`NO 15/9-F-11` holds F-11, F-11 A, F-11 B and F-11 T2). The
wellbore of an object is therefore read from the object (`nameWellbore`, `uidWellbore`), never from the folder.
<well>/<n>/log/<i>/<j>/<k>/NNNNN.xml one log (`<k>`) cut into consecutive chunk files
<well>/<n>/{trajectory,message,bhaRun,mudLog}/N.xml
Parsed here: `log` (header, logCurveInfo, logData; time- and depth-indexed), `trajectory`, `message`, `bhaRun`,
`mudLog`. Not parsed: `tubular`, `rig`, `wbGeometry`, `_wellInfo`, `_wellboreInfo`.
Column names are the WITSML element names (a nested element prefixes its leaves with its tag), so every value can
be traced back to the schema. Values are stored as published, in the published unit. Log data are stored long:
one row per published value `(wellbore, log_id, mnemonic, index, value | text, chunk)`, because the logs publish
1,744 different mnemonics, of which the two service companies share 3 (HKLD, MWIN, DXC). `log_id` + `chunk` name the
source file of every value. Normalisations, all counted, none silent:
* an empty log cell is "no value" and makes no row;
* a log value equal to the `nullValue` of its curve (or of its log) becomes missing (`n_null_value`);
* the sentinels -999.25 and -9999 become missing (TADI, arXiv:2605.00060, section 3.3 "Sentinel values");
two more sentinels found in the object files are listed in `EXTRA_SENTINELS` with the reason;
* a cell of a numeric curve that is not a number (array curves publish 16 space-separated values) is kept as
text (`n_not_number`); curves of type string or date time are text;
* trajectory angles and magnetic fields are published in two units (Schlumberger: dega, nT; Baker Hughes: rad, T):
they are stored in the units of `STORED_UNITS` and the conversion is counted in the `units` table;
* duplicates, see `dedup_curve` (inside one log: rows with the same index, one is kept) and `merge_curve`
(between logs of one wellbore: rows with the same mnemonic and index are all kept and ranked, `dup_rank`);
* three Schlumberger-server wellbores are renamed to their DDR name (`WELLBORE_BY_UID`).
Deviations from TADI (sections 3.2-3.3): TADI converts ROP to m/h, WOB to kN and RPM to 1/min and drops values it
calls implausible (ROP > 200 m/h, RPM > 300, WOB > 500 kN). Here units stay as published (recorded per column and
per curve) and no value is dropped for being large: `tadi_implausible` only flags mudLog intervals, and the values
listed in `SUSPECT_VALUES` are only counted per curve, because a benchmark value must be the published one. TADI
did not parse the `log` objects.
Times: log indexes are UTC timestamps (every published index ends in "Z", checked); other times stay ISO strings
as published.
"""
from __future__ import annotations
import collections
import io
import math
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.csv as pacsv
import pyarrow.parquet as pq
from .names import canonical, stem
NS = "{http://www.witsml.org/schemas/1series}"
#: TADI section 3.3: "WITSML uses -999.25 and -9999".
SENTINELS = (-999.25, -9999.0)
#: Sentinels of the object files that TADI does not list: (table, column prefix) -> value.
#: * mudLog gas concentrations (ppm) are published as -999 where there is no reading; a concentration is never
#: negative. (+999 also occurs, 5 times, but 999 ppm is a possible reading, so it is kept.)
#: * `stnGridCorUsed` is 999.25 in 2,123 Baker Hughes stations: a grid convergence of 999.25 rad is not an angle.
EXTRA_SENTINELS = {
("mudlog_intervals", "chromatograph_"): -999.0,
("mudlog_intervals", "mudGas_"): -999.0,
("trajectory", "corUsed_stnGridCorUsed"): 999.25,
}
#: Log values that look like more sentinels. They are *kept* and counted per curve (`log_suspects`): none of them
#: is a declared null value, and e.g. 9999 s is a possible off-bottom time.
SUSPECT_VALUES = (-999.0, 999.25, -999.99, 9999.0, -99999.0, 99999.0, 1e30, -1e30)
SUSPECT_HUGE = 1e15 # |value| above this is counted as "huge"
#: Unit a column is stored in when the source publishes it in more than one unit: published unit -> (stored, factor).
STORED_UNITS = {
"rad": ("dega", 180.0 / math.pi),
"T": ("nT", 1e9),
"rad/m": ("dega/30m", 30.0 * 180.0 / math.pi),
"dega/m": ("dega/30m", 30.0),
}
#: TADI section 3.3 quality filters in the published SI units; used only to flag (`tadi_implausible`).
TADI_FILTERS = {"ropAv": 200.0 / 3600.0, "rpmAv": 300.0 / 60.0, "wobAv": 500.0e3} # m/s, c/s, N
#: commonData leaves that identify people and machines of the operator; not needed, not copied.
DROPPED = {"priv_userOwner", "priv_userLastChange", "priv_ipOwner", "priv_ipLastChange"}
#: WITSML `typeLogData` values stored as numbers; every other type is stored as text.
NUMERIC_TYPES = {"double", "float", "long", "int", "short", "byte"}
INDEX_KINDS = {"date time": "time", "measured depth": "depth"}
#: Logs that hold display settings of the WITSML store (2 rows of text written on 22.09.2015 into every wellbore),
#: not measurements. They are parsed like every log but excluded from time ranges and coverage.
SETTINGS_LOGS = {"GlcSettingsLog"}
#: Hole depth and bit depth of the time logs: Schlumberger `DMEA`/`DBTM`; Baker Hughes `Depth`/`BITDEP` of the
#: `GenTime` log. (Every Baker Hughes log has a `Depth` curve: the reference depth of *that* log, which for an MWD
#: log is the sensor depth. Only in `GenTime` is it the hole depth.)
HOLE_DEPTH = {"DMEA": None, "Depth": "GenTime"} # mnemonic -> required log name (None: any)
BIT_DEPTH = {"DBTM": None, "BITDEP": "GenTime"}
#: The Schlumberger server names three wellbores of slot F-15 differently from the DDR and from NPD: uidWellbore
#: -> DDR wellbore. No DDR and no NPD wellbore is called F-15 S. Evidence, per uid (the first item is recomputed on
#: every run by `scripts/06_parse_witsml.py`, which fails if a uid agrees better with another DDR wellbore):
#: 1. hole depth `DMEA` at the end of the DDR report periods against `md` of the DDR (table
#: `check_wellbore_identity`), for every DDR wellbore of the slot;
#: 2. DDR survey stations found in the WITSML trajectories (MD within 0.5 m, inclination 0.1, azimuth 0.5 deg);
#: 3. total depth in `_wellboreInfo` against the deepest `md` of the DDR and the TD of NPD FactPages;
#: 4. dates of the time logs against the DDR reports and the NPD entry and completion dates.
#:
#: B-744206 "15/9-F-15S" = DDR 15/9-F-15: (1) 47 reports, median |diff| 0.12 m, 42 within 5 m; (2) 27 of its
#: 27 distinct DDR stations; (3) 4090.0 m, DDR 4090 m; (4) logs 08.09-08.12.2008, NPD completed 05.12.2008.
#: B-826806 "15/9-F-15" = DDR 15/9-F-15 A: (1) 15 reports, median 0.50 m, 13 within 5 m, while against DDR
#: 15/9-F-15 all 3 reports are 2890 m off; (2) 53 stations of F-15 A, 0 of F-15; (3) 4096.5 m, DDR and
#: NPD 4095 m; (4) logs 08.12.2008-12.01.2009, NPD 11.12.2008-10.01.2009.
#: B-861401 "15/9-F-15A" = DDR 15/9-F-15 C: (1) 7 reports, median 0.12 m, 7 within 5 m, while against DDR
#: 15/9-F-15 B both reports are about 960 m off; (2) 6 of the 6 stations of F-15 C, 1 of F-15 A;
#: (3) 3232.1 m, DDR and NPD 3232 m; (4) logs 14.01-02.03.2009, NPD 18.01-15.02.2009.
#: B-854763 "15/9-F-15B" keeps its name: (1) 2 reports within 0.6 m; (2) 8 of 9 stations; (3) 3497.6 m, NPD 3497 m.
#: The Baker Hughes server (2013 onwards) uses the NPD names: its "NO 15/9-F-15 C" is DDR 15/9-F-15 C.
WELLBORE_BY_UID = {
"B-744206": "15/9-F-15",
"B-826806": "15/9-F-15 A",
"B-861401": "15/9-F-15 C",
}
_MAIN = re.compile(r"\s*-\s*Main Wellbore$")
def published_wellbore(name_well: str, name_wellbore: str) -> tuple[str, str]:
"""(canonical wellbore as published, source). The name comes from `nameWellbore` ("15/9-F-15A - Main
Wellbore", "NO 15/9-F-11 T2"); when that is not a wellbore name ("EcoScope_Customer_Run5", "test") it falls
back to `nameWell` and says so."""
try:
return canonical(_MAIN.sub("", name_wellbore or "")), "nameWellbore"
except ValueError:
return canonical(name_well), "nameWell"
def wellbore_name(name_well: str, name_wellbore: str, uid_wellbore: str | None = None) -> tuple[str, str]:
"""(DDR wellbore, source): `WELLBORE_BY_UID` first, else the published name."""
if uid_wellbore in WELLBORE_BY_UID:
return WELLBORE_BY_UID[uid_wellbore], "uidWellbore"
return published_wellbore(name_well, name_wellbore)
def wellbore_dir(wellbore: str) -> str:
"""File name of a wellbore in the parquet tree: '15/9-F-11 T2' -> '15_9_F_11_T2'."""
return stem(wellbore)
def _tag(e: ET.Element) -> str:
return e.tag.replace(NS, "")
# --------------------------------------------------------------------------------------------------------------
# log: reading
# --------------------------------------------------------------------------------------------------------------
@dataclass
class LogFile:
"""One chunk file of a log: header leaves, logCurveInfo rows, and the raw comma-separated data rows."""
header: dict
curves: list[dict]
mnemonics: list[str]
units: list[str]
rows: list[str]
def read_log_file(source, header_only: bool = False) -> LogFile:
"""Stream one `<logs><log>` file (path or binary file object). `logData/data` rows are kept as text.
With `header_only` the parse stops at the first logCurveInfo (enough to name the wellbore)."""
header: dict = {}
curves: list[dict] = []
mnemonics: list[str] = []
units: list[str] = []
rows: list[str] = []
stack: list[str] = []
n_logs = 0
for event, e in ET.iterparse(source, events=("start", "end")):
tag = _tag(e)
if event == "start":
stack.append(tag)
if tag == "log":
n_logs += 1
header.update(e.attrib)
elif header_only and tag in ("logCurveInfo", "logData"):
return LogFile(header, curves, mnemonics, units, rows)
continue
stack.pop()
parent = stack[-1] if stack else ""
if tag == "data":
rows.append(e.text or "")
e.clear()
elif tag == "logCurveInfo":
c = {"uid": e.attrib.get("uid")}
for child in e:
c[_tag(child)] = (child.text or "").strip()
if "uom" in child.attrib:
c[_tag(child) + "_uom"] = child.attrib["uom"]
curves.append(c)
e.clear()
elif tag == "mnemonicList":
mnemonics = [m.strip() for m in (e.text or "").split(",")]
elif tag == "unitList":
units = [u.strip() for u in (e.text or "").split(",")]
elif parent == "log" and len(e) == 0:
header[tag] = (e.text or "").strip()
if "uom" in e.attrib:
header[tag + "_uom"] = e.attrib["uom"]
elif parent == "commonData" and tag not in DROPPED:
header["commonData_" + tag] = (e.text or "").strip()
if n_logs != 1:
raise ValueError(f"{source}: {n_logs} log elements, expected 1")
return LogFile(header, curves, mnemonics, units, rows)
def _split(rows: list[str], n_cols: int) -> tuple[pa.Table, int]:
"""Comma-separated rows -> a table of string columns c0..cN. Rows with another field count are dropped and
counted (WITSML 1.4.1 has no quoting, so a text value with a comma would break its row)."""
bad = [0]
def on_invalid(row) -> str:
bad[0] += 1
return "skip"
data = "\n".join(r.replace("\n", " ").replace("\r", " ") for r in rows).encode("utf-8")
names = [f"c{i}" for i in range(n_cols)]
table = pacsv.read_csv(
io.BytesIO(data),
read_options=pacsv.ReadOptions(column_names=names, block_size=max(len(data) + 16, 1 << 20),
use_threads=False),
parse_options=pacsv.ParseOptions(delimiter=",", quote_char=False, escape_char=False,
newlines_in_values=False, ignore_empty_lines=False,
invalid_row_handler=on_invalid),
convert_options=pacsv.ConvertOptions(column_types={n: pa.string() for n in names},
strings_can_be_null=True, null_values=[""]),
)
return table, bad[0]
def _objects(col: pa.ChunkedArray) -> np.ndarray:
out = np.empty(len(col), dtype=object)
out[:] = col.to_pylist()
return out
def _numbers(col: pa.ChunkedArray) -> tuple[np.ndarray, np.ndarray | None, int]:
"""A string column -> (float64 values, NaN where missing; texts of the cells that are not numbers, or None;
number of such cells)."""
try:
return pc.cast(col, pa.float64()).to_numpy(zero_copy_only=False), None, 0
except pa.ArrowInvalid:
raw = _objects(col)
out = np.full(len(raw), np.nan)
text = np.full(len(raw), None, dtype=object)
bad = 0
for i, s in enumerate(raw):
if s is None:
continue
try:
out[i] = float(s)
except ValueError:
text[i], bad = s, bad + 1
return out, text, bad
def parse_time_index(col: pa.ChunkedArray) -> np.ndarray:
"""ISO 8601 strings ending in "Z" -> int64 milliseconds since the epoch (UTC). Raises on anything else."""
if not pc.all(pc.ends_with(col, "Z")).as_py():
raise ValueError("a time index value does not end in 'Z'")
t = pd.to_datetime(col.to_pandas(), utc=True, format="ISO8601")
return t.dt.as_unit("ms").astype("int64").to_numpy()
def _float_or_none(s) -> float | None:
try:
return float(s) if s not in (None, "") else None
except ValueError:
return None
@dataclass
class CurveData:
"""Values of one curve of one log, one list entry per chunk file, in file order."""
index: list = field(default_factory=list) # int64 ms since the epoch, or float64 metres
value: list = field(default_factory=list) # float64, NaN where the value is text
text: list = field(default_factory=list) # object array or None
chunk: list = field(default_factory=list) # int16 source file number
has_text: bool = False
stats: collections.Counter = field(default_factory=collections.Counter)
@dataclass
class Curve:
"""One curve of one log after `dedup_curve`: sorted by index, one row per index value."""
log_id: int
mnemonic: str
index: np.ndarray
value: np.ndarray
text: np.ndarray | None
chunk: np.ndarray
stats: dict
class ParsedLog:
"""All chunk files of one log merged: header, curve table, and the values of every curve in file order."""
def __init__(self) -> None:
self.header: dict = {}
self.kind: str | None = None # "time" | "depth"
self.index_unit: str | None = None
self.curve_info: dict[str, dict] = {} # mnemonic -> logCurveInfo of the first chunk that has it
self.data: dict[str, CurveData] = {}
self.counts: collections.Counter = collections.Counter()
self.index_values: list[np.ndarray] = [] # the index column of every chunk, in file order
def add(self, lf: LogFile, chunk: int) -> None:
h = lf.header
if not self.header:
self.header = dict(h)
self.kind = INDEX_KINDS.get(h.get("indexType", ""))
if self.kind is None:
raise ValueError(f"unsupported indexType {h.get('indexType')!r}")
else:
for key in ("uid", "uidWellbore", "indexType", "indexCurve"):
if h.get(key) != self.header.get(key):
raise ValueError(f"chunk {chunk}: {key} changes inside one log: "
f"{self.header.get(key)!r} -> {h.get(key)!r}")
for c in lf.curves:
known = self.curve_info.setdefault(c["mnemonic"], c)
if known is not c and known.get("unit") != c.get("unit"):
raise ValueError(f"chunk {chunk}: unit of {c['mnemonic']} changes inside one log")
self.counts["files"] += 1
self.counts["rows"] += len(lf.rows)
if not lf.rows:
return
names = lf.mnemonics
index_curve = h.get("indexCurve", "")
if names.count(index_curve) != 1:
raise ValueError(f"chunk {chunk}: index curve {index_curve!r} is not exactly once in mnemonicList")
if len(set(names)) != len(names):
raise ValueError(f"chunk {chunk}: repeated mnemonic in mnemonicList")
table, bad = _split(lf.rows, len(names))
self.counts["bad_rows"] += bad
i_index = names.index(index_curve)
icol = table.column(i_index)
if icol.null_count:
raise ValueError(f"chunk {chunk}: {icol.null_count} rows without an index value")
if self.kind == "time":
index = parse_time_index(icol)
else:
unit = lf.units[i_index] if i_index < len(lf.units) else ""
if unit not in ("m", ""):
raise ValueError(f"chunk {chunk}: depth index in {unit!r}, expected metres")
self.index_unit = unit or self.index_unit
index = pc.cast(icol, pa.float64()).to_numpy(zero_copy_only=False)
self.index_values.append(index)
log_null = _float_or_none(h.get("nullValue"))
for j, name in enumerate(names):
if j == i_index:
continue
col = table.column(j)
n_valid = len(col) - col.null_count
if n_valid == 0:
continue
info = self.curve_info.get(name)
if info is None: # data for a curve without logCurveInfo
info = self.curve_info.setdefault(name, {"mnemonic": name, "undeclared": True,
"unit": lf.units[j] if j < len(lf.units) else None})
cd = self.data.setdefault(name, CurveData())
ltype = (info.get("typeLogData") or "").lower()
if ltype in NUMERIC_TYPES or not ltype:
values, text, n_bad = _numbers(col)
cd.stats["n_not_number"] += n_bad
keep = ~np.isnan(values)
cd.stats["n_nan"] += int(n_valid - n_bad - keep.sum()) # the literal "NaN"
null = _float_or_none(info.get("nullValue"))
null = log_null if null is None else null
if null is not None:
hit = keep & (values == null)
cd.stats["n_null_value"] += int(hit.sum())
keep &= ~hit
for s in SENTINELS:
hit = keep & (values == s)
if hit.any():
cd.stats[f"sentinel:{s:g}"] += int(hit.sum())
keep &= ~hit
for s in SUSPECT_VALUES:
n_hit = int((keep & (values == s)).sum())
if n_hit:
cd.stats[f"suspect:{s:g}"] += n_hit
n_hit = int((keep & (np.abs(values) > SUSPECT_HUGE)).sum())
if n_hit:
cd.stats["suspect:huge"] += n_hit
if text is not None:
keep |= np.array([t is not None for t in text])
cd.has_text = True
cd.text.append(text[keep])
else:
cd.text.append(None)
cd.value.append(values[keep])
else:
raw = _objects(col)
keep = np.array([s is not None for s in raw])
cd.has_text = True
cd.text.append(raw[keep])
cd.value.append(np.full(int(keep.sum()), np.nan))
cd.index.append(index[keep])
cd.chunk.append(np.full(int(keep.sum()), chunk, dtype=np.int16))
def index_stats(self) -> dict:
"""Row-level statistics of the index column over all chunks, in file order. Steps are in seconds for a
time log and metres for a depth log, between consecutive distinct index values."""
if not self.index_values:
return {"n_index_values": 0}
idx = np.concatenate(self.index_values)
uniq = np.unique(idx)
ustep = np.diff(uniq) / (1000.0 if self.kind == "time" else 1.0)
return {
"n_index_values": int(len(idx)),
"n_index_distinct": int(len(uniq)),
"n_index_backwards": int((np.diff(idx) < 0).sum()),
"index_min": idx.min(), "index_max": idx.max(),
"step_median": float(np.median(ustep)) if len(ustep) else None,
"step_p10": float(np.quantile(ustep, 0.1)) if len(ustep) else None,
"step_p90": float(np.quantile(ustep, 0.9)) if len(ustep) else None,
}
def curves(self, log_id: int = 0) -> list[Curve]:
"""Every curve with data, de-duplicated on the index (`dedup_curve`) and sorted by it."""
out = []
for name in sorted(self.data):
cd = self.data[name]
index, value, chunk = np.concatenate(cd.index), np.concatenate(cd.value), np.concatenate(cd.chunk)
text = None
if cd.has_text:
text = np.concatenate([t if t is not None else np.full(len(v), None, dtype=object)
for t, v in zip(cd.text, cd.value)])
index, value, text, chunk, dd = dedup_curve(index, value, text, chunk)
stats = dict(cd.stats)
stats.update(dd)
stats["n_values"] = int(len(index))
stats["n_text"] = int(sum(t is not None for t in text)) if text is not None else 0
out.append(Curve(log_id, name, index, value, text, chunk, stats))
return out
def parse_log(files: list[Path]) -> ParsedLog:
"""All chunk files of one log, in file-name order (00001.xml, 00002.xml, ...)."""
log = ParsedLog()
for f in sorted(files):
log.add(read_log_file(f), int(f.stem))
return log
def find_logs(root: Path) -> list[tuple[str, str, Path, list[Path]]]:
"""(well folder, wellbore subfolder, log directory, chunk files) of every log under `root`, sorted."""
out = []
for d in sorted(p for p in root.glob("*/*/log/*/*/*") if p.is_dir()):
files = sorted(d.glob("*.xml"))
if files:
rel = d.relative_to(root).parts
out.append((rel[0], rel[1], d, files))
return out
# --------------------------------------------------------------------------------------------------------------
# log: duplicates
# --------------------------------------------------------------------------------------------------------------
def _same(value_a: np.ndarray, value_b: np.ndarray, text_a, text_b) -> np.ndarray:
same = (value_a == value_b) | (np.isnan(value_a) & np.isnan(value_b))
if text_a is not None:
same &= text_a == text_b
return same
def dedup_curve(index: np.ndarray, value: np.ndarray, text: np.ndarray | None, chunk: np.ndarray):
"""De-duplicate one curve of one log on its index. Rows are sorted by index (stable, so file order breaks
ties). Among rows with the same index the *last* row in file order is kept and the others are dropped. A
dropped row is counted in `n_dup_same` if the row after it has the same value, else in `n_dup_conflict` (a
WITSML store appends corrections, so the later row is the one the server would return).
In the Volve logs every such row is a plain repeat (`n_dup_conflict` is 0 in all 2,047 logs): the last row of
a chunk file is repeated as the first row of the next file, and one log was stored twice.
Returns (index, value, text, chunk, counts); `n_out_of_order` counts the rows that had to move."""
n = len(index)
order = np.argsort(index, kind="stable")
moved = order != np.arange(n)
if moved.any():
index, value, chunk = index[order], value[order], chunk[order]
text = text[order] if text is not None else None
counts = {"n_dup_same": 0, "n_dup_conflict": 0, "n_out_of_order": int(moved.sum())}
if n < 2:
return index, value, text, chunk, counts
same_index = index[1:] == index[:-1]
if not same_index.any():
return index, value, text, chunk, counts
same_value = _same(value[1:], value[:-1], None if text is None else text[1:], None if text is None else text[:-1])
keep = np.ones(n, dtype=bool)
keep[:-1] = ~same_index # the last row of every run of equal index
counts["n_dup_same"] = int((same_index & same_value).sum())
counts["n_dup_conflict"] = int((same_index & ~same_value).sum())
return index[keep], value[keep], text[keep] if text is not None else None, chunk[keep], counts
#: Two colliding values that differ by at most this (relative to max(1, |value|)) are "rounding": memory logs
#: publish 4-5 decimals where the real-time log publishes float32 values with all their digits.
ROUNDING = 1e-4
def merge_curve(curves: list[Curve]):
"""All logs of one wellbore that publish the same mnemonic -> one series sorted by index, every row kept.
A mnemonic is only unique inside a log (the Baker Hughes `Depth` curve is the reference depth of its own
log), so rows of different logs with the same index are *not* dropped. They are ranked: `dup_rank` is 0 for
the row of the preferred log and 1, 2, ... for the others. The preferred log is the one with the most values
of this curve in the wellbore (the main record; ties: lower log_id). Keeping `dup_rank = 0` gives at most one
value per (wellbore, mnemonic, index).
Returns (log_id, index, value, text, chunk, dup_rank, overlaps); `overlaps` has one row per pair (preferred
log, other log): colliding index values, how many values are identical, differ by rounding, or conflict, and
the largest absolute difference."""
curves = sorted(curves, key=lambda c: (-len(c.index), c.log_id))
index = np.concatenate([c.index for c in curves])
value = np.concatenate([c.value for c in curves])
chunk = np.concatenate([c.chunk for c in curves])
log_id = np.concatenate([np.full(len(c.index), c.log_id, dtype=np.int32) for c in curves])
text = None
if any(c.text is not None for c in curves):
text = np.concatenate([c.text if c.text is not None else np.full(len(c.index), None, dtype=object)
for c in curves])
n = len(index)
rank = np.zeros(n, dtype=np.int8)
if len(curves) == 1:
return log_id, index, value, text, chunk, rank, []
order = np.argsort(index, kind="stable") # stable: the preferred log comes first in a tie
index, value, chunk, log_id = index[order], value[order], chunk[order], log_id[order]
text = text[order] if text is not None else None
new_run = np.ones(n, dtype=bool)
new_run[1:] = index[1:] != index[:-1]
if new_run.all():
return log_id, index, value, text, chunk, rank, []
first = np.flatnonzero(new_run)[np.cumsum(new_run) - 1] # position of the preferred row
position = np.arange(n) - first
rank = np.minimum(position, 127).astype(np.int8)
dup = position > 0
va, vb = value[first[dup]], value[dup]
same = _same(va, vb, None if text is None else text[first[dup]], None if text is None else text[dup])
with np.errstate(invalid="ignore"):
diff = np.abs(va - vb)
rounding = ~same & (diff <= ROUNDING * np.maximum(1.0, np.abs(va)))
pairs = pd.DataFrame({"log_id": log_id[first[dup]], "other_log_id": log_id[dup], "same": same,
"rounding": rounding, "conflict": ~same & ~rounding, "diff": np.where(same, 0.0, diff)})
g = pairs.groupby(["log_id", "other_log_id"], sort=True)
overlaps = g.agg(n=("same", "size"), n_same=("same", "sum"), n_rounding=("rounding", "sum"),
n_conflict=("conflict", "sum"), max_abs_diff=("diff", "max")).reset_index()
return log_id, index, value, text, chunk, rank, overlaps.to_dict("records")
def log_schema(kind: str) -> pa.Schema:
index = ("time", pa.timestamp("ms", tz="UTC")) if kind == "time" else ("md", pa.float64())
return pa.schema([("wellbore", pa.dictionary(pa.int32(), pa.string())), ("log_id", pa.int32()),
("mnemonic", pa.dictionary(pa.int32(), pa.string())), index, ("value", pa.float64()),
("text", pa.string()), ("chunk", pa.int16()), ("dup_rank", pa.int8())])
class LongWriter:
"""Writes the long log table of one wellbore, curve after curve (so the file is sorted by mnemonic, index).
The time index is delta-encoded, so a regular sampling costs almost nothing; the file takes about one byte
per value. Small curves are buffered into row groups of about a million rows."""
ROW_GROUP = 1 << 20
def __init__(self, path: Path, kind: str, wellbore: str, mnemonics: list[str]) -> None:
self.path, self.kind, self.schema = path, kind, log_schema(kind)
self.wellbores, self.mnemonics = pa.array([wellbore]), pa.array(sorted(mnemonics))
self.codes = {m: i for i, m in enumerate(sorted(mnemonics))}
self.buffer: list[pa.Table] = []
self.buffered = self.rows = 0
path.parent.mkdir(parents=True, exist_ok=True)
self.tmp = path.with_suffix(".parquet.tmp")
self.writer = pq.ParquetWriter(
self.tmp, self.schema, compression="zstd", compression_level=9,
use_dictionary=["wellbore", "mnemonic", "log_id", "chunk", "text", "dup_rank"],
column_encoding={"time": "DELTA_BINARY_PACKED"} if kind == "time" else None)
def write(self, mnemonic: str, log_id, index, value, text, chunk, dup_rank) -> None:
n = len(index)
if n == 0:
return
zeros = pa.array(np.zeros(n, dtype=np.int32))
idx = pa.array(index, type=pa.int64()).cast(pa.timestamp("ms", tz="UTC")) if self.kind == "time" \
else pa.array(index, type=pa.float64())
table = pa.Table.from_arrays([
pa.DictionaryArray.from_arrays(zeros, self.wellbores), pa.array(log_id, type=pa.int32()),
pa.DictionaryArray.from_arrays(pa.array(np.full(n, self.codes[mnemonic], dtype=np.int32)), self.mnemonics),
idx, pa.array(value, mask=np.isnan(value)),
pa.array(text, type=pa.string()) if text is not None else pa.nulls(n, pa.string()),
pa.array(chunk, type=pa.int16()), pa.array(dup_rank, type=pa.int8())], schema=self.schema)
self.buffer.append(table)
self.buffered += n
self.rows += n
if self.buffered >= self.ROW_GROUP:
self._flush()
def _flush(self) -> None:
if self.buffer:
self.writer.write_table(pa.concat_tables(self.buffer), row_group_size=self.ROW_GROUP)
self.buffer, self.buffered = [], 0
def close(self) -> None:
self._flush()
self.writer.close()
self.tmp.replace(self.path)
# --------------------------------------------------------------------------------------------------------------
# trajectory, message, bhaRun, mudLog
# --------------------------------------------------------------------------------------------------------------
class Flat:
"""Flattens WITSML elements into rows and counts sentinels and units per (table, column)."""
def __init__(self) -> None:
self.sentinels: collections.Counter = collections.Counter() # (table, column, value) -> n
self.units: collections.Counter = collections.Counter() # (table, column, uom published) -> n
def value(self, e: ET.Element, table: str, column: str):
text = (e.text or "").strip()
if "uom" not in e.attrib:
return text or None
uom = e.attrib["uom"]
if not text:
return None
v = float(text)
extra = [s for (t, prefix), s in EXTRA_SENTINELS.items() if t == table and column.startswith(prefix)]
if v in SENTINELS or v in extra:
self.sentinels[(table, column, v)] += 1
return None
self.units[(table, column, uom)] += 1
return v * STORED_UNITS[uom][1] if uom in STORED_UNITS else v
def leaves(self, elem: ET.Element, row: dict, table: str, prefix: str = "", skip: tuple[str, ...] = ()) -> dict:
"""Leaves of `elem` into `row`; a nested element prefixes its leaves with its tag (numbered from the second
occurrence on). `uid` and `uidRef` attributes become `<tag>_uid` and `<tag>_uidRef` columns."""
seen: collections.Counter = collections.Counter()
for child in elem:
tag = _tag(child)
if tag in skip or tag in DROPPED:
continue
if len(child) == 0:
column = prefix + tag
if column in row:
raise ValueError(f"{table}: repeated leaf {column}")
row[column] = self.value(child, table, column)
if "uidRef" in child.attrib:
row[column + "_uidRef"] = child.attrib["uidRef"]
else:
seen[tag] += 1
nested = f"{prefix}{tag}{seen[tag] if seen[tag] > 1 else ''}_"
if "uid" in child.attrib:
row[nested + "uid"] = child.attrib["uid"]
self.leaves(child, row, table, nested, skip)
return row
def _object(path: Path, plural: str, singular: str) -> ET.Element:
root = ET.parse(path).getroot()
if _tag(root) != plural or len(root) != 1 or _tag(root[0]) != singular:
raise ValueError(f"{path}: expected one {singular} in {plural}")
return root[0]
def _ids(obj: ET.Element, path: Path, root: Path) -> dict:
rel = path.relative_to(root)
name_well, name_wellbore = obj.findtext(NS + "nameWell") or "", obj.findtext(NS + "nameWellbore") or ""
wb, source = wellbore_name(name_well, name_wellbore, obj.attrib.get("uidWellbore"))
return {"wellbore": wb, "wellbore_source": source,
"wellbore_witsml": published_wellbore(name_well, name_wellbore)[0], "folder": rel.parts[0],
"path": rel.as_posix(), "uidWell": obj.attrib.get("uidWell"),
"uidWellbore": obj.attrib.get("uidWellbore"), "uid": obj.attrib.get("uid")}
def _utc(s: pd.Series) -> pd.Series:
return pd.to_datetime(s, utc=True, format="ISO8601")
def parse_objects(root: Path) -> tuple[dict[str, pd.DataFrame], Flat]:
"""trajectory, message, bhaRun and mudLog files under `root` -> tables `trajectory_catalog` (one row per
trajectory), `trajectory` (stations), `messages`, `bha_runs`, `mudlog_catalog`, `mudlog_intervals`,
`mudlog_lithology`, `mudlog_qualifiers`. UTC timestamps are added next to the published time strings."""
flat = Flat()
rows: dict[str, list[dict]] = {k: [] for k in (
"trajectory_catalog", "trajectory", "messages", "bha_runs", "mudlog_catalog", "mudlog_intervals",
"mudlog_lithology", "mudlog_qualifiers")}
for path in sorted(root.glob("*/*/trajectory/*.xml")):
obj = _object(path, "trajectorys", "trajectory")
ids = _ids(obj, path, root)
head = flat.leaves(obj, dict(ids), "trajectory_catalog", skip=("trajectoryStation",))
stations = obj.findall(NS + "trajectoryStation")
head["n_stations"] = len(stations)
rows["trajectory_catalog"].append(head)
for seq, st in enumerate(stations):
row = {"wellbore": ids["wellbore"], "path": ids["path"], "traj_uid": ids["uid"],
"traj_name": head.get("name"), "seq": seq, "uid": st.attrib.get("uid")}
rows["trajectory"].append(flat.leaves(st, row, "trajectory"))
for path in sorted(root.glob("*/*/message/*.xml")):
obj = _object(path, "messages", "message")
rows["messages"].append(flat.leaves(obj, _ids(obj, path, root), "messages"))
for path in sorted(root.glob("*/*/bhaRun/*.xml")):
obj = _object(path, "bhaRuns", "bhaRun")
rows["bha_runs"].append(flat.leaves(obj, _ids(obj, path, root), "bha_runs"))
for path in sorted(root.glob("*/*/mudLog/*.xml")):
obj = _object(path, "mudLogs", "mudLog")
ids = _ids(obj, path, root)
head = flat.leaves(obj, dict(ids), "mudlog_catalog", skip=("geologyInterval",))
intervals = obj.findall(NS + "geologyInterval")
head["n_intervals"] = len(intervals)
rows["mudlog_catalog"].append(head)
for seq, gi in enumerate(intervals):
base = {"wellbore": ids["wellbore"], "path": ids["path"], "mudlog_uid": ids["uid"], "seq": seq,
"uid": gi.attrib.get("uid")}
row = flat.leaves(gi, dict(base), "mudlog_intervals", skip=("lithology",))
liths = gi.findall(NS + "lithology")
row["n_lithology"] = len(liths)
rows["mudlog_intervals"].append(row)
for lseq, lith in enumerate(liths):
lrow = {"wellbore": ids["wellbore"], "mudlog_uid": ids["uid"], "interval_uid": base["uid"],
"interval_seq": seq, "seq": lseq, "uid": lith.attrib.get("uid")}
rows["mudlog_lithology"].append(flat.leaves(lith, lrow, "mudlog_lithology", skip=("qualifier",)))
for qseq, q in enumerate(lith.findall(NS + "qualifier")):
qrow = {"wellbore": ids["wellbore"], "mudlog_uid": ids["uid"], "interval_uid": base["uid"],
"lithology_uid": lrow["uid"], "seq": qseq, "uid": q.attrib.get("uid")}
rows["mudlog_qualifiers"].append(flat.leaves(q, qrow, "mudlog_qualifiers"))
tables = {name: pd.DataFrame(r) for name, r in rows.items()}
for table, column in (("trajectory", "dTimStn"), ("messages", "dTim"), ("bha_runs", "dTimStart"),
("bha_runs", "dTimStop"), ("mudlog_intervals", "dTim")):
if column in tables[table]:
tables[table][column + "_utc"] = _utc(tables[table][column])
if len(tables["mudlog_intervals"]):
tables["mudlog_intervals"]["tadi_implausible"] = tadi_implausible(tables["mudlog_intervals"])
return tables, flat
def tadi_implausible(intervals: pd.DataFrame) -> pd.Series:
"""True where TADI (section 3.3) would drop a mudLog interval: ROP > 200 m/h, RPM > 300 or WOB > 500 kN.
A flag only; the values stay as published."""
out = pd.Series(False, index=intervals.index)
for column, limit in TADI_FILTERS.items():
if column in intervals:
out |= intervals[column] > limit
return out
def units_table(flat: Flat) -> pd.DataFrame:
"""(table, column, uom published, n values, uom stored, factor) for every measure of the object tables.
Refuses a column that would be stored in more than one unit."""
rows = []
for (table, column, uom), n in sorted(flat.units.items()):
stored, factor = STORED_UNITS.get(uom, (uom, 1.0))
rows.append({"table": table, "column": column, "uom": uom, "n": n, "uom_stored": stored, "factor": factor})
out = pd.DataFrame(rows, columns=["table", "column", "uom", "n", "uom_stored", "factor"])
mixed = out.groupby(["table", "column"])["uom_stored"].nunique()
if (mixed > 1).any():
raise ValueError(f"columns stored in more than one unit: {mixed[mixed > 1].index.tolist()}")
return out
def sentinels_table(flat: Flat) -> pd.DataFrame:
return pd.DataFrame([{"table": t, "column": c, "value": v, "n": n, "kind": "sentinel"}
for (t, c, v), n in sorted(flat.sentinels.items())],
columns=["table", "column", "value", "n", "kind"])
# --------------------------------------------------------------------------------------------------------------
# DuckDB views over the long log tables
# --------------------------------------------------------------------------------------------------------------
def depth_filter(channels: dict) -> str:
return " OR ".join(f"(d.mnemonic = '{m}'" + (f" AND c.name = '{name}')" if name else ")")
for m, name in channels.items())
def view_sql(out: Path) -> dict[str, str]:
"""SELECT statements of the views over `<out>/time_log/*.parquet` and `<out>/depth_log/*.parquet`:
`time_log`, `depth_log` every published value;
`time_log_dedup`, `depth_log_dedup` one value per (wellbore, mnemonic, index): the rows with dup_rank = 0.
Not for the Baker Hughes `Depth` curve, which is the reference
depth of its own log (9.0 of its 15.0 million collisions between logs
disagree): select it by log, or use `drill_depth`;
`drill_depth` hole depth and bit depth against time (`HOLE_DEPTH`, `BIT_DEPTH`), one
value per (wellbore, time, depth): the log with the most values wins.
"""
hole, bit = depth_filter(HOLE_DEPTH), depth_filter(BIT_DEPTH)
mnemonics = ", ".join(repr(m) for m in (*HOLE_DEPTH, *BIT_DEPTH))
views = {}
for kind in ("time", "depth"):
views[f"{kind}_log"] = f"SELECT * FROM read_parquet('{(Path(out) / f'{kind}_log').as_posix()}/*.parquet')"
views[f"{kind}_log_dedup"] = f"SELECT * EXCLUDE (dup_rank) FROM {kind}_log WHERE dup_rank = 0"
views["drill_depth"] = f"""
SELECT wellbore, time, depth, first(value ORDER BY n_values DESC, log_id) AS md,
first(log_id ORDER BY n_values DESC, log_id) AS log_id
FROM (SELECT d.wellbore, d.time, d.value, d.log_id, c.n_values,
CASE WHEN {hole} THEN 'hole' ELSE 'bit' END AS depth
FROM time_log d JOIN log_catalog c USING (log_id)
WHERE d.mnemonic IN ({mnemonics}) AND d.value IS NOT NULL AND ({hole} OR {bit}))
GROUP BY wellbore, time, depth"""
return views
def connect(out: Path | None = None):
"""Read-only connection to `volve_witsml.duckdb`. The log views stored in the file name the parquet files by
the absolute path they had when the file was built; here they are redefined (as temporary views) over the
files next to the database, so the tables also work after the outputs folder was moved or copied."""
import duckdb
from . import paths
out = Path(out) if out else paths.outputs_dir() / "witsml"
con = duckdb.connect(str(out / "volve_witsml.duckdb"), read_only=True)
for name, sql in view_sql(out.resolve()).items():
con.execute(f"CREATE OR REPLACE TEMP VIEW {name} AS {sql}")
return con