Compare commits
4 Commits
8cb55a3153
...
5f780bab67
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f780bab67 | |||
| 4a1011f5e1 | |||
| 23e15ee27e | |||
| fd1440b0c0 |
28
AGENTS.md
28
AGENTS.md
@@ -64,7 +64,7 @@ Read first: `docs/plan.md` (plan, gates, decisions; §1 data facts, §6 roadmap,
|
||||
coverage (`scripts/16_m34_session.py prepare|regroup|status|collect`, batches of 15 T4 / 50 T2 items with `.txt` copies because
|
||||
Read returns about 42k characters). `configs/protocol_v2.yaml` (+ `.sha256`) extends v1; never edit it while the VAI run
|
||||
exists (its SHA is in every checkpoint). `g2` (v1) cannot be met; `g2_v2` needs VAI complete plus the v1 comparison baselines.
|
||||
Track runs with `bash scripts/m34_status.sh`. 168 tests (20/11).
|
||||
Track runs with `bash scripts/m34_status.sh`. 204 tests (20/11).
|
||||
- **G2 v2 passed on 20/11/2026** (`outputs/m34/report.json` refreshed 06:32 UTC): `g2_v2.passed` True with no missing
|
||||
classification or QA cells; `g2` (v1) False as expected. C4 coverage 1,376 paired questions, 1,293 without date-flagged
|
||||
pages; `sha256sum -c configs/protocol_v2.yaml.sha256` OK. Headline T4 macro-family accuracy (well-scoped, mean of 3
|
||||
@@ -92,14 +92,34 @@ Read first: `docs/plan.md` (plan, gates, decisions; §1 data facts, §6 roadmap,
|
||||
agent − tool_only −0.08 to −0.12 (agent is worse); OCR − XML +0.02 to +0.04 (includes 0, so H5 is not supported on T4).
|
||||
Wrong-wellbore rate: RAG 0.30, C4 HTML/OCR 0.36–0.38, C4 XML 0.20, tool modes about 0.05. Code leakage T2(b): TF-IDF
|
||||
+0.531, DistilBERT +0.27 to +0.29; T3 about 0. DeepSeek − TF-IDF on T2 −0.055 (CI includes 0). Qwen is partial v1, seed 0.
|
||||
- **Protocol v4: error taxonomy and RQ4 done (20/11/2026, plan §1.7, §12 item 35).** `configs/protocol_v4.yaml` (+ `.sha256`,
|
||||
extends v3; never edit it) was locked before any error class or EGS value was computed. `scripts/19_m5_errors.py`
|
||||
(`volve_dia/m5_errors.py`, 24 tests) writes `outputs/m5/errors/` from complete DeepSeek reps 0–2 (primary) and Qwen v1
|
||||
seed 0 (partial), well-scoped questions. One class per prediction, first rule wins. DeepSeek macro shares (mean of 3 reps):
|
||||
abstention dominates text retrieval (C4 XML 0.678, HTML 0.535, OCR 0.580, RAG 0.638, zero-shot 0.891), then wrong
|
||||
wellbore (0.095–0.190). Tool modes mostly err with the right report cited but a wrong value (0.14–0.15), and agent has
|
||||
6.4% call failures. Aggregation and multi_hop are near 0 with text but about 0.72 with tool_only. For comparison
|
||||
questions the answer is a wellbore, so a wrong pick counts as wrong wellbore. EGS is adapted to the JSON answer format:
|
||||
number with a TADI unit plus a cited known DDR report, sections 0. Pooled Spearman with the automatic score is 0.538 /
|
||||
0.535 / 0.535, so H4 (weak correlation) is not supported. Accuracy at EGS 0 / 1/3 / 2/3 is 0.01 / 0.22 / 0.67. Without
|
||||
abstentions ρ is about 0.23, and within tool_only ρ is 0.07: EGS mostly separates answers from abstentions. Qwen ρ is 0.33.
|
||||
- **Protocol v5: T5 similar-interval retrieval done (20/11/2026, plan §1.8, §12 item 36).** `configs/protocol_v5.yaml`
|
||||
(+ `.sha256`, extends v4; never edit it) was locked before any retrieval score; only relevance-label counts were seen.
|
||||
`scripts/20_m5_t5.py` (`volve_dia/m5_t5.py`, 12 tests) writes `outputs/m5/t5/`. Items: own-hole T3 intervals with a known
|
||||
T1 section and formation (NPT b 410, a 373; 19 wellbores, 10 wells). Gain g = same section + same formation + shared cause
|
||||
(0–3). Candidates from other wells (primary) or other wellbores (sensitivity). No representation reads codes, causes,
|
||||
labels, section or formation. NPT (b) nDCG@10: random 0.463, depth 0.666, witsml_pre 0.495, text_pre 0.611, text_event
|
||||
0.528, rrf_pre 0.670 (+0.004 vs depth, CI −0.010–0.018), rrf_all 0.661. Depth is the strongest single baseline because
|
||||
section and formation follow depth in one field; cause overlap barely moves (0.70 random, 0.75 best). Neighbour forecast
|
||||
over 4,894 T3 cells (k = 10, other wells): AP 0.150 (0.116–0.204) by depth, 0.135 with WITSML, prevalence 0.114.
|
||||
T5 is outside G2 and stays a diagnostic.
|
||||
|
||||
## Next
|
||||
|
||||
Roadmap and gates: `docs/plan.md` §6, §12 item 1.
|
||||
|
||||
1. G2 v2 and G3 passed (20/11). Next in M5: error taxonomy by question family and the EGS correlation with the
|
||||
automatic score (RQ4); T4 headline numbers stay automatic. Then paper writing (M6) and release terms at G4. No claim
|
||||
of a human, author or expert audit is allowed.
|
||||
1. G2 v2, G3, the error taxonomy, RQ4 and T5 are done (20/11). Next: paper writing (M6) and release
|
||||
terms at G4. T4 headline numbers stay automatic. No claim of a human, author or expert audit is allowed.
|
||||
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; G1 locked NPT (b) (+0.025 median weighted κ in the first pass).
|
||||
4. At G4, confirm the release terms for this copy. Local `license.txt` states CC BY-NC-SA 4.0 and no resale,
|
||||
|
||||
36
README.md
36
README.md
@@ -158,7 +158,39 @@ Judge (Sonnet chính, Haiku độ nhạy) là subagent trong session: mỗi judg
|
||||
`outputs/m5/judge/batches/batch_NN.txt` và ghi `outputs/m5/judge/answers/<model>/batch_NN.json`. `prepare` không chạy lại
|
||||
khi mẫu đã có; `collect` kiểm checksum protocol v3, hash mẫu và hash prompt. **G3 đạt ngày 20/11/2026:** Sonnet κ = 0,98
|
||||
(CI 95% 0,947–1,0), Haiku 0,90 so với điểm tự động. Đây là độ nhất quán với bộ chấm tự động, không phải khớp với người;
|
||||
số chính của T4 vẫn là điểm tự động ([plan §1.7](docs/plan.md#17-m5-g3-và-phân-tích-kết-quả-cuối-ngày-20112026)).
|
||||
số chính của T4 vẫn là điểm tự động ([plan §1.7](docs/plan.md#17-m5-g3-phân-tích-kết-quả-cuối-phân-loại-lỗi-và-rq4-ngày-20112026)).
|
||||
|
||||
## Phân loại lỗi và RQ4 (M5, protocol v4)
|
||||
|
||||
`configs/protocol_v4.yaml` (khóa bằng `.sha256`, mở rộng v3) cố định luật phân loại lỗi theo họ câu hỏi và cách chuyển thể
|
||||
EGS của TADI cho câu trả lời JSON trước khi tính.
|
||||
|
||||
```bash
|
||||
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 \
|
||||
scripts/runlog.sh -n m5_errors -- .venv/bin/python scripts/19_m5_errors.py # khoảng 3 phút
|
||||
```
|
||||
|
||||
Script kiểm checksum v4 và digest đầu vào của mọi checkpoint, chỉ giữ các lượt đủ câu (DeepSeek ba lượt, Qwen v1 seed 0),
|
||||
rồi ghi `outputs/m5/errors/`: `report.json` (độ phủ, tỉ lệ macro, ρ Spearman và CI theo giếng, cách đọc H4),
|
||||
`taxonomy.csv` (TB ba lượt và khoảng), `taxonomy_by_run.csv`, `by_answer_type.csv`, `egs_by_run.csv`,
|
||||
`predictions.parquet`. Kết quả ngày 20/11: ρ EGS gộp 0,535–0,538, H4 không được ủng hộ
|
||||
([plan §1.7](docs/plan.md#17-m5-g3-phân-tích-kết-quả-cuối-phân-loại-lỗi-và-rq4-ngày-20112026)).
|
||||
|
||||
## T5 truy xuất khoảng tương đồng (M5, protocol v5)
|
||||
|
||||
`configs/protocol_v5.yaml` (khóa bằng `.sha256`, mở rộng v4) cố định mục, mức liên quan theo luật (cùng section + cùng
|
||||
formation + giao nhóm nguyên nhân), biểu diễn, metric và thống kê trước mọi điểm truy xuất.
|
||||
|
||||
```bash
|
||||
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 \
|
||||
scripts/runlog.sh -n m5_t5 -- .venv/bin/python scripts/20_m5_t5.py # khoảng 2 phút
|
||||
```
|
||||
|
||||
Script kiểm checksum v5, dựng các khoảng T3 đủ điều kiện (NPT b 410, a 373), tính nDCG@10, MRR, P@10 cho từng biểu diễn
|
||||
(random, depth, witsml_pre, text_pre, text_event, RRF) với CI bootstrap theo giếng, và dự báo khó khăn từ 10 ô láng giềng
|
||||
trên 4.894 ô T3. Kết quả ghi ở `outputs/m5/t5/`: `report.json`, `per_query.parquet`, `items_a.parquet`, `items_b.parquet`,
|
||||
`knn_scores.parquet`. Kết quả ngày 20/11: depth nDCG@10 0,666, random 0,463, không biểu diễn nào hơn depth với CI loại 0
|
||||
([plan §1.8](docs/plan.md#18-m5-t5-truy-xuất-khoảng-tương-đồng-ngày-20112026)).
|
||||
|
||||
## Ba phiên bản của một DDR và parser OCR
|
||||
|
||||
@@ -207,6 +239,8 @@ Dịch vụ OCR:
|
||||
| `scripts/11_m34_classify.py`, `12_m34_qa.py`, `13_m34_report.py`, `14_m34_t2_llm.py` | Dựng đặc trưng, dự đoán T1–T4/C4, Qwen zero-shot cho T2, chấm và tạo bảng độ phủ G2 |
|
||||
| `scripts/run_m34.sh` | Driver M3–M4 có runlog, gồm `prepare`, `classical`, `distilbert`, `qa`, `qa-local`, `t2-llm` và `report` |
|
||||
| `scripts/18_m5_judge.py prepare\|status\|collect` | Hiệu chuẩn LLM-judge cho G3 theo protocol v3 → `outputs/m5/judge/` (report.json, judged.csv, disagreements.csv) |
|
||||
| `scripts/19_m5_errors.py` | Phân loại lỗi theo họ câu hỏi và RQ4 (EGS so với điểm tự động) theo protocol v4 → `outputs/m5/errors/` |
|
||||
| `scripts/20_m5_t5.py` | T5 truy xuất khoảng tương đồng và dự báo từ láng giềng theo protocol v5 → `outputs/m5/t5/` |
|
||||
| `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 |
|
||||
|
||||
68
configs/protocol_v4.yaml
Normal file
68
configs/protocol_v4.yaml
Normal file
@@ -0,0 +1,68 @@
|
||||
# Protocol v4: M5 error taxonomy by question family and RQ4 (EGS against the automatic score). Extends locked v3.
|
||||
protocol: volve-dia
|
||||
version: 4
|
||||
status: locked
|
||||
drafted: 2026-11-20
|
||||
locked_before: any error-class count or EGS value was computed; only the G2 v2 headline metrics were known
|
||||
extends:
|
||||
file: configs/protocol_v3.yaml
|
||||
sha256: 61bc3e1d4f2e7840adb9e5c5fd14bd445c25b988666eca2217325ccda3001622
|
||||
deviation:
|
||||
date: 2026-11-20
|
||||
what: >-
|
||||
Protocols v1 to v3 list error analysis (M5) and RQ4 without fixing rules. v4 fixes both before computing them.
|
||||
TADI (arXiv 2605.00060, eq. 3) defines EGS = (1/3)(has_measurement + has_ddr_quote + sections_present/6) for a
|
||||
six-section narrative answer. The locked T4 baselines answer in a JSON object {answer, unit, citations} with no
|
||||
sections and no quoted text, so v4 adapts the two signals that can be observed and records the section term as 0.
|
||||
consequence: >-
|
||||
EGS here is an adaptation of TADI's proxy to the benchmark's answer format, not TADI's agent output. Its rank
|
||||
correlation with correctness is unaffected by the constant section term. Correctness is the automatic score
|
||||
against the XML answer; no human rater exists (plan section 12 item 20).
|
||||
unchanged:
|
||||
- protocols v1, v2 and v3 in full, including T4 automatic scoring, headline metrics, G2 and G3
|
||||
predictions:
|
||||
primary: VAI DeepSeek-V4.1-Flash-1017, repetitions 0, 1 and 2 (outputs/m34/v2/qa/vai-deepseek-v4-1-flash/rep*.sqlite)
|
||||
secondary: Qwen v1 seed 0 (outputs/m34/qa/qwen.sqlite), complete runs only, reported as partial v1
|
||||
complete_run: a (model, mode, source, seed) run whose item set equals the locked question set of that condition
|
||||
provenance: checkpoint input digests must equal the current M3-M4 input digests (as in the G2 report)
|
||||
universe: well-scoped questions (single and pair; the 10 field questions are excluded), as in the T4 headline
|
||||
error_taxonomy:
|
||||
unit: prediction
|
||||
rule: >-
|
||||
Each well-scoped prediction gets exactly one class, the first rule that matches, in this order. Answerable
|
||||
questions: correct; failed (call or parse failure); abstained (no answer to an answerable question); wrong_wellbore
|
||||
(the scorer's wrong_wellbore flag: a cited or named wellbore outside the question); no_citation (no citation);
|
||||
evidence_missed (citations, none of them an evidence report, report recall 0); wrong_with_evidence (at least one
|
||||
evidence report cited, answer still wrong). Unanswerable questions: correct (abstained); failed;
|
||||
answered_unanswerable.
|
||||
fields: the stored scorer fields failed, correct, wrong_wellbore and report_recall, and t4.is_abstention on the answer
|
||||
report: >-
|
||||
Share of each class among all predictions of a run, per family (lookup, aggregation, temporal_event, comparison,
|
||||
multi_hop) and macro over families (mean of family shares, as the headline); counts alongside. Primary numbers
|
||||
are the mean over the three DeepSeek repetitions with the per-repetition range. Cross-tabulation by answer type.
|
||||
Descriptive only: no test and no gate.
|
||||
rq4:
|
||||
egs:
|
||||
has_measurement: >-
|
||||
a number followed by a TADI drilling unit in the text "<answer> <unit>". Units, matched case-insensitively as
|
||||
a whole token after optional space: m, m/hr, kN, sg, g/cm3, mPa, Pa, ppm, hrs, days, %
|
||||
has_measurement_extended: >-
|
||||
sensitivity only: the TADI units plus h, hr, hour(s), metre(s), meter(s), mMD, mTVD, in, inch(es), ft, ft/h,
|
||||
deg, degree(s), bar, psi, pcf, degC
|
||||
has_ddr_quote: >-
|
||||
at least one citation that resolves to a known DDR report (the report id names the wellbore and the date);
|
||||
quoted text cannot be observed in the JSON answer format
|
||||
sections_present: 0 of 6 for every prediction (no sections in the answer format)
|
||||
formula: EGS = (has_measurement + has_ddr_quote + 0) / 3, so EGS takes the values 0, 1/3 and 2/3
|
||||
correctness: the stored automatic `correct` flag (failed predictions are excluded)
|
||||
universe: well-scoped answerable questions, failed predictions excluded; abstentions included (primary)
|
||||
sensitivity: [abstentions excluded, extended unit list]
|
||||
statistic: >-
|
||||
Spearman rank correlation between EGS and correctness over all modes and sources of one repetition (pooled), and
|
||||
within each (mode, source) run. 95% interval by whole-well cluster bootstrap, 2,000 resamples, seed 20261117.
|
||||
Accuracy at each EGS level is reported beside it.
|
||||
h4_reading: >-
|
||||
H4 (EGS correlates weakly with correctness) is supported if the pooled point rho of the primary model is below
|
||||
0.3 in absolute value in every repetition; a pooled rho of 0.3 or more in every repetition does not support it;
|
||||
otherwise mixed. Within-run rhos are reported, since pooling across modes mixes mode differences into rho.
|
||||
code: scripts/19_m5_errors.py, volve_dia/m5_errors.py
|
||||
1
configs/protocol_v4.yaml.sha256
Normal file
1
configs/protocol_v4.yaml.sha256
Normal file
@@ -0,0 +1 @@
|
||||
6a9ad0fb64e319b914427e4ec58c4cfafdca91b393da9309f9b30391a12568d0 configs/protocol_v4.yaml
|
||||
98
configs/protocol_v5.yaml
Normal file
98
configs/protocol_v5.yaml
Normal file
@@ -0,0 +1,98 @@
|
||||
# Protocol v5: T5 similar-interval retrieval (optional task of plan section 4). Extends locked v4.
|
||||
protocol: volve-dia
|
||||
version: 5
|
||||
status: locked
|
||||
drafted: 2026-11-20
|
||||
locked_before: >-
|
||||
any retrieval or forecasting score was computed; only relevance-label counts (eligible intervals per definition,
|
||||
well, section and formation, and the number of fully relevant candidates per query) were inspected
|
||||
extends:
|
||||
file: configs/protocol_v4.yaml
|
||||
sha256: 6a9ad0fb64e319b914427e4ec58c4cfafdca91b393da9309f9b30391a12568d0
|
||||
deviation:
|
||||
date: 2026-11-20
|
||||
what: >-
|
||||
Plan section 4 lists T5 as optional (embedding of WITSML, DDR and formation windows; nDCG@k, MRR; PR-AUC when
|
||||
trouble is forecast from neighbours; leave-one-wellbore-out; relevance by rule: same hole section, same formation,
|
||||
same NPT group). Protocols v1 to v4 do not define it. v5 fixes items, relevance, representations, metrics and
|
||||
statistics before any score. The primary candidate pool excludes the query's whole well, matching the primary
|
||||
grouping of v1; the plan's leave-one-wellbore-out pool is a sensitivity analysis.
|
||||
consequence: >-
|
||||
T5 is a diagnostic task outside G2. The relevance labels come from the XML-derived T3 intervals, the T1 section
|
||||
and the formation picks, all by code. No rater is involved and no gate depends on T5.
|
||||
unchanged:
|
||||
- protocols v1 to v4 in full, including masking, T3 labels and the T1-T4 headline metrics
|
||||
items:
|
||||
unit: T3 interval (outputs/labels/t3_intervals.parquet)
|
||||
primary_definition: b
|
||||
sensitivity_definition: a
|
||||
eligible: >-
|
||||
an interval of a T3 wellbore of protocol v1 (tasks.t3.wellbores) whose md_top lies in the own hole
|
||||
(md_top >= own_hole_top_md of that wellbore), whose section is known and whose formation is known
|
||||
section: >-
|
||||
t1_reports.section (published or forward-filled) of the report of the interval's first activity (the act_id
|
||||
that sorts first); intervals whose report has no section are not eligible
|
||||
formation: >-
|
||||
the unit of the deepest formation pick with md <= interval md_top among the picks of the DDR wellbore
|
||||
(outputs/witsml/formation_tops.parquet, column wellbore); the unit is case-folded and the words "volve" and
|
||||
"sand" and the suffixes "fm." and "gp." are removed, so "Hugin Fm. VOLVE" becomes "hugin" and "Heather Fm. Sand
|
||||
VOLVE" becomes "heather"; intervals above the first pick are not eligible
|
||||
cause_set: the pipe-separated causes of the interval (derived from codes by the T3 rule; never a model input)
|
||||
relevance:
|
||||
gain: g = [same section] + [same formation] + [cause sets intersect], so g takes the values 0 to 3
|
||||
fully_relevant: g = 3
|
||||
candidates:
|
||||
primary: every eligible interval of the same definition from the other wells (leave-one-well-out)
|
||||
sensitivity: every eligible interval of the same definition from the other wellbores (leave-one-wellbore-out)
|
||||
representations:
|
||||
rule: >-
|
||||
No representation reads activity codes, causes, labels, section or formation fields. Text is the masked
|
||||
activity comments of table t2_inputs. Hole sizes or depths named in the text are observable context, not code
|
||||
leakage (as in v1 t1_hole_size). Transformations (TF-IDF vocabulary and weights, imputation medians, z-scores)
|
||||
are fitted on the candidate pool of each held-out group, never on the query group.
|
||||
random: mean of each metric over 100 random orderings of the candidates (numpy default_rng, seed 20261117)
|
||||
depth: absolute difference of md_top (smaller is closer)
|
||||
witsml_pre: >-
|
||||
mean and population standard deviation of HKLD, ROP, RPM and SPPA in the 24 hours before the interval's
|
||||
first_start_utc (end excluded; suspect values missing as in v1), the same aggregation as the T3 features;
|
||||
missing values replaced by the candidate-pool median, z-scored on the pool, Euclidean distance
|
||||
text_pre: >-
|
||||
TF-IDF (word 1-2 grams, min_df 1, sublinear tf) of the masked comments of the same wellbore's activities that end
|
||||
in [first_start_utc - 24 h, first_start_utc), joined in time order; cosine similarity
|
||||
text_event: >-
|
||||
TF-IDF as above of the masked comments of the interval's own activities. This is a description view (query by
|
||||
example after the event), not a forecast, and is reported separately from the pre-event representations
|
||||
rrf_pre: reciprocal rank fusion, sum of 1 / (60 + rank), over depth, witsml_pre and text_pre
|
||||
rrf_all: reciprocal rank fusion over depth, witsml_pre, text_pre and text_event
|
||||
ties: equal scores are ordered by one fixed random order of the candidates (numpy default_rng, seed 20261117)
|
||||
metrics:
|
||||
primary: nDCG@10 with linear gain g; the ideal ranking sorts all candidates of the query by g
|
||||
secondary:
|
||||
- MRR of the first fully relevant candidate; queries without a fully relevant candidate are left out of MRR and
|
||||
their number is reported
|
||||
- P@10, the share of fully relevant candidates among the first 10
|
||||
- per-attribute share among the first 10 (same section, same formation, cause overlap), descriptive
|
||||
aggregation: mean over queries
|
||||
statistics:
|
||||
ci: whole-well cluster bootstrap over query wells, 2,000 resamples, seed 20261117, percentile 95% interval
|
||||
paired: per-query differences against random and against depth, with the same bootstrap
|
||||
reading: >-
|
||||
Descriptive, no gate. A representation is said to retrieve better than another only if the 95% interval of the
|
||||
paired difference excludes 0. Section and formation are both functions of depth within one field, so depth is
|
||||
the reference baseline.
|
||||
knn_forecast:
|
||||
purpose: the plan's PR-AUC when trouble is forecast from neighbours; secondary
|
||||
items: the 4,894 cells of outputs/m34/features_t3.parquet (the T3 universe of v1), label_b primary, label_a
|
||||
sensitivity
|
||||
neighbours: the k = 10 nearest cells from the other wells (leave-one-well-out); ties by row order
|
||||
representations:
|
||||
depth: md_top
|
||||
depth_witsml: >-
|
||||
md_top, depth_from_own_top and the eight witsml mean and sd columns of the T3 feature table; missing values
|
||||
replaced by the training-pool median, z-scored on the training pool, Euclidean distance
|
||||
score: mean label of the k neighbours
|
||||
metric: >-
|
||||
pooled out-of-fold average precision with a whole-well bootstrap 95% interval (2,000 resamples, seed 20261117),
|
||||
reported beside the prevalence and the v1 T3 baselines (majority 0.114, TF-IDF 0.123, definition b, masked)
|
||||
code: scripts/20_m5_t5.py, volve_dia/m5_t5.py
|
||||
outputs: outputs/m5/t5/
|
||||
1
configs/protocol_v5.yaml.sha256
Normal file
1
configs/protocol_v5.yaml.sha256
Normal file
@@ -0,0 +1 @@
|
||||
c99bb91bdca9a4ab00ef065847ec095121944ddccbffde32c34dc6f8fc125047 configs/protocol_v5.yaml
|
||||
115
docs/plan.md
115
docs/plan.md
@@ -27,7 +27,7 @@ Nhãn trong tài liệu này:
|
||||
| **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). |
|
||||
| **Trạng thái và việc tiếp theo** | G1 đạt ngày 18/11/2026. SHA-256 xác nhận protocol đã khóa trước mọi baseline. T4 và C4 là trọng tâm. T1 đoạn khoan công bố là kết quả bổ trợ. T2–T3 dự đoán nhãn dựng từ DDR theo NPT (b), kèm độ nhạy (a). Chưa lớp nào đủ điều kiện báo điểm riêng. Ngày 19/11 dừng Qwen/Llama v1 (giữ checkpoint, báo là v1 chưa đầy đủ); protocol v2 (§12 ý 32): VAI DeepSeek là baseline API chạy toàn ma trận, Sonnet và Haiku thay Qwen và Llama trên mẫu cố định trong session. **Ngày 20/11/2026 G2 v2 đạt** (§12 ý 33): TF-IDF, DistilBERT (mọi shard), VAI DeepSeek (T4/C4 48.951/48.951, T2 70.341/70.341) và mẫu Sonnet/Haiku đều xong; G2 v1 không thể đạt. **G3 đạt ngày 20/11/2026** (protocol v3, §12 ý 34): Sonnet κ = 0,98 so với điểm tự động theo đáp án XML (không có người chấm); số chính của T4 vẫn là điểm tự động. Việc còn lại: phân loại lỗi và EGS (RQ4), viết bài, điều khoản phát hành ở G4. Xem §1.6, §1.7 và §6. |
|
||||
| **Trạng thái và việc tiếp theo** | G1 đạt ngày 18/11/2026. SHA-256 xác nhận protocol đã khóa trước mọi baseline. T4 và C4 là trọng tâm. T1 đoạn khoan công bố là kết quả bổ trợ. T2–T3 dự đoán nhãn dựng từ DDR theo NPT (b), kèm độ nhạy (a). Chưa lớp nào đủ điều kiện báo điểm riêng. Ngày 19/11 dừng Qwen/Llama v1 (giữ checkpoint, báo là v1 chưa đầy đủ); protocol v2 (§12 ý 32): VAI DeepSeek là baseline API chạy toàn ma trận, Sonnet và Haiku thay Qwen và Llama trên mẫu cố định trong session. **Ngày 20/11/2026 G2 v2 đạt** (§12 ý 33): TF-IDF, DistilBERT (mọi shard), VAI DeepSeek (T4/C4 48.951/48.951, T2 70.341/70.341) và mẫu Sonnet/Haiku đều xong; G2 v1 không thể đạt. **G3 đạt ngày 20/11/2026** (protocol v3, §12 ý 34): Sonnet κ = 0,98 so với điểm tự động theo đáp án XML (không có người chấm); số chính của T4 vẫn là điểm tự động. Cùng ngày, protocol v4 (§12 ý 35) khóa trước khi tính phân loại lỗi theo họ câu hỏi và RQ4: bỏ trả lời là lỗi chính của truy xuất văn bản, tool chủ yếu sai giá trị dù trích đúng báo cáo; EGS (bản chuyển thể) có ρ Spearman 0,53–0,54 với điểm tự động nên H4 không được ủng hộ, nhưng tương quan chủ yếu đến từ các câu bỏ trả lời. T5 (truy xuất khoảng tương đồng, protocol v5, §12 ý 36) xong cùng ngày: độ sâu là baseline mạnh nhất (nDCG@10 0,666 so với ngẫu nhiên 0,463), không biểu diễn nào hơn độ sâu với CI loại 0. Việc còn lại: viết bài (M6), điều khoản phát hành ở G4. Xem §1.6, §1.7, §1.8 và §6. |
|
||||
|
||||
---
|
||||
|
||||
@@ -258,7 +258,7 @@ trên những ngày thiếu `diaHole` vẫn chưa xác định.
|
||||
theo wellbore DistilBERT 0,619, TF-IDF 0,484. Mở mã theo giếng: TF-IDF 0,994, DistilBERT 0,869. AP T3(b) che mã theo
|
||||
giếng: majority 0,114, TF-IDF 0,123, DistilBERT 0,121, xấp xỉ mức ngẫu nhiên, nên T3 vẫn chỉ là chẩn đoán.
|
||||
|
||||
### 1.7 M5: G3 và phân tích kết quả cuối ngày 20/11/2026
|
||||
### 1.7 M5: G3, phân tích kết quả cuối, phân loại lỗi và RQ4 ngày 20/11/2026
|
||||
|
||||
- **G3 đạt** [KT, protocol v3, `scripts/18_m5_judge.py`, `outputs/m5/judge/report.json`, §12 ý 34]. Tham chiếu là điểm
|
||||
tự động theo đáp án XML (không có người chấm). Mẫu 100 câu trả lời văn bản tự do (string, enumeration, list) của VAI
|
||||
@@ -298,9 +298,80 @@ trên những ngày thiếu `diaHole` vẫn chưa xác định.
|
||||
- **LLM so với TF-IDF (RQ1).** T2(b) che mã: DeepSeek − TF-IDF −0,055 / −0,058 / −0,055, CI chứa 0 (ví dụ −0,134 đến 0,011).
|
||||
Qwen − TF-IDF −0,200 (−0,250 đến −0,152), chỉ là v1 chưa đầy đủ, seed 0. DistilBERT theo wellbore − theo giếng (che mã):
|
||||
+0,040 / +0,015 / +0,021, CI chứa 0.
|
||||
- **Phân loại lỗi theo họ câu hỏi** [KT, protocol v4, `scripts/19_m5_errors.py`, `outputs/m5/errors/`, §12 ý 35]. Mỗi dự
|
||||
đoán trên câu thuộc giếng nhận đúng một lớp, theo thứ tự luật khóa trước: đúng; lỗi gọi; bỏ trả lời; nhầm wellbore; không
|
||||
trích; trích sai báo cáo (report recall 0); trích đúng báo cáo nhưng sai giá trị; với câu không trả lời được: trả lời câu
|
||||
không có đáp án. Tỉ lệ macro theo họ (trung bình ba lượt VAI DeepSeek; lớp "đúng" khớp đúng số chính của G2 v2):
|
||||
|
||||
| Chế độ | Đúng | Bỏ trả lời | Nhầm wellbore | Trích sai báo cáo | Trích đúng, sai giá trị | Lỗi gọi |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| C4 XML | 0,151 | 0,678 | 0,095 | 0,026 | 0,047 | 0 |
|
||||
| C4 HTML | 0,177 | 0,535 | 0,190 | 0,025 | 0,072 | 0 |
|
||||
| C4 OCR | 0,181 | 0,580 | 0,137 | 0,026 | 0,074 | 0 |
|
||||
| RAG | 0,148 | 0,638 | 0,110 | 0,030 | 0,066 | 0 |
|
||||
| zero-shot | 0,071 | 0,891 | 0,026 | 0,012 | 0 | 0 |
|
||||
| few-shot | 0,151 | 0,739 | 0,079 | 0,009 | 0 | 0 |
|
||||
| tool_only | 0,712 | 0,083 | 0,049 | 0,008 | 0,144 | 0,004 |
|
||||
| agent | 0,618 | 0,129 | 0,026 | 0,014 | 0,146 | 0,064 |
|
||||
|
||||
Lỗi chính của truy xuất văn bản là bỏ trả lời (54–68% mọi dự đoán), sau đó là nhầm wellbore. Họ aggregation gần như không
|
||||
bao giờ đúng với văn bản (C4 0,017–0,027, RAG 0,016; khoảng 70% bỏ trả lời) nhưng đạt 0,726 với tool_only; multi_hop bỏ trả
|
||||
lời 91–100% với C4/RAG, tool_only 0,723. Ở lookup, C4 XML đúng 0,089 so với 0,285 của HTML và OCR vì bỏ trả lời 0,762 so với
|
||||
0,45: đây là lý do XML thấp nhất trong C4 (§1.7, H5). Họ comparison có nhầm wellbore 21–25% ở mọi chế độ, kể cả tool_only
|
||||
(0,246), vì đáp án là một trong hai wellbore được hỏi nên chọn nhầm wellbore cũng là lớp này. Với tool_only và agent, lỗi còn
|
||||
lại chủ yếu là trích đúng báo cáo nhưng sai giá trị (0,14–0,15); agent có thêm 6,4% lỗi gọi (0,048–0,081 qua ba lượt). Qwen
|
||||
(v1 chưa đầy đủ, seed 0) ít bỏ trả lời hơn (0,15–0,35) nhưng nhầm wellbore nhiều hơn: C4 XML 0,371, HTML 0,512, OCR 0,583,
|
||||
RAG 0,482. Chỉ mô tả, không kiểm định.
|
||||
- **RQ4: EGS và điểm tự động** [KT, protocol v4]. Câu trả lời của baseline là JSON {answer, unit, citations}, nên EGS của TADI
|
||||
được chuyển thể và khóa trước khi tính: có số đo (số kèm đơn vị TADI) + có trích một báo cáo DDR có thật, mục bằng 0, chia
|
||||
3; EGS chỉ nhận 0, 1/3, 2/3. Tham chiếu là điểm tự động theo đáp án XML (không có người chấm). Spearman ρ gộp mọi chế độ của
|
||||
VAI DeepSeek: 0,538 / 0,535 / 0,535 (CI bootstrap theo giếng 0,530–0,551 ở lượt 0), khoảng 15.950 dự đoán mỗi lượt;
|
||||
Qwen 0,331 (0,295–0,372). Accuracy theo mức EGS (lượt 0): 0 → 0,013 (n 6.242), 1/3 → 0,221 (6.489), 2/3 → 0,669 (3.211).
|
||||
Theo luật khóa trước, ρ ≥ 0,3 ở cả ba lượt nên **H4 (tương quan yếu) không được ủng hộ**. Độ nhạy: bỏ các câu bỏ trả lời,
|
||||
ρ còn 0,233 / 0,234 / 0,231 (CI khoảng 0,19–0,30), Qwen 0,256; đơn vị mở rộng 0,52 (DeepSeek), 0,18 (Qwen). Trong từng
|
||||
chế độ: C4 HTML 0,581, OCR 0,573, XML 0,338, RAG 0,346, agent 0,327, tool_only 0,067, few-shot −0,036, zero-shot không xác
|
||||
định (EGS luôn 0). Bỏ câu bỏ trả lời: C4 HTML 0,54, OCR 0,51, XML 0,13, RAG 0,12, agent 0,05, tool_only −0,09. Cách đọc:
|
||||
EGS chủ yếu tách câu có trả lời khỏi câu bỏ trả lời; giữa các câu có trả lời, nó chỉ báo độ đúng ở C4 HTML/OCR và gần như
|
||||
không mang thông tin ở chế độ tool, nơi accuracy cao nhất. Vì vậy EGS không thay được điểm theo đáp án chuẩn.
|
||||
|
||||
---
|
||||
|
||||
### 1.8 M5: T5 truy xuất khoảng tương đồng ngày 20/11/2026
|
||||
|
||||
- **Thiết kế** [KT, protocol v5 khóa SHA-256 `c99bb91b…` trước mọi điểm truy xuất, `scripts/20_m5_t5.py`,
|
||||
`outputs/m5/t5/`, §12 ý 36]. Mục là khoảng T3 nằm trong lỗ của chính wellbore, biết section (T1 của báo cáo chứa activity
|
||||
đầu tiên) và formation (pick sâu nhất có md ≤ md_top). NPT (b): 410 khoảng, 19 wellbore, 10 giếng; (a): 373. Mức liên quan
|
||||
g = cùng section + cùng formation + giao nhóm nguyên nhân (0–3), "liên quan đầy đủ" khi g = 3. Ứng viên là khoảng của các
|
||||
giếng khác (chính) hoặc các wellbore khác (độ nhạy, đúng leave-one-wellbore-out của kế hoạch). Mỗi truy vấn có trung vị 358
|
||||
ứng viên, 14 ứng viên liên quan đầy đủ; 36/410 truy vấn không có ứng viên g = 3 nên không tính MRR. Biểu diễn không đọc mã,
|
||||
nguyên nhân, nhãn, section hay formation: depth (|Δ md_top|); witsml_pre (trung bình và độ lệch HKLD, ROP, RPM, SPPA trong
|
||||
24 h trước khoảng); text_pre (TF-IDF comment đã che mã 24 h trước khoảng); text_event (TF-IDF comment của chính khoảng, là
|
||||
góc nhìn mô tả sau sự kiện, không phải dự báo); RRF (k = 60) trên các biểu diễn trước sự kiện (rrf_pre) và thêm text_event
|
||||
(rrf_all). TF-IDF, trung vị và z-score fit trên tập ứng viên của từng fold. T5 nằm ngoài G2, không có cổng.
|
||||
- **Kết quả (NPT b, loại cả giếng; TB theo truy vấn, CI bootstrap theo giếng):**
|
||||
|
||||
| Biểu diễn | nDCG@10 | MRR | P@10 | Hiệu nDCG@10 so với depth |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| random (100 thứ tự) | 0,463 (0,444–0,478) | 0,161 | 0,052 | −0,203 (−0,228 đến −0,184) |
|
||||
| depth | 0,666 (0,644–0,685) | 0,397 | 0,194 | — |
|
||||
| witsml_pre | 0,495 (0,462–0,527) | 0,219 | 0,086 | −0,171 (−0,209 đến −0,136) |
|
||||
| text_pre | 0,611 (0,590–0,630) | 0,379 | 0,166 | −0,055 (−0,063 đến −0,048) |
|
||||
| text_event | 0,528 (0,506–0,544) | 0,271 | 0,109 | −0,138 (−0,163 đến −0,118) |
|
||||
| rrf_pre | 0,670 (0,653–0,687) | 0,435 | 0,221 | +0,004 (−0,010 đến 0,018) |
|
||||
| rrf_all | 0,661 (0,638–0,680) | 0,434 | 0,217 | −0,005 (−0,024 đến 0,009) |
|
||||
|
||||
- **Cách đọc.** Độ sâu là baseline mạnh nhất vì trong một mỏ, section và formation đều là hàm của độ sâu: trong 10 kết quả
|
||||
đầu, tỉ lệ cùng formation là 0,71 với depth và 0,23 với random. Không biểu diễn nào hơn depth với CI loại 0; rrf_pre hơn
|
||||
+0,004 nDCG@10 và +0,038 MRR (−0,006 đến 0,084). Text trước sự kiện tìm đúng section nhiều hơn depth (0,58 so với 0,45)
|
||||
nhưng kém về formation (0,37). WITSML 24 h trước chỉ hơn ngẫu nhiên +0,032 (0,008–0,053). Nhóm nguyên nhân gần như không
|
||||
tách được: tỉ lệ giao nguyên nhân trong top 10 là 0,70 (random) đến 0,75 (text), vì equipment chiếm đa số. Độ nhạy NPT (a) và
|
||||
loại theo wellbore cho cùng kết luận (depth 0,658–0,663; rrf_pre − depth +0,003 đến +0,005, CI chứa 0).
|
||||
- **Dự báo khó khăn từ láng giềng** (4.894 ô T3, điểm = trung bình nhãn của 10 ô gần nhất thuộc giếng khác): AP pooled với
|
||||
NPT (b) là 0,150 (0,116–0,204) theo độ sâu và 0,135 (0,110–0,183) theo độ sâu + WITSML, prevalence 0,114; NPT (a) 0,132 và
|
||||
0,120, prevalence 0,098. Số này cao hơn TF-IDF T3 của v1 (0,123) nhưng CI rộng và vẫn gần mức ngẫu nhiên, nên T3 và T5 vẫn
|
||||
là phân tích chẩn đoán.
|
||||
- Mã `volve_dia/m5_t5.py`, 12 test; lượt `20261120-073123_m5_t5` (1 phút 36 giây).
|
||||
|
||||
## 2. Research gap
|
||||
|
||||
### 2.1 Phát biểu
|
||||
@@ -308,7 +379,7 @@ trên những ngày thiếu `diaHole` vẫn chưa xác định.
|
||||
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 độ đúng theo đáp án chuẩn (dự án dùng điểm tự động theo đáp án XML, không có người chấm);
|
||||
3. EGS của TADI chưa được đối chiếu với độ đúng theo đáp án chuẩn (dự án dùng điểm tự động theo đáp án XML, không có người chấm; kết quả ở §1.7);
|
||||
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.
|
||||
@@ -339,7 +410,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 giải T4 và các đích bổ trợ tốt đến đâu khi kiểm soát rò rỉ và split theo giếng? | H1: trên T2, ưu thế của LLM zero-shot so với TF-IDF + LR còn chưa rõ khi che mã | Metric theo §4.2, CI bootstrap theo giếng |
|
||||
| RQ2 | Điểm T2–T3 đổi bao nhiêu khi mở mã hoạt động hoặc đổi nhóm từ giếng sang wellbore? | H2: mở mã làm điểm tăng | So cặp ablation mã, kèm phân tích độ nhạy theo wellbore. Mọi dự báo T3 giữ đặc trưng trước mốc |
|
||||
| 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 độ đúng không? | H4: EGS (regex) tương quan yếu với độ đúng | Spearman giữa EGS và điểm tự động theo đáp án XML; không có người chấm |
|
||||
| RQ4 | EGS của TADI có tương quan với độ đúng không? | H4: EGS (regex) tương quan yếu với độ đúng | Spearman giữa EGS (chuyển thể, protocol v4) và điểm tự động theo đáp án XML; không có người chấm. **Kết quả 20/11:** ρ 0,53–0,54, H4 không được ủng hộ; bỏ câu bỏ trả lời ρ 0,23 (§1.7) |
|
||||
| RQ5 | Sai lệch của OCR làm điểm T4, T1 section và T2 NPT đổ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 |
|
||||
|
||||
Kết quả được báo cáo bất kể chiều nào; giả thuyết không đạt cũng là kết quả.
|
||||
@@ -363,7 +434,7 @@ Kết quả được báo cáo bất kể chiều nào; giả thuyết không đ
|
||||
| T2 Dự đoán dòng NPT theo mã DDR | Comment và tóm tắt 24 h | PR-AUC với định nghĩa (b), kèm độ nhạy theo (a) | Che mã hoạt động và chạy ablation có mã |
|
||||
| T3 Dự đoán khoảng theo mã DDR | Chuỗi activity, WITSML và formation | IoU khoảng và PR-AUC trên lưới 10 m, chính (b), độ nhạy (a) | Chỉ dùng đặ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 tự động theo đáp án XML | Đá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 |
|
||||
| T5 (tùy chọn) Truy xuất khoảng tương đồng | Độ sâu, thống kê WITSML và comment đã che mã 24 h trước khoảng; comment của chính khoảng (góc nhìn mô tả) | nDCG@10 (chính), MRR, P@10; AP khi dự báo khó khăn từ 10 láng giềng; loại cả giếng (chính), loại wellbore (độ nhạy); protocol v5, §1.8 | Nhãn liên quan xác định bằng luật; biểu diễn không đọc mã, nguyên nhân, section hay formation |
|
||||
|
||||
T4 và C4 là kết quả chính. Nhãn loại thao tác T1 và nhóm nguyên nhân T2 nằm trong báo cáo kiểm định nhãn.
|
||||
Các đích có điểm baseline dùng metric tổng hợp trong bảng. G1 không có lớp hoặc nhóm gộp đủ điều kiện báo
|
||||
@@ -384,7 +455,7 @@ Nguyên tắc: **mọi nhãn sinh bằng mã từ dữ liệu gốc**, có prove
|
||||
- **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.
|
||||
- **T5:** hai khoảng liên quan nếu cùng hole section, cùng formation, cùng nhóm NPT. Protocol v5 dùng mức g = tổng ba điều kiện (0–3), liên quan đầy đủ khi g = 3; section lấy từ T1, formation là pick sâu nhất trên md_top (§1.8).
|
||||
|
||||
### 4.4 Kiểm định nhãn: ba lớp
|
||||
|
||||
@@ -454,7 +525,7 @@ Ngưỡng các cổng chốt trong `protocol_v1` trước G1; sau đó ngưỡng
|
||||
| **M1 Dữ liệu và nhãn** | 30/10 – 30/11/2026 (xong phần máy và chấm thử bằng LLM 17/11) | 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** | Xong và đạt G1 ngày 18/11/2026 | Chấm mù bằng ≥ 3 LLM rater (300 activity và 90 ngày T1, hai lượt); 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 đạt:** khóa SHA-256 trước baseline. Giữ κ ≥ 0,60, ≥ 20 mục được chấm và ≥ 3 giếng có ≥ 5 mục mỗi giếng. 0 lớp đủ ngưỡng báo điểm riêng |
|
||||
| **M3–M4 Baseline** | 18–20/11/2026 (xong phần chạy) | TF-IDF + logistic, DistilBERT (mọi shard, ba seed), VAI DeepSeek (toàn ma trận T4/C4 và T2, ba lượt lặp), mẫu Sonnet/Haiku; Qwen v1 dừng 19/11 (chưa đầy đủ), Llama không chạy | Bảng kết quả, ≥ 3 seed cho model ngẫu nhiên, CI theo giếng (`outputs/m34/report.json`) | **G2 v2 đạt 20/11** (protocol v2, §12 ý 32–33). G2 v1 không thể đạt vì Qwen và Llama dừng |
|
||||
| **M5 Hiệu chuẩn judge và phân tích lỗi** | 20/11/2026 – 3/2027 | Dùng kết quả độ ổn định từ M2; 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 κ giữa judge và điểm tự động theo đáp án XML đạt ≥ 0,6 (không có người chấm; protocol v3); không đạt thì T4 chỉ báo metric tự động và ghi rõ. **Đạt ngày 20/11/2026:** Sonnet κ = 0,98 (CI 0,947–1,0), Haiku 0,90; số chính T4 vẫn là điểm tự động (§1.7) |
|
||||
| **M5 Hiệu chuẩn judge và phân tích lỗi** | 20/11/2026 – 3/2027 | Dùng kết quả độ ổn định từ M2; 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 κ giữa judge và điểm tự động theo đáp án XML đạt ≥ 0,6 (không có người chấm; protocol v3); không đạt thì T4 chỉ báo metric tự động và ghi rõ. **Đạt ngày 20/11/2026:** Sonnet κ = 0,98 (CI 0,947–1,0), Haiku 0,90; số chính T4 vẫn là điểm tự động (§1.7). Phân loại lỗi và RQ4 xong 20/11 (protocol v4, §12 ý 35). T5 xong 20/11 (protocol v5, §1.8, §12 ý 36) |
|
||||
| **M6 Viết và nộp** | 4/2027 | Viết bài; đóng gói code, nhãn, protocol, hash sau khi xác nhận giấy phép phát hành ở G4; 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 |
|
||||
|
||||
---
|
||||
@@ -474,8 +545,10 @@ Ngưỡng các cổng chốt trong `protocol_v1` trước G1; sau đó ngưỡng
|
||||
| `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` và `.sha256` | Bảng ánh xạ, 39 template T4, ghép OCR, protocol đã khóa tại G1 |
|
||||
| `scripts/10_m2_*.py`, `scripts/run_m2.sh`, `configs/m2_validation.yaml` | Mẫu phân tầng, rater mở chạy cục bộ, kiểm chéo, thống kê độ đồng thuận và kiểm tra trước khi khóa G1 |
|
||||
| `tests/` | 168 test đạt ngày 20/11 (gồm 8 test mock baseline v2, 3 test mẫu session và 5 test judge G3). Test cần dữ liệu mang marker `data` |
|
||||
| `tests/` | 204 test đạt ngày 20/11 (gồm 8 test mock baseline v2, 3 test mẫu session, 5 test judge G3, 24 test phân loại lỗi/EGS và 12 test T5). Test cần dữ liệu mang marker `data` |
|
||||
| `scripts/18_m5_judge.py`, `volve_dia/m5_judge.py`, `configs/protocol_v3.yaml` và `.sha256` | Hiệu chuẩn LLM-judge cho G3 so với điểm tự động theo đáp án XML (§1.7, §12 ý 34) |
|
||||
| `scripts/19_m5_errors.py`, `volve_dia/m5_errors.py`, `configs/protocol_v4.yaml` và `.sha256` | Phân loại lỗi theo họ câu hỏi và RQ4 (EGS so với điểm tự động) → `outputs/m5/errors/` (§1.7, §12 ý 35) |
|
||||
| `scripts/20_m5_t5.py`, `volve_dia/m5_t5.py`, `configs/protocol_v5.yaml` và `.sha256` | T5 truy xuất khoảng tương đồng và dự báo từ láng giềng → `outputs/m5/t5/` (§1.8, §12 ý 36) |
|
||||
| `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 |
|
||||
| `scripts/11_m34_classify.py`, `12_m34_qa.py`, `13_m34_report.py`, `14_m34_t2_llm.py`, `run_m34.sh`; v2: `15_m34_v2.py`, `16_m34_session.py`, `run_m34_v2.sh`, `m34_status.sh`, `volve_dia/m34_v2.py`, `configs/protocol_v2.yaml` | Đặc trưng và T1–T3, Qwen zero-shot T2, suy luận T4/C4, metric ghép cặp, kiểm độ phủ G2 |
|
||||
| `volve_dia/m34_*.py`, `configs/m34_baselines.yaml` | Triển khai thiết kế baseline, điểm và CI. Cấu hình chạy nối với hash giao thức G1 |
|
||||
@@ -537,8 +610,8 @@ Danh sách chính ở bản đánh giá mục 9. Ghi chú đọc và BibTeX: `do
|
||||
## 12. Việc làm ngay và nhật ký quyết định
|
||||
|
||||
1. **Việc tiếp theo (từ 20/11/2026).**
|
||||
1. G2 v2 (ý 33) và G3 (ý 34) đã đạt. Còn lại ở M5: phân loại lỗi theo họ câu hỏi và tương quan EGS với điểm tự động
|
||||
(RQ4); T4 vẫn báo điểm tự động làm số chính. Sau đó viết bài (M6). Không được gọi bất kỳ kết quả nào là audit của người, của tác giả hay của chuyên gia.
|
||||
1. G2 v2 (ý 33), G3 (ý 34), phân loại lỗi và RQ4 (ý 35), T5 (ý 36) đã xong. Tiếp theo là viết bài (M6); T4 vẫn báo điểm tự
|
||||
động làm số chính. Không được gọi bất kỳ kết quả nào là audit của người, của tác giả hay của chuyên gia.
|
||||
2. Giữ cách xử lý 16 trang lệch ngày và 7 trang chưa ghép của OCR hub theo §12 ý 21.
|
||||
3. Các bài EAGE và OnePetro chưa lấy được toàn văn trong lần kiểm tra ngày 18/11. Xác nhận điều khoản
|
||||
phát hành Volve ở G4 theo §12 ý 23.
|
||||
@@ -723,3 +796,25 @@ Danh sách chính ở bản đánh giá mục 9. Ghi chú đọc và BibTeX: `do
|
||||
LLM, mẫu phân tầng nên κ không phải ước lượng cho toàn bộ câu trả lời văn bản tự do.
|
||||
- Phân tích kết quả cuối ghi ở §1.7: agent kém tool_only, OCR không kém XML trên T4 (H5 không được ủng hộ), rò rỉ mã rõ ở
|
||||
T2 và xấp xỉ 0 ở T3, DeepSeek không hơn TF-IDF trên T2 (CI chứa 0).
|
||||
|
||||
35. **20/11/2026. Protocol v4: phân loại lỗi theo họ câu hỏi và RQ4.**
|
||||
- Lệch so với kế hoạch: protocol v1–v3 nêu phân tích lỗi (M5) và RQ4 nhưng chưa cố định luật. `configs/protocol_v4.yaml`
|
||||
(khóa SHA-256 `6a9ad0fb…`, mở rộng v3, không sửa v1–v3) cố định cả hai trước khi tính bất kỳ lớp lỗi hay giá trị EGS nào.
|
||||
- EGS của TADI (arXiv 2605.00060, công thức 3) cần câu trả lời sáu mục có trích dẫn văn bản; baseline trả JSON
|
||||
{answer, unit, citations}, nên v4 chuyển thể: có số đo (số kèm đơn vị TADI) + có trích báo cáo DDR có thật, mục = 0. Mục
|
||||
hằng số không ảnh hưởng tương quan hạng. Đây là bản chuyển thể, không phải output agent của TADI.
|
||||
- Dữ liệu: VAI DeepSeek ba lượt (chính), Qwen v1 seed 0 chỉ các lượt đủ (phụ, chưa đầy đủ); chỉ câu thuộc giếng; checkpoint
|
||||
phải mang digest đầu vào hiện hành. Mã: `volve_dia/m5_errors.py`, `scripts/19_m5_errors.py`, 24 test; chạy 3 phút.
|
||||
- Kết quả ở §1.7: bỏ trả lời là lỗi chính của truy xuất văn bản; tool chủ yếu sai giá trị dù trích đúng báo cáo; ρ EGS gộp
|
||||
0,535–0,538 ở cả ba lượt nên H4 không được ủng hộ; bỏ câu bỏ trả lời ρ còn khoảng 0,23; trong chế độ tool ρ ≈ 0,07.
|
||||
Không gọi kết quả nào là đánh giá của người, tác giả hay chuyên gia.
|
||||
|
||||
36. **20/11/2026. Protocol v5: T5 truy xuất khoảng tương đồng.**
|
||||
- Lệch so với kế hoạch: T5 là nhiệm vụ tùy chọn, protocol v1–v4 chưa định nghĩa. `configs/protocol_v5.yaml` (khóa SHA-256
|
||||
`c99bb91b…`, mở rộng v4, không sửa v1–v4) cố định mục, mức liên quan, biểu diễn, metric và thống kê trước mọi điểm truy
|
||||
xuất; trước khi khóa chỉ xem số đếm nhãn (số khoảng đủ điều kiện, số ứng viên liên quan đầy đủ).
|
||||
- Ứng viên chính loại cả giếng của truy vấn (nhất quán với split chính của v1); leave-one-wellbore-out của kế hoạch là độ
|
||||
nhạy. Biểu diễn trước sự kiện dùng cửa sổ 24 h trước từng khoảng (không dùng hàng đặc trưng T3, vốn chung một mốc cho cả
|
||||
wellbore). Comment của chính khoảng là góc nhìn mô tả, báo riêng.
|
||||
- Kết quả ở §1.8: depth nDCG@10 0,666, random 0,463; text_pre 0,611; witsml_pre 0,495; rrf_pre 0,670 (+0,004 so với depth, CI
|
||||
chứa 0). Dự báo từ láng giềng AP 0,150 (0,116–0,204) so với prevalence 0,114. T5 ngoài G2, không có cổng.
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
(protocol v2, toàn ma trận T4/C4 và T2, ba lượt lặp) đều xong; Sonnet và Haiku đã chạy mẫu con trong session. Qwen và Llama
|
||||
dừng ngày 19/11 (Qwen là kết quả v1 chưa đầy đủ).
|
||||
- **G3 đạt ngày 20/11/2026** (protocol v3): judge Sonnet khớp điểm tự động theo đáp án XML với κ = 0,98 trên 100 câu
|
||||
trả lời văn bản tự do (không có người chấm). Còn lại: phân loại lỗi, EGS, viết bài, điều khoản phát hành ở G4.
|
||||
trả lời văn bản tự do (không có người chấm).
|
||||
- **Phân loại lỗi và RQ4 xong ngày 20/11/2026** (protocol v4): EGS tương quan vừa với điểm tự động (ρ 0,53–0,54),
|
||||
chủ yếu vì tách câu có trả lời khỏi câu bỏ trả lời.
|
||||
- **T5 xong ngày 20/11/2026** (protocol v5): truy xuất khoảng tương đồng theo độ sâu đạt nDCG@10 0,666 (ngẫu nhiên 0,463);
|
||||
văn bản, WITSML hay kết hợp không hơn độ sâu. Còn lại: viết bài, điều khoản phát hành ở G4.
|
||||
|
||||
**Bài giảng này dành cho ai.** Người chưa biết gì về khoan dầu khí, học máy hay mô hình ngôn ngữ lớn. Chỉ cần toán phổ thông: tỉ lệ, trung bình, xác suất đơn giản.
|
||||
|
||||
@@ -366,7 +370,7 @@ Tỉ lệ NPT (định nghĩa b) khác nhau rất nhiều giữa các wellbore:
|
||||
|
||||
| Công trình | Có gì | Thiếu gì |
|
||||
| --- | --- | --- |
|
||||
| **TADI** (arXiv 2026) | Agent trên Volve: DuckDB 12 bảng, 12 tool; đề xuất điểm EGS; 130 câu hỏi mẫu | Không có kết quả định lượng; EGS chưa tính trên câu nào; không có đáp án chuẩn |
|
||||
| **TADI** (arXiv 2026) | Agent trên Volve: DuckDB 12 bảng, 12 tool; đề xuất điểm EGS; 130 câu hỏi mẫu | Không có kết quả định lượng; EGS chưa tính trên câu nào; không có đáp án chuẩn (dự án đã đối chiếu EGS chuyển thể, Bài 7.5) |
|
||||
| **PetroAgents** (preprint 2026) | Phân loại NPT theo ngày-giếng, 1.750 ví dụ, 7 lớp; macro-F1 0,464 và 0,442 | Đánh giá trên mẫu 60 ví dụ; nhãn sinh từ chính mã DDR; multi-agent hơn single-LLM 0,048 với p = 0,22 trên 3 seed, tức chưa có ý nghĩa thống kê |
|
||||
| Bodén et al. (SPE-228117-MS) | Trợ lý RAG cho báo cáo khoan | Hệ thống đóng, bộ câu hỏi không công bố |
|
||||
| Hussain & Reddy (SPE-236554-MS); Bihani et al. (SPE-235330-MS) | Hỏi đáp trên 1.266 và 1.681 DDR | Không có bộ đề công khai có đáp án chuẩn |
|
||||
@@ -395,7 +399,7 @@ Chỗ trống mà Volve-DIA nhắm tới:
|
||||
| **T2** Dự đoán dòng NPT theo mã DDR | DDR đánh dấu dòng nào là NPT theo (b)? | Comment và tóm tắt 24 h đã che mã | PR-AUC tổng hợp, kèm độ nhạy (a) |
|
||||
| **T3** Định vị khoảng khó khăn | Ô độ sâu 10 m nào sắp gặp khó khăn? | Chuỗi activity, WITSML và formation **trước** thời điểm dự báo | PR-AUC trên lưới 10 m; IoU khoảng |
|
||||
| **T4** Hỏi đáp có dẫn chứng | Ví dụ: "F-12 mất bao nhiêu giờ chờ thời tiết?" | Câu hỏi bằng ngôn ngữ tự nhiên | Đúng trong dung sai; trích dẫn đúng dòng; tỉ lệ số bịa |
|
||||
| T5 (tùy chọn) Truy xuất | Khoảng nào ở giếng cũ giống khoảng sắp khoan nhất? | Embedding của cửa sổ WITSML, DDR, formation | nDCG@k, MRR |
|
||||
| T5 (tùy chọn) Truy xuất | Khoảng nào ở giếng cũ giống khoảng sắp khoan nhất? | Độ sâu, thống kê WITSML và comment đã che mã 24 h trước khoảng | nDCG@10, MRR, P@10 |
|
||||
|
||||
Ví dụ trên báo cáo F-12 ở Bài 2.3:
|
||||
- **T1:** đáp án là "đoạn 12¼", dòng 3 thuộc loại `interruption`".
|
||||
@@ -671,7 +675,12 @@ Ngưỡng của dự án: **κ ≥ 0,6**.
|
||||
|
||||
- TADI đề xuất **EGS** (Evidence Grounding Score): dùng biểu thức chính quy kiểm xem câu trả lời có con số đo, có trích DDR, có đủ 6 mục hay không.
|
||||
- Một câu trả lời có thể đủ mọi thứ đó mà vẫn sai.
|
||||
- Dự án sẽ đo tương quan giữa EGS và độ đúng thật (giả thuyết H4: tương quan yếu).
|
||||
- Dự án đo tương quan giữa EGS và độ đúng theo đáp án XML (giả thuyết H4: tương quan yếu).
|
||||
- Baseline trả lời bằng JSON (đáp án, đơn vị, trích dẫn), không có 6 mục, nên protocol v4 chuyển thể EGS: có số kèm đơn vị
|
||||
khoan + có trích một báo cáo DDR có thật, phần mục bằng 0. EGS chỉ nhận 0, 1/3, 2/3.
|
||||
- Kết quả (DeepSeek, ba lượt): Spearman ρ 0,535–0,538, nên H4 không được ủng hộ. Accuracy ở mức EGS 0 / 1/3 / 2/3 là
|
||||
0,01 / 0,22 / 0,67. Nhưng bỏ các câu "không có thông tin" thì ρ chỉ còn khoảng 0,23, và trong chế độ tool ρ chỉ 0,07.
|
||||
Tức là EGS chủ yếu phân biệt "có trả lời" với "bỏ trả lời"; nó không thay được chấm theo đáp án chuẩn.
|
||||
|
||||
**Nguồn:** Lu et al. (2026b, TADI).
|
||||
|
||||
@@ -906,7 +915,7 @@ Mỗi baseline ngẫu nhiên chạy ba seed.
|
||||
| T2 | PR-AUC dự đoán mã NPT (b) | PR-AUC theo (a) để kiểm tra độ nhạy |
|
||||
| T3 | PR-AUC trên lưới 10 m | IoU khoảng |
|
||||
| T4 | Đúng trong dung sai | Precision và recall của trích dẫn; tỉ lệ số bịa; tỉ lệ trả lời nhầm wellbore; tỉ lệ từ chối đúng |
|
||||
| T5 | nDCG@k | MRR |
|
||||
| T5 | nDCG@10 (mức liên quan 0–3) | MRR và P@10 trên khoảng liên quan đầy đủ; AP dự báo từ láng giềng |
|
||||
|
||||
*Đúng trong dung sai:* câu hỏi số có dung sai tuyệt đối hoặc tương đối ghi sẵn trong câu; câu hỏi ngày có dung sai theo ngày.
|
||||
|
||||
@@ -1062,7 +1071,7 @@ Mẫu Sonnet/Haiku (300 câu T4, ngoài độ phủ G2) xem plan §12 ý 33. Kh
|
||||
Bootstrap lấy nguyên giếng, giữ cặp dự đoán giữa các phương thức.
|
||||
[Thiết kế và kết quả M3–M4](plan.md#16-triển-khai-m3m4-ngày-18112026).
|
||||
|
||||
### 10.7 M5: judge và đọc kết quả cuối (20/11/2026)
|
||||
### 10.7 M5: judge, đọc kết quả cuối, phân loại lỗi, EGS và T5 (20/11/2026)
|
||||
|
||||
**Judge khớp bộ chấm tự động, không phải khớp người.** Một số câu T4 có đáp án là chữ (tên giàn, danh sách wellbore).
|
||||
Bộ chấm tự động so chuỗi nên có thể chấm sai một câu trả lời đúng nhưng viết khác. Một LLM-judge đọc nghĩa có thể sửa
|
||||
@@ -1079,6 +1088,29 @@ nhận "MERSK INSPIRER" (lỗi OCR) cho "MÆRSK INSPIRER". G3 đạt, nhưng s
|
||||
- Rò rỉ mã rất lớn ở T2 (TF-IDF +0,53 AP, DistilBERT +0,27 đến +0,29) và gần 0 ở T3, vì T3 che mã đã gần mức ngẫu nhiên.
|
||||
- DeepSeek zero-shot không hơn TF-IDF trên T2 (−0,055, CI chứa 0). Số Qwen chỉ là v1 chưa đầy đủ (seed 0).
|
||||
|
||||
**Phân loại lỗi theo họ câu hỏi (protocol v4).** Mỗi câu trả lời sai được xếp vào đúng một lớp, theo thứ tự cố định: lỗi
|
||||
gọi, bỏ trả lời, nhầm wellbore, không trích, trích sai báo cáo, trích đúng báo cáo nhưng sai giá trị. Với DeepSeek:
|
||||
- Truy xuất văn bản (C4, RAG) chủ yếu **bỏ trả lời** (54–68% mọi câu), sau đó nhầm wellbore. C4 XML điểm thấp nhất vì bỏ
|
||||
trả lời nhiều nhất (lookup 76% so với 45% ở HTML/OCR), không phải vì đọc XML sai.
|
||||
- Câu tổng hợp (aggregation) và nhiều bước (multi_hop) gần như không bao giờ đúng với văn bản, nhưng đúng khoảng 72% với tool:
|
||||
cộng giờ hay đếm sự kiện qua nhiều báo cáo cần truy vấn bảng, không phải đọc vài đoạn văn.
|
||||
- Chế độ tool sai chủ yếu ở giá trị dù đã trích đúng báo cáo (14–15%); agent thêm 6,4% lỗi gọi.
|
||||
- Câu so sánh hai wellbore: đáp án là tên wellbore, nên chọn nhầm cũng tính là "nhầm wellbore" (21–25% ở mọi chế độ).
|
||||
|
||||
**T5: truy xuất khoảng tương đồng (protocol v5, §1.8 của plan).** Câu hỏi: khi sắp khoan một khoảng, các khoảng khó khăn
|
||||
nào ở giếng cũ giống nó nhất? Mỗi truy vấn là một khoảng NPT (b) của T3 (410 khoảng, 10 giếng); ứng viên là khoảng của các
|
||||
giếng khác. Hai khoảng "liên quan" theo luật: cộng 1 điểm nếu cùng đoạn khoan, 1 nếu cùng formation, 1 nếu chung nhóm nguyên
|
||||
nhân (0–3 điểm). Thước đo chính là nDCG@10: 10 kết quả đầu có xếp các khoảng điểm cao lên trước không (1 là hoàn hảo).
|
||||
Biểu diễn không được đọc mã, nguyên nhân, đoạn khoan hay formation.
|
||||
- Xếp theo **độ sâu gần nhất** đạt 0,666, ngẫu nhiên 0,463. Trong một mỏ, đoạn khoan và formation gần như do độ sâu quyết
|
||||
định, nên độ sâu đã lấy được phần lớn điểm.
|
||||
- Comment 24 h trước khoảng đạt 0,611; thống kê WITSML 24 h trước 0,495 (chỉ hơn ngẫu nhiên một chút); kết hợp ba cách
|
||||
(RRF) 0,670, hơn độ sâu +0,004 nhưng CI chứa 0.
|
||||
- Không cách nào tìm được khoảng cùng nhóm nguyên nhân tốt hơn hẳn ngẫu nhiên (0,75 so với 0,70 trong top 10), vì hỏng thiết
|
||||
bị chiếm đa số.
|
||||
- Dự báo ô 10 m sắp gặp khó khăn bằng 10 ô láng giềng ở giếng khác: AP 0,150 theo độ sâu (prevalence 0,114). T3 và T5 vẫn
|
||||
là phân tích chẩn đoán.
|
||||
|
||||
---
|
||||
|
||||
## Bài 11. Được nói gì, không được nói gì
|
||||
@@ -1145,9 +1177,11 @@ Danh sách đầy đủ ở [plan.md](plan.md) §10.
|
||||
| Nhãn T1–T3 | [labels.py](../volve_dia/labels.py), [configs/labels.yaml](../configs/labels.yaml) |
|
||||
| Câu hỏi và đáp án T4 | [t4.py](../volve_dia/t4.py), [t4_pandas.py](../volve_dia/t4_pandas.py), [configs/t4_templates.yaml](../configs/t4_templates.yaml) |
|
||||
| Mẫu chấm mù, κ và ghi nguồn gốc M2 | [audit.py](../volve_dia/audit.py), [m2.py](../volve_dia/m2.py) |
|
||||
| Luật chia, metric, cổng | [configs/protocol_v1.yaml](../configs/protocol_v1.yaml), [protocol_v2.yaml](../configs/protocol_v2.yaml), [protocol_v3.yaml](../configs/protocol_v3.yaml) |
|
||||
| Luật chia, metric, cổng | [configs/protocol_v1.yaml](../configs/protocol_v1.yaml), [protocol_v2.yaml](../configs/protocol_v2.yaml), [protocol_v3.yaml](../configs/protocol_v3.yaml), [protocol_v4.yaml](../configs/protocol_v4.yaml), [protocol_v5.yaml](../configs/protocol_v5.yaml) |
|
||||
| Baseline M3–M4, so cặp, CI theo giếng | [m34.py](../volve_dia/m34.py) và các `m34_*.py` |
|
||||
| Hiệu chuẩn judge G3 | [m5_judge.py](../volve_dia/m5_judge.py) |
|
||||
| Phân loại lỗi, EGS và RQ4 | [m5_errors.py](../volve_dia/m5_errors.py) |
|
||||
| T5 truy xuất khoảng tương đồng | [m5_t5.py](../volve_dia/m5_t5.py) |
|
||||
|
||||
### 12.3 Chạy theo pha
|
||||
|
||||
@@ -1160,6 +1194,8 @@ Cài đặt và bảng mô tả từng script ở [README.md](../README.md).
|
||||
| M3–M4 | `scripts/run_m34.sh` | Đặc trưng, baseline T1–T4/C4, CI và độ phủ G2 |
|
||||
| M3–M4 v2 | `scripts/run_m34_v2.sh`, `15_m34_v2.py`, `16_m34_session.py`, `m34_status.sh` | VAI DeepSeek cho T4/C4 và T2 (đầy đủ), mẫu Sonnet/Haiku trong session, theo dõi tiến trình |
|
||||
| M5 | `scripts/18_m5_judge.py prepare\|status\|collect` | Mẫu G3, batch cho judge trong session, κ so với điểm tự động |
|
||||
| M5 | `scripts/19_m5_errors.py` (khoảng 3 phút) | Phân loại lỗi theo họ câu hỏi, EGS và ρ Spearman với điểm tự động (protocol v4) |
|
||||
| M5 | `scripts/20_m5_t5.py` (khoảng 2 phút) | T5 truy xuất khoảng tương đồng và dự báo từ láng giềng (protocol v5) |
|
||||
|
||||
`run_m1.sh` chưa được chạy trọn một lần từ đầu đến cuối; các bước của nó đã chạy riêng lẻ.
|
||||
|
||||
@@ -1170,8 +1206,10 @@ Cài đặt và bảng mô tả từng script ở [README.md](../README.md).
|
||||
|
||||
### 12.4 Test quan trọng
|
||||
|
||||
- Test nằm trong [tests/](../tests/): 168 test đạt ngày 20/11. Test cần dữ liệu mang marker `data`.
|
||||
- Test nằm trong [tests/](../tests/): 204 test đạt ngày 20/11. Test cần dữ liệu mang marker `data`.
|
||||
- [test_m5_judge.py](../tests/test_m5_judge.py): rút mẫu G3 cố định, view che cho judge, kiểm phán quyết, κ và cổng.
|
||||
- [test_m5_errors.py](../tests/test_m5_errors.py): nhận diện số đo và trích DDR, thứ tự luật phân loại lỗi, lọc lượt đủ, Spearman và cách đọc H4.
|
||||
- [test_m5_t5.py](../tests/test_m5_t5.py): chuẩn hóa formation, điều kiện chọn khoảng, mức liên quan, nDCG/MRR, phá hòa, RRF, bootstrap theo giếng và kNN loại cả giếng.
|
||||
- [test_ddr_xml.py](../tests/test_ddr_xml.py): số lượng khóa (`EXPECTED`) và sentinel.
|
||||
- [test_qc.py](../tests/test_qc.py): luật so và căn hàng của QC.
|
||||
- [test_witsml.py](../tests/test_witsml.py): số lượng WITSML và ghép tên wellbore.
|
||||
|
||||
@@ -160,3 +160,6 @@ run_id,parent,name,status,exit_code,start,end,wall_s,wall,device,git,dirty,code_
|
||||
20261118-120118_m34_report_watch,,m34_report_watch,ok,0,2026-11-18T12:01:18+00:00,2026-11-20T06:32:55+00:00,153096.8,42:31:37,,2b59d635ce86,True,d007a681a812317d,runlog,"bash -c ' ⏎ set -euo pipefail ⏎ wait_for_stage() { ⏎ local stage=""$1"" pid=""$2"" ⏎ printf ""Waiting for %s (PID %s)\n"" ""$stage"" ""$pid"" ⏎ tail --pid=""$pid"" --sleep-interval=30 -f /dev/null ⏎ printf ""Refreshing coverage after %s exited\n"" ""$stage"" ⏎ env -u RUNLOG_DIR scripts/run_m34.sh report ⏎ } ⏎ wait_for_stage qwen_qa 1113332 & ⏎ qwen_watch=$! ⏎ wait_for_stage qwen_t2 1119743 & ⏎ t2_watch=$! ⏎ wait_for_stage distilbert 1110839 & ⏎ distilbert_watch=$! ⏎ result=0 ⏎ for watcher in ""$qwen_watch"" ""$t2_watch"" ""$distilbert_watch""; do ⏎ wait ""$watcher"" || result=1 ⏎ done ⏎ exit ""$result"" ⏎ '"
|
||||
20261120-064939_m5_judge_prepare,,m5_judge_prepare,ok,0,2026-11-20T06:49:39+00:00,2026-11-20T06:49:40+00:00,1.0,0:00:01,,2b59d635ce86,True,1b8d4420a03891bd,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/18_m5_judge.py prepare
|
||||
20261120-065136_m5_judge_collect,,m5_judge_collect,ok,0,2026-11-20T06:51:36+00:00,2026-11-20T06:51:48+00:00,11.8,0:00:12,,2b59d635ce86,True,3b1cc8df87a85b4a,runlog,/home/jovyan/lamlvh/Volve-DIA/.venv/bin/python scripts/18_m5_judge.py collect
|
||||
20261120-070705_m5_errors,,m5_errors,ok,0,2026-11-20T07:07:05+00:00,2026-11-20T07:10:16+00:00,190.6,0:03:11,,8cb55a31538a,False,5db8b1cd0e5847f9,runlog,.venv/bin/python scripts/19_m5_errors.py
|
||||
20261120-071047_m5_errors,,m5_errors,ok,0,2026-11-20T07:10:47+00:00,2026-11-20T07:14:01+00:00,193.1,0:03:13,,8cb55a31538a,True,ac5a4107dcc4ad71,runlog,.venv/bin/python scripts/19_m5_errors.py
|
||||
20261120-073123_m5_t5,,m5_t5,ok,0,2026-11-20T07:31:23+00:00,2026-11-20T07:32:59+00:00,95.8,0:01:36,,23e15ee27edf,False,bf9b78258e4f2df1,runlog,.venv/bin/python scripts/20_m5_t5.py
|
||||
|
||||
|
20
report.html
20
report.html
@@ -122,7 +122,7 @@ 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; D-8 đến D-14 chốt 17/11/2026, D-15 đến D-17 chốt 18/11/2026, D-18 chốt 20/11/2026)</h2>
|
||||
<h2>Quyết định (D-1 đến D-7 chốt 29/10/2026; D-8 đến D-14 chốt 17/11/2026, D-15 đến D-17 chốt 18/11/2026, D-18 đến D-20 chốt 20/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>
|
||||
@@ -196,12 +196,12 @@ const PHASES = [
|
||||
{id:"m34-stats", t:"Bảng kết quả ≥ 3 seed, CI bootstrap theo giếng", s:"done", n:"Báo cáo G2 kiểm tập ID của từng điều kiện; tiến trình theo dõi dựng lại <code>report.json</code> lúc 06:32 UTC ngày 20/11 rồi kết thúc. T4 báo điểm tự động (G3 đạt ngày 20/11 nhưng số chính vẫn là điểm tự động theo protocol v3)."}
|
||||
]},
|
||||
{id:"M5", name:"M5 Hiệu chuẩn judge và phân tích lỗi", start:"2026-11-20", end:"2027-03-31", when:"20/11/2026 – 3/2027",
|
||||
out:"κ, agreement của judge (<code>outputs/m5/judge/report.json</code>), phân tích lỗi, tương quan EGS",
|
||||
out:"κ, agreement của judge (<code>outputs/m5/judge/report.json</code>), phân loại lỗi và tương quan EGS (<code>outputs/m5/errors/report.json</code>), T5 (<code>outputs/m5/t5/report.json</code>)",
|
||||
gate:{label:"G3", date:"2026-11-20", text:"chỉ dùng LLM-judge cho T4 khi κ giữa judge và điểm tự động theo đáp án XML đạt ≥ 0,6 (không có người chấm); không đạt thì T4 chỉ báo metric tự động và ghi rõ", res:"<b>G3 đạt ngày 20/11/2026</b> (protocol v3, §12 ý 34): judge chính Sonnet κ = 0,98 (CI 95% theo giếng 0,947–1,0; khớp 99/100) so với điểm tự động; Haiku (độ nhạy) κ = 0,90 (0,826–0,966). Đây là độ nhất quán với bộ chấm tự động, không phải khớp với người. Số chính của T4 vẫn là điểm tự động."},
|
||||
tasks:[
|
||||
{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:"doing", n:"Phân tích kết quả cuối xong (plan §1.7): agent − RAG +0,46 đến +0,48 (CI theo giếng loại 0, cả ba lượt); agent − tool_only −0,08 đến −0,12 (CI dưới 0): agent kém tool_only. OCR − XML +0,02 đến +0,04, CI chứa 0: không thấy OCR làm giảm điểm T4 (H5 không được ủng hộ). Tỉ lệ nhầm wellbore: RAG và C4 HTML/OCR 0,30–0,38, C4 XML 0,20, tool khoảng 0,05. Còn lại: phân loại lỗi theo họ câu hỏi và EGS (RQ4)."},
|
||||
{id:"m5-judge", t:"Hiệu chuẩn LLM-judge và đối chiếu EGS", s:"done", n:"Protocol v3 khóa trước mọi phán quyết. 100 câu trả lời văn bản tự do của VAI DeepSeek (lượt 0; enumeration 20/24, list 15/15, string 15/11 đúng/sai; 10 giếng) do Sonnet và Haiku chấm mù (subagent trong session, hai batch 50). κ so với điểm tự động: Sonnet 0,98, Haiku 0,90; giữa hai judge 0,92. Năm bất đồng: một câu trả lời dạng câu văn nêu đúng wellbore mà bộ chấm tự động chấm sai; bốn câu OCR \"MERSK INSPIRER\" Haiku chấp nhận. Không có người chấm; tương quan EGS (RQ4) sẽ dùng điểm tự động."}
|
||||
{id:"m5-t5", t:"T5 truy xuất khoảng tương đồng (nếu kịp)", s:"done", n:"Protocol v5 (SHA-256 <code>c99bb91b…</code>, khóa trước mọi điểm truy xuất), <code>scripts/20_m5_t5.py</code>, 12 test. 410 khoảng NPT (b), 10 giếng; ứng viên từ giếng khác. nDCG@10: random 0,463, depth 0,666, witsml_pre 0,495, text_pre 0,611, text_event 0,528, rrf_pre 0,670 (+0,004 so với depth, CI chứa 0). Dự báo từ 10 láng giềng AP 0,150 (0,116–0,204), prevalence 0,114 (plan §1.8, §12 ý 36)."},
|
||||
{id:"m5-err", t:"Phân tích lỗi theo họ câu hỏi và tương quan EGS (RQ4)", s:"done", n:"Phân tích kết quả cuối (plan §1.7): agent − RAG +0,46 đến +0,48 (CI theo giếng loại 0); agent − tool_only −0,08 đến −0,12 (dưới 0); OCR − XML +0,02 đến +0,04 (chứa 0, H5 không được ủng hộ). Protocol v4 khóa trước khi tính phân loại lỗi và EGS (§12 ý 35). VAI DeepSeek, tỉ lệ macro TB 3 lượt: bỏ trả lời là lỗi chính của C4/RAG (C4 XML 0,678, HTML 0,535, OCR 0,580, RAG 0,638), sau đó nhầm wellbore (0,095–0,190); tool_only và agent chủ yếu trích đúng báo cáo nhưng sai giá trị (0,14–0,15), agent thêm 6,4% lỗi gọi. Aggregation và multi_hop gần như không đúng với văn bản nhưng khoảng 0,72 với tool_only. EGS (chuyển thể: số đo + trích DDR) có ρ Spearman 0,535–0,538 với điểm tự động ở cả ba lượt: H4 không được ủng hộ; bỏ câu bỏ trả lời ρ ≈ 0,23; trong tool_only ρ 0,07. Không có người chấm."},
|
||||
{id:"m5-judge", t:"Hiệu chuẩn LLM-judge (G3)", s:"done", n:"Protocol v3 khóa trước mọi phán quyết. 100 câu trả lời văn bản tự do của VAI DeepSeek (lượt 0; enumeration 20/24, list 15/15, string 15/11 đúng/sai; 10 giếng) do Sonnet và Haiku chấm mù (subagent trong session, hai batch 50). κ so với điểm tự động: Sonnet 0,98, Haiku 0,90; giữa hai judge 0,92. Năm bất đồng: một câu trả lời dạng câu văn nêu đúng wellbore mà bộ chấm tự động chấm sai; bốn câu OCR \"MERSK INSPIRER\" Haiku chấp nhận. Không có người chấm; tương quan EGS (RQ4) dùng điểm tự động (xem dòng phân tích lỗi)."}
|
||||
]},
|
||||
{id:"M6", name:"M6 Viết và nộp", start:"2027-04-01", end:"2027-04-30", when:"4/2027",
|
||||
out:"Bản nộp",
|
||||
@@ -251,6 +251,8 @@ const DECISIONS = [
|
||||
{id:"D-16", q:"Thời gian lượt hai", p:"Lặp lại cùng ngày để đo độ lặp ngắn hạn khi đổi seed.", n:"Cập nhật sau lượt một, trước lượt hai và G1. Lịch chờ 14 ngày đã hủy (plan §12 ý 24)."},
|
||||
{id:"D-17", q:"Phạm vi báo cáo tại G1", p:"T4 và C4 là kết quả chính. T1 đoạn khoan công bố là kết quả bổ trợ. T2–T3 báo dự đoán mã DDR theo NPT (b) và độ nhạy (a).", n:"0 lớp qua đủ ngưỡng để báo điểm riêng. Giữ độ khớp và số mục trong kiểm định nhãn (plan §12 ý 26)."},
|
||||
{id:"D-18", q:"Tham chiếu của G3", p:"Không có người chấm, nên protocol v3 lấy điểm tự động theo đáp án XML làm tham chiếu cho judge; ngưỡng κ ≥ 0,6, phạm vi và hậu quả khi trượt giữ nguyên. Judge chính Sonnet, Haiku là độ nhạy.", n:"Mẫu 100 câu và prompt khóa hash trước mọi phán quyết. Đạt nghĩa là nhất quán với bộ chấm tự động, không phải khớp với người (plan §12 ý 34)."},
|
||||
{id:"D-19", q:"Luật phân loại lỗi và EGS cho RQ4", p:"Protocol v4 (mở rộng v3) khóa trước khi tính: mỗi dự đoán một lớp lỗi theo thứ tự luật; EGS của TADI chuyển thể cho câu trả lời JSON (số đo kèm đơn vị TADI + trích báo cáo DDR có thật, mục = 0); Spearman với điểm tự động, gộp và trong từng chế độ, bootstrap theo giếng; H4 được ủng hộ nếu |ρ| gộp < 0,3 ở mọi lượt.", n:"EGS ở đây là bản chuyển thể, không phải output agent của TADI. Kết quả: ρ 0,535–0,538, H4 không được ủng hộ (plan §1.7, §12 ý 35)."},
|
||||
{id:"D-20", q:"Định nghĩa T5 (truy xuất khoảng tương đồng)", p:"Protocol v5 (mở rộng v4) khóa trước mọi điểm truy xuất: mục là khoảng T3 trong lỗ của chính wellbore, biết section và formation; mức liên quan g = cùng section + cùng formation + giao nhóm nguyên nhân (0–3); ứng viên từ giếng khác (chính), wellbore khác (độ nhạy); biểu diễn không đọc mã, nguyên nhân, section hay formation; nDCG@10 chính, MRR và P@10 phụ; CI bootstrap theo giếng.", n:"T5 ngoài G2, không có cổng. Kết quả: depth là baseline mạnh nhất, không biểu diễn nào hơn depth với CI loại 0 (plan §1.8, §12 ý 36)."},
|
||||
];
|
||||
|
||||
const FINDS = [
|
||||
@@ -268,7 +270,9 @@ const FINDS = [
|
||||
{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."},
|
||||
{h:"T4: truy vấn tool vượt xa truy xuất văn bản (G2 v2, 20/11)", p:"VAI DeepSeek, accuracy macro theo họ câu hỏi (câu thuộc giếng, TB 3 lượt, điểm tự động): <b>tool_only 0,712</b>, <b>agent 0,618</b>, so với RAG 0,148, few-shot 0,151, zero-shot 0,071 và C4 XML / HTML / OCR 0,151 / 0,177 / 0,181. T2(b) che mã: DistilBERT AP 0,597 > TF-IDF 0,461 > DeepSeek zero-shot 0,405; mở mã TF-IDF 0,994. T3(b) che mã xấp xỉ ngẫu nhiên (majority 0,114, TF-IDF 0,123, DistilBERT 0,121). Không phải audit của người hay chuyên gia (plan §1.6, §12 ý 33)."},
|
||||
{h:"Agent kém tool_only; OCR không làm giảm T4; G3 đạt (20/11)", p:"Chênh lệch ghép cặp, CI 95% theo giếng, từng lượt: agent − RAG <b>+0,46 đến +0,48</b> (loại 0); agent − tool_only <b>−0,08 đến −0,12</b> (dưới 0); few-shot − zero-shot +0,07 đến +0,09 (loại 0); RAG − zero-shot +0,07 đến +0,08 (chứa 0); OCR − XML +0,02 đến +0,04 (chứa 0, cả khi loại trang lệch ngày). Tỉ lệ nhầm wellbore: RAG và C4 HTML/OCR 0,30–0,38, C4 XML 0,20, tool khoảng 0,05. Rò rỉ mã: T2(b) TF-IDF +0,531, DistilBERT +0,27 đến +0,29; T3 xấp xỉ 0. T2 DeepSeek − TF-IDF −0,055 (CI chứa 0). G3: Sonnet κ 0,98 so với điểm tự động (độ nhất quán, không phải người chấm). Số Qwen chỉ là v1 chưa đầy đủ (seed 0)."}
|
||||
{h:"Agent kém tool_only; OCR không làm giảm T4; G3 đạt (20/11)", p:"Chênh lệch ghép cặp, CI 95% theo giếng, từng lượt: agent − RAG <b>+0,46 đến +0,48</b> (loại 0); agent − tool_only <b>−0,08 đến −0,12</b> (dưới 0); few-shot − zero-shot +0,07 đến +0,09 (loại 0); RAG − zero-shot +0,07 đến +0,08 (chứa 0); OCR − XML +0,02 đến +0,04 (chứa 0, cả khi loại trang lệch ngày). Tỉ lệ nhầm wellbore: RAG và C4 HTML/OCR 0,30–0,38, C4 XML 0,20, tool khoảng 0,05. Rò rỉ mã: T2(b) TF-IDF +0,531, DistilBERT +0,27 đến +0,29; T3 xấp xỉ 0. T2 DeepSeek − TF-IDF −0,055 (CI chứa 0). G3: Sonnet κ 0,98 so với điểm tự động (độ nhất quán, không phải người chấm). Số Qwen chỉ là v1 chưa đầy đủ (seed 0)."},
|
||||
{h:"Lỗi theo họ câu hỏi và EGS (RQ4, 20/11)", p:"VAI DeepSeek, TB 3 lượt: truy xuất văn bản chủ yếu <b>bỏ trả lời</b> (C4 0,54–0,68, RAG 0,64), sau đó nhầm wellbore; C4 XML thấp nhất vì bỏ trả lời nhiều nhất (lookup 0,76 so với 0,45 ở HTML/OCR). Aggregation: C4/RAG đúng 0,02–0,03, tool_only 0,73. tool_only và agent sai chủ yếu ở giá trị dù đã trích đúng báo cáo (0,14–0,15). EGS chuyển thể: <b>ρ 0,535–0,538</b> với điểm tự động, nên H4 (tương quan yếu) không được ủng hộ; accuracy theo mức EGS 0 / 1/3 / 2/3 = 0,01 / 0,22 / 0,67. Bỏ câu bỏ trả lời ρ ≈ 0,23; trong tool_only ρ 0,07: EGS chủ yếu tách câu có trả lời khỏi câu bỏ trả lời, không thay được điểm theo đáp án XML. Không có người chấm (plan §1.7)."},
|
||||
{h:"T5: độ sâu là baseline mạnh nhất (20/11)", p:"Truy xuất khoảng tương đồng (protocol v5, NPT b, 410 truy vấn, ứng viên từ giếng khác): nDCG@10 depth 0,666 so với random 0,463; comment 24 h trước khoảng 0,611; WITSML 24 h trước 0,495; RRF 0,670 (+0,004, CI chứa 0). Trong một mỏ, section và formation gần như do độ sâu quyết định; nhóm nguyên nhân gần như không tách được (giao nguyên nhân trong top 10: 0,70 random, 0,75 tốt nhất). Dự báo từ láng giềng AP 0,150 so với prevalence 0,114 nên T3/T5 vẫn là chẩn đoán (plan §1.8)."},
|
||||
];
|
||||
|
||||
const OCRQC = [
|
||||
@@ -324,7 +328,9 @@ const LOG = [
|
||||
["2026-11-19","Dừng Qwen và Llama v1; protocol v2: VAI DeepSeek-V4.1-Flash-1017 chạy toàn ma trận (bắt đầu 03:22 UTC), Sonnet và Haiku chạy mẫu trong session (plan §12 ý 32)."],
|
||||
["2026-11-19","Mẫu Sonnet/Haiku xong 110/110 batch mỗi model (plan §12 ý 33)."],
|
||||
["2026-11-20","VAI DeepSeek xong T4/C4 48.951/48.951 và T2 70.341/70.341; mọi shard DistilBERT xong lúc 06:27 UTC. Báo cáo dựng lại lúc 06:32 UTC: <b>G2 v2 đạt</b>, G2 v1 không thể đạt. T4 tool_only 0,712 và agent 0,618 so với RAG 0,148 và zero-shot 0,071; T3 xấp xỉ ngẫu nhiên. Còn lại G3, viết bài, điều khoản phát hành ở G4 (plan §12 ý 33)."],
|
||||
["2026-11-20","Protocol v3 khóa (tham chiếu G3 là điểm tự động theo đáp án XML, không có người chấm). <b>G3 đạt</b>: Sonnet κ 0,98 (CI 0,947–1,0), Haiku 0,90 trên 100 câu trả lời văn bản tự do; số chính T4 vẫn là điểm tự động. Phân tích kết quả cuối: agent kém tool_only, OCR không kém XML trên T4, RAG và C4 HTML/OCR nhầm wellbore 0,30–0,38 (plan §1.7, §12 ý 34)."],
|
||||
["2026-11-20","Protocol v3 khóa (tham chiếu G3 là điểm tự động theo đáp án XML, không có người chấm). <b>G3 đạt</b>: Sonnet κ 0,98 (CI 0,947–1,0), Haiku 0,90 trên 100 câu trả lời văn bản tự do; số chính T4 vẫn là điểm tự động. Phân tích kết quả cuối: agent kém tool_only, OCR không kém XML trên T4, RAG và C4 HTML/OCR nhầm wellbore 0,30–0,38 (plan §1.7, §12 ý 34)."],,
|
||||
["2026-11-20","Protocol v4 khóa (SHA-256 <code>6a9ad0fb…</code>) trước khi tính phân loại lỗi và EGS. <code>scripts/19_m5_errors.py</code> (3 phút, <code>20261120-071047_m5_errors</code>): lớp \"đúng\" khớp số chính G2 v2; bỏ trả lời là lỗi chính của C4/RAG; EGS ρ 0,535–0,538 với điểm tự động (H4 không được ủng hộ; bỏ câu bỏ trả lời ρ ≈ 0,23). 192 test đạt."],
|
||||
["2026-11-20","Protocol v5 khóa (SHA-256 <code>c99bb91b…</code>) trước mọi điểm truy xuất T5; trước đó chỉ xem số đếm nhãn. <code>scripts/20_m5_t5.py</code> (1 phút 36 giây, <code>20261120-073123_m5_t5</code>): depth nDCG@10 0,666, random 0,463, rrf_pre 0,670 (CI hiệu với depth chứa 0); kNN AP 0,150. 204 test đạt (plan §1.8, §12 ý 36)."],
|
||||
];
|
||||
/* ===================== HẾT DATA ===================== */
|
||||
|
||||
|
||||
86
scripts/19_m5_errors.py
Normal file
86
scripts/19_m5_errors.py
Normal file
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M5 error taxonomy by question family and RQ4 (EGS against the automatic score) under protocol v4.
|
||||
|
||||
scripts/19_m5_errors.py read the complete T4 runs, write outputs/m5/errors/
|
||||
|
||||
Refuses to run unless configs/protocol_v4.yaml matches its checksum and every checkpoint carries the current M3-M4
|
||||
input digests. Correctness is the automatic score against the XML answer; no human rater exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import duckdb
|
||||
import yaml
|
||||
|
||||
from volve_dia import m34, m5_errors as me
|
||||
from volve_dia.m34_qa import qa_universe
|
||||
from volve_dia.m5_judge import sha256_file
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROTOCOL = ROOT / "configs/protocol_v4.yaml"
|
||||
PRIMARY = "vai-deepseek-v4-1-flash"
|
||||
RESAMPLES, SEED = 2000, 20261117
|
||||
SHARE_COLUMNS = ("n",) + me.CLASSES
|
||||
|
||||
|
||||
def main():
|
||||
expected = (PROTOCOL.with_suffix(".yaml.sha256")).read_text().split()[0]
|
||||
if sha256_file(PROTOCOL) != expected:
|
||||
raise SystemExit("configs/protocol_v4.yaml does not match its checksum")
|
||||
v4 = yaml.safe_load(PROTOCOL.read_text())
|
||||
protocol, _ = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
out = root / "m34"
|
||||
questions, paired, _, blocked = qa_universe(root, protocol)
|
||||
by_id = {q["id"]: q for q in questions}
|
||||
paired_ids = {q["id"] for q in paired}
|
||||
sets = {"c4": paired_ids, "c4_clean": paired_ids - blocked}
|
||||
all_ids = set(by_id)
|
||||
|
||||
with duckdb.connect(str(root / "ddr/volve_ddr.duckdb"), read_only=True) as con:
|
||||
known = {r[0] for r in con.execute("SELECT report_id FROM reports").fetchall()}
|
||||
sources = [(db, PRIMARY) for db in sorted((out / f"v2/qa/{PRIMARY}").glob("rep*.sqlite"))]
|
||||
sources.append((out / "qa/qwen.sqlite", "qwen"))
|
||||
frame = me.load_predictions(sources, digests, by_id, known)
|
||||
frame, coverage = me.complete_runs(frame, lambda mode: sets.get(mode, all_ids))
|
||||
frame = frame[frame["scope"].ne("field")].reset_index(drop=True)
|
||||
|
||||
dest = root / "m5/errors"
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
tax = me.taxonomy(frame)
|
||||
tax.to_csv(dest / "taxonomy_by_run.csv", index=False)
|
||||
summary = me.mean_over_seeds(tax, ["model", "mode", "modality", "family"], SHARE_COLUMNS)
|
||||
summary.to_csv(dest / "taxonomy.csv", index=False)
|
||||
me.by_answer_type(frame).to_csv(dest / "by_answer_type.csv", index=False)
|
||||
rows = me.rq4(frame, RESAMPLES, SEED)
|
||||
egs = frame.groupby(["model", "mode", "modality", "seed"]).agg(
|
||||
n=("egs", "size"), mean_egs=("egs", "mean"), measurement=("measurement", "mean"),
|
||||
measurement_ext=("measurement_ext", "mean"), ddr_reference=("ddr_reference", "mean"),
|
||||
accuracy=("correct", "mean")).reset_index()
|
||||
egs.to_csv(dest / "egs_by_run.csv", index=False)
|
||||
frame.drop(columns=["answerable"]).to_parquet(dest / "predictions.parquet", index=False)
|
||||
|
||||
macro = summary[summary["family"].eq("macro")]
|
||||
report = {
|
||||
"protocol": {"file": str(PROTOCOL.relative_to(ROOT)), "sha256": expected, "version": v4["version"]},
|
||||
"inputs": digests,
|
||||
"reference": "automatic score against the XML answer (no human rater)",
|
||||
"coverage": coverage,
|
||||
"n_predictions_well_scoped": int(len(frame)),
|
||||
"taxonomy_macro": json.loads(macro.to_json(orient="records")),
|
||||
"rq4": rows,
|
||||
"h4": [me.h4_reading(rows, model) for model in sorted(frame["model"].unique())],
|
||||
"primary_model": PRIMARY,
|
||||
}
|
||||
m34.atomic_write(dest / "report.json", json.dumps(report, indent=1).encode())
|
||||
for h in report["h4"]:
|
||||
print(h)
|
||||
print(macro[["model", "mode", "modality", "correct", "wrong_wellbore", "no_citation", "evidence_missed",
|
||||
"wrong_with_evidence", "abstained", "answered_unanswerable"]].round(3).to_string(index=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
133
scripts/20_m5_t5.py
Normal file
133
scripts/20_m5_t5.py
Normal file
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""T5 similar-interval retrieval and the neighbour forecast under protocol v5.
|
||||
|
||||
scripts/20_m5_t5.py build the T5 items, score every representation, write outputs/m5/t5/
|
||||
|
||||
Refuses to run unless configs/protocol_v5.yaml matches its checksum. Relevance labels come from the XML-derived T3
|
||||
intervals, the T1 section and the formation picks; no representation reads codes, causes, labels, section or formation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from volve_dia import m34, m5_t5 as t5
|
||||
from volve_dia.m34_features import witsml_windows
|
||||
from volve_dia.m5_judge import sha256_file
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROTOCOL = ROOT / "configs/protocol_v5.yaml"
|
||||
RESAMPLES, SEED, HISTORY = 2000, 20261117, pd.Timedelta(hours=24)
|
||||
RUNS = (("b", "well", "primary"), ("a", "well", "sensitivity_definition"),
|
||||
("b", "wellbore", "sensitivity_pool"), ("a", "wellbore", "sensitivity_definition_pool"))
|
||||
V1_T3_AP = {"majority": 0.114, "tfidf": 0.123}
|
||||
|
||||
|
||||
def pre_event_text(items, acts):
|
||||
"""Masked comments of the same wellbore's activities that end in [start - 24 h, start), in time order."""
|
||||
acts = acts.dropna(subset=["end_utc"]).sort_values(["wellbore", "end_utc", "act_id"])
|
||||
by_wellbore = {w: g for w, g in acts.groupby("wellbore")}
|
||||
texts = []
|
||||
for wellbore, start in zip(items["wellbore"], items["first_start_utc"]):
|
||||
g = by_wellbore.get(wellbore)
|
||||
if g is None:
|
||||
texts.append("")
|
||||
continue
|
||||
window = g[g["end_utc"].lt(start) & g["end_utc"].ge(start - HISTORY)]
|
||||
texts.append(t5.DELIMITER.join(window["comments"].dropna()))
|
||||
return texts
|
||||
|
||||
|
||||
def build_items(root, protocol, spec, definition):
|
||||
intervals = pd.read_parquet(root / "labels/t3_intervals.parquet")
|
||||
cells = pd.read_parquet(root / "labels/t3_cells.parquet")
|
||||
sections = pd.read_parquet(root / "labels/t1_reports.parquet", columns=["report_id", "section"])
|
||||
sections = sections.set_index("report_id")["section"]
|
||||
picks = pd.read_parquet(root / "witsml/formation_tops.parquet", columns=["wellbore", "unit", "md"])
|
||||
picks = picks.dropna(subset=["wellbore", "md"])
|
||||
items = t5.eligible_intervals(intervals, cells, sections, picks, protocol["tasks"]["t3"]["wellbores"], definition)
|
||||
acts = pd.read_parquet(root / "labels/t2_inputs.parquet",
|
||||
columns=["act_id", "wellbore", "end_utc", "comments"])
|
||||
comments = acts.set_index("act_id")["comments"]
|
||||
items["text_pre"] = pre_event_text(items, acts)
|
||||
items["text_event"] = items["act_ids"].map(
|
||||
lambda ids: t5.DELIMITER.join(str(c) for c in comments.reindex(sorted(ids)).dropna()))
|
||||
windows = items[["interval_id", "wellbore", "first_start_utc"]].rename(
|
||||
columns={"interval_id": "item", "first_start_utc": "window_end"})
|
||||
windows["window_start"] = windows["window_end"] - HISTORY
|
||||
stats = witsml_windows(root, windows, protocol, spec).reindex(columns=list(t5.WITSML_COLUMNS))
|
||||
items = items.join(stats, on="interval_id")
|
||||
return items
|
||||
|
||||
|
||||
def label_counts(items):
|
||||
return {"n": int(len(items)), "wells": int(items["well"].nunique()), "wellbores": int(items["wellbore"].nunique()),
|
||||
"by_well": items["well"].value_counts().sort_index().to_dict(),
|
||||
"by_section": items["section"].value_counts().to_dict(),
|
||||
"by_formation": items["formation"].value_counts().to_dict(),
|
||||
"witsml_missing_share": float(items[list(t5.WITSML_COLUMNS)].isna().all(axis=1).mean()),
|
||||
"text_pre_empty_share": float(items["text_pre"].eq("").mean())}
|
||||
|
||||
|
||||
def main():
|
||||
expected = PROTOCOL.with_suffix(".yaml.sha256").read_text().split()[0]
|
||||
if sha256_file(PROTOCOL) != expected:
|
||||
raise SystemExit("configs/protocol_v5.yaml does not match its checksum")
|
||||
v5 = yaml.safe_load(PROTOCOL.read_text())
|
||||
protocol, spec = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
dest = root / "m5/t5"
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
report = {"protocol": {"file": str(PROTOCOL.relative_to(ROOT)), "sha256": expected, "version": v5["version"]},
|
||||
"inputs": digests, "items": {}, "retrieval": {}, "knn_forecast": {}}
|
||||
frames = []
|
||||
items_by_def = {d: build_items(root, protocol, spec, d) for d in ("a", "b")}
|
||||
for d, items in items_by_def.items():
|
||||
report["items"][d] = label_counts(items)
|
||||
items.drop(columns=["cause_set"]).assign(act_ids=items["act_ids"].map(list)).to_parquet(
|
||||
dest / f"items_{d}.parquet", index=False)
|
||||
for definition, group, name in RUNS:
|
||||
per_query = t5.evaluate(items_by_def[definition], group, SEED)
|
||||
per_query.insert(0, "run", name)
|
||||
frames.append(per_query)
|
||||
first = per_query.drop_duplicates("interval_id")
|
||||
report["retrieval"][name] = {
|
||||
"definition": definition, "held_out": group, "n_queries": int(len(first)),
|
||||
"queries_without_fully_relevant": int(first["n_fully_relevant"].eq(0).sum()),
|
||||
"median_fully_relevant": float(first["n_fully_relevant"].median()),
|
||||
"median_candidates": float(first["n_candidates"].median()),
|
||||
"representations": t5.summarise(per_query, RESAMPLES, SEED)}
|
||||
print(name, {r: round(v["ndcg10"]["mean"], 3) for r, v in report["retrieval"][name]["representations"].items()})
|
||||
pd.concat(frames, ignore_index=True).to_parquet(dest / "per_query.parquet", index=False)
|
||||
|
||||
features = pd.read_parquet(root / "m34/features_t3.parquet")
|
||||
columns = {"depth": ["md_top"], "depth_witsml": ["md_top", "depth_from_own_top", *t5.WITSML_COLUMNS]}
|
||||
knn = features[["item", "well", "wellbore", "label_a", "label_b"]].copy()
|
||||
for label in ("label_b", "label_a"):
|
||||
block = {}
|
||||
for rep, cols in columns.items():
|
||||
scores = t5.knn_scores(features, label, cols)
|
||||
knn[f"{rep}_{label}"] = scores
|
||||
block[rep] = t5.ap_ci(features[label], scores, features["well"], RESAMPLES, SEED)
|
||||
report["knn_forecast"][label] = block
|
||||
print(label, {r: round(v["ap"], 3) for r, v in block.items()}, "prevalence",
|
||||
round(block["depth"]["prevalence"], 3))
|
||||
report["knn_forecast"]["v1_t3_reference_ap_b_masked"] = V1_T3_AP
|
||||
knn.to_parquet(dest / "knn_scores.parquet", index=False)
|
||||
m34.atomic_write(dest / "report.json", json.dumps(report, indent=1, default=_json).encode())
|
||||
|
||||
|
||||
def _json(value):
|
||||
if isinstance(value, (np.integer, np.floating)):
|
||||
return value.item()
|
||||
raise TypeError(type(value))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
99
tests/test_m5_errors.py
Normal file
99
tests/test_m5_errors.py
Normal file
@@ -0,0 +1,99 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from volve_dia import m5_errors as me
|
||||
|
||||
KNOWN = {"15_9_F_14_2008_05_23"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer,unit,tadi,ext", [
|
||||
("3520", "m", True, True), ("3,520.5 m", "", True, True), ("1.48", "g/cm3", True, True),
|
||||
("12", "hours", False, True), ("12 1/4", "in", False, True), ("3520", "mMD", False, True),
|
||||
("3520 m MD", "", True, True), ("15/9-F-14", "", False, False), ("MAERSK INSPIRER", "", False, False),
|
||||
("25", "%", True, True), ("40", "mm", False, False), ("2008-05-23", "", False, False)])
|
||||
def test_has_measurement(answer, unit, tadi, ext):
|
||||
p = {"answer": answer, "unit": unit}
|
||||
assert me.has_measurement(p) is tadi
|
||||
assert me.has_measurement(p, me.EXTENDED_MEASUREMENT) is ext
|
||||
|
||||
|
||||
def test_ddr_reference_and_egs():
|
||||
cited = {"answer": "3520", "unit": "m", "citations": ["reports:15_9_F_14_2008_05_23"]}
|
||||
assert me.has_ddr_reference(cited, KNOWN)
|
||||
assert me.has_ddr_reference({"citations": ["activities:15_9_F_14_2008_05_23:3"]}, KNOWN)
|
||||
assert not me.has_ddr_reference({"citations": ["reports:15_9_F_99_2008_05_23", "nonsense"]}, KNOWN)
|
||||
assert me.egs(cited, KNOWN) == pytest.approx(2 / 3)
|
||||
assert me.egs({"answer": None, "citations": []}, KNOWN) == 0
|
||||
|
||||
|
||||
def row(**kw):
|
||||
base = {"correct": False, "failed": False, "answerable": True, "abstained": False, "wrong_wellbore": False,
|
||||
"n_citations": 1, "report_recall": 0.0}
|
||||
return base | kw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kw,expected", [
|
||||
({"correct": True}, "correct"), ({"failed": True}, "failed"), ({"answerable": False}, "answered_unanswerable"),
|
||||
({"abstained": True, "wrong_wellbore": True}, "abstained"), ({"wrong_wellbore": True}, "wrong_wellbore"),
|
||||
({"n_citations": 0}, "no_citation"), ({"report_recall": None}, "evidence_missed"),
|
||||
({"report_recall": 0.5}, "wrong_with_evidence"), ({"answerable": False, "correct": True}, "correct")])
|
||||
def test_error_class_first_rule_wins(kw, expected):
|
||||
assert me.error_class(row(**kw)) == expected
|
||||
|
||||
|
||||
def store(path, rows, inputs):
|
||||
con = sqlite3.connect(path)
|
||||
con.execute("CREATE TABLE metadata (provenance TEXT)")
|
||||
con.execute("INSERT INTO metadata VALUES (?)", (json.dumps({"inputs": inputs}),))
|
||||
con.execute("CREATE TABLE predictions (mode TEXT, modality TEXT, seed INT, item TEXT, data TEXT)")
|
||||
con.executemany("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)", rows)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def test_load_complete_and_taxonomy(tmp_path):
|
||||
questions = {f"q{i}": {"well": f"W{i % 2}", "family": ("lookup", "aggregation")[i % 2], "template_id": "T",
|
||||
"scope": "single", "answer_type": "number", "answerable": i != 3} for i in range(4)}
|
||||
preds = []
|
||||
for i in range(4):
|
||||
d = {"item": f"q{i}", "failed": False, "correct": i in (0, 3), "wrong_wellbore": i == 1,
|
||||
"report_recall": 0.0, "prediction": {"answer": None if i == 3 else "10", "unit": "m",
|
||||
"citations": ["reports:15_9_F_14_2008_05_23"]}}
|
||||
preds.append(("rag", "xml", 0, f"q{i}", json.dumps(d)))
|
||||
store(tmp_path / "a.sqlite", preds, {"x": "1"})
|
||||
store(tmp_path / "b.sqlite", preds[:2], {"x": "1"})
|
||||
with pytest.raises(ValueError, match="Stale"):
|
||||
me.load_predictions([(tmp_path / "a.sqlite", "m")], {"x": "2"}, questions, KNOWN)
|
||||
frame = me.load_predictions([(tmp_path / "a.sqlite", "m"), (tmp_path / "b.sqlite", "n")], {"x": "1"},
|
||||
questions, KNOWN)
|
||||
kept, coverage = me.complete_runs(frame, lambda mode: set(questions))
|
||||
assert set(kept["model"]) == {"m"} and [c["complete"] for c in coverage] == [True, False]
|
||||
assert list(kept.sort_values("item")["error_class"]) == ["correct", "wrong_wellbore", "evidence_missed",
|
||||
"correct"]
|
||||
assert kept.loc[kept["item"] == "q3", "egs"].item() == pytest.approx(1 / 3)
|
||||
tax = me.taxonomy(kept)
|
||||
macro = tax[tax["family"] == "macro"].iloc[0]
|
||||
assert macro["correct"] == pytest.approx((0.5 + 0.5) / 2) and macro["n"] == 4
|
||||
assert macro["wrong_wellbore"] == pytest.approx((0 + 0.5) / 2)
|
||||
|
||||
|
||||
def test_spearman_bootstrap_and_h4():
|
||||
rng = np.random.default_rng(0)
|
||||
n = 400
|
||||
frame = pd.DataFrame({"well": rng.choice(list("ABCDEFGH"), n), "egs": rng.choice([0, 1 / 3, 2 / 3], n),
|
||||
"mode": "rag", "modality": "xml", "model": "m", "seed": 0, "answerable": True,
|
||||
"failed": False, "abstained": False})
|
||||
frame["egs_ext"] = frame["egs"]
|
||||
frame["correct"] = rng.random(n) < 0.2 + 0.6 * frame["egs"]
|
||||
rows = me.rq4(frame, 200, 1)
|
||||
pooled = [r for r in rows if r["variant"] == "primary" and r["mode"] == "pooled"][0]
|
||||
assert pooled["rho"] > 0.3 and pooled["ci95"][0] < pooled["rho"] < pooled["ci95"][1]
|
||||
assert set(pooled["by_level"]) == {"0.000", "0.333", "0.667"}
|
||||
assert me.h4_reading(rows, "m")["reading"] == "not supported"
|
||||
assert me.spearman([0, 0, 0], [1, 0, 1]) is None
|
||||
107
tests/test_m5_t5.py
Normal file
107
tests/test_m5_t5.py
Normal file
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from volve_dia import m5_t5 as t5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unit,expected", [
|
||||
("Hugin Fm. VOLVE", "hugin"), ("Heather Fm. Sand VOLVE", "heather"), ("NORDLAND GP.", "nordland"),
|
||||
("Smith Bank Fm.", "smith bank"), ("Seabed", "seabed"), ("Heather Fm.", "heather")])
|
||||
def test_normalise_unit(unit, expected):
|
||||
assert t5.normalise_unit(unit) == expected
|
||||
|
||||
|
||||
def test_formation_and_eligibility():
|
||||
picks = pd.DataFrame({"wellbore": ["W1", "W1", "W1"], "unit": ["NORDLAND GP.", "Utsira Fm.", "Hugin Fm. VOLVE"],
|
||||
"md": [100.0, 500.0, 3000.0]})
|
||||
assert t5.formation_at(picks, "W1", 50) is None
|
||||
assert t5.formation_at(picks, "W1", 500) == "utsira"
|
||||
assert t5.formation_at(picks, "W1", 3500) == "hugin"
|
||||
intervals = pd.DataFrame({
|
||||
"interval_id": ["W1:b:I1", "W1:b:I2", "W1:b:I3", "W1:a:I1", "W2:b:I1"], "definition": ["b", "b", "b", "a", "b"],
|
||||
"wellbore": ["W1", "W1", "W1", "W1", "W2"], "well": ["A"] * 5, "md_top": [80.0, 600.0, 3100.0, 600.0, 700.0],
|
||||
"causes": ["equipment", "equipment|weather", None, "other", "other"],
|
||||
"act_ids": [["W1_2008_01_02:001"], ["W1_2008_01_03:004", "W1_2008_01_03:002"], ["W1_2008_01_09:001"],
|
||||
["W1_2008_01_03:002"], ["W2_2008_02_01:001"]]})
|
||||
cells = pd.DataFrame({"wellbore": ["W1", "W2"], "own_hole_top_md": [50.0, 0.0]})
|
||||
sections = pd.Series({"W1_2008_01_02": "26", "W1_2008_01_03": "12.25"})
|
||||
items = t5.eligible_intervals(intervals, cells, sections, picks, ["W1"], "b")
|
||||
# I1 lies above the first pick, I3 has no section, W2 is not a T3 wellbore.
|
||||
assert list(items["interval_id"]) == ["W1:b:I2"]
|
||||
row = items.iloc[0]
|
||||
assert row["report_id"] == "W1_2008_01_03" and row["formation"] == "utsira"
|
||||
assert row["cause_set"] == frozenset({"equipment", "weather"})
|
||||
|
||||
|
||||
def test_gains_and_metrics():
|
||||
query = pd.Series({"section": "8.5", "formation": "hugin", "cause_set": frozenset({"equipment"})})
|
||||
pool = pd.DataFrame({"section": ["8.5", "8.5", "12.25", "8.5"], "formation": ["hugin", "ty", "hugin", "hugin"],
|
||||
"cause_set": [frozenset({"equipment", "weather"}), frozenset(), frozenset({"equipment"}),
|
||||
frozenset({"weather"})]})
|
||||
gain, parts = t5.gains(query, pool)
|
||||
assert list(gain) == [3, 1, 2, 2]
|
||||
best = t5.ranking_metrics(np.array([0, 2, 3, 1]), gain, parts, k=2)
|
||||
assert best["ndcg10"] == pytest.approx(1.0) and best["mrr"] == 1.0 and best["p10"] == 0.5
|
||||
worst = t5.ranking_metrics(np.array([1, 2, 3, 0]), gain, parts, k=2)
|
||||
idcg = 3 + 2 / np.log2(3)
|
||||
assert worst["ndcg10"] == pytest.approx((1 + 2 / np.log2(3)) / idcg) and worst["mrr"] == 0.25
|
||||
assert worst["section10"] == 0.5 and worst["formation10"] == 0.5
|
||||
none = t5.ranking_metrics(np.array([1, 0]), np.array([0, 2]), {a: np.zeros(2, bool) for a in t5.ATTRIBUTES}, k=2)
|
||||
assert np.isnan(none["mrr"])
|
||||
|
||||
|
||||
def test_order_ties_and_rrf():
|
||||
assert list(t5.order([1.0, 2.0, 1.0], np.array([2, 0, 1]))) == [1, 2, 0]
|
||||
fused = t5.rrf([np.array([3.0, 2.0, 1.0]), np.array([1.0, 2.0, 3.0])], np.arange(3))
|
||||
assert fused[1] == pytest.approx(2 / 62) and fused[0] == pytest.approx(fused[2])
|
||||
|
||||
|
||||
def synthetic_items(n_wells=4, per_well=12, seed=0):
|
||||
rng = np.random.default_rng(seed)
|
||||
rows = []
|
||||
for w in range(n_wells):
|
||||
for i in range(per_well):
|
||||
deep = i % 2 == 0
|
||||
rows.append({"interval_id": f"W{w}:b:I{i:02d}", "well": f"W{w}", "wellbore": f"W{w}",
|
||||
"md_top": (3000.0 if deep else 500.0) + rng.normal(0, 50),
|
||||
"section": "8.5" if deep else "17.5", "formation": "hugin" if deep else "utsira",
|
||||
"cause_set": frozenset({"equipment" if deep else "weather"}),
|
||||
"text_pre": "reaming tight hole" if deep else "waiting on weather",
|
||||
"text_event": "packed off" if deep else "crane stopped wind",
|
||||
**{c: rng.normal(5 if deep else 0, 1) for c in t5.WITSML_COLUMNS}})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def test_evaluate_and_summarise():
|
||||
items = synthetic_items()
|
||||
per_query = t5.evaluate(items, "well", seed=1, orders=20)
|
||||
assert set(per_query["representation"]) == set(t5.REPRESENTATIONS)
|
||||
assert per_query.groupby("representation").size().eq(len(items)).all()
|
||||
assert (per_query["n_candidates"] == 36).all() and (per_query["n_fully_relevant"] == 18).all()
|
||||
mean = per_query.groupby("representation")["ndcg10"].mean()
|
||||
for rep in ("depth", "witsml_pre", "text_pre", "text_event", "rrf_pre", "rrf_all"):
|
||||
assert mean[rep] == pytest.approx(1.0)
|
||||
assert mean["random"] < 0.9
|
||||
summary = t5.summarise(per_query, resamples=200, seed=1)
|
||||
depth = summary["depth"]
|
||||
assert depth["ndcg10"]["mean"] == pytest.approx(1.0)
|
||||
assert depth["ndcg10_minus_random"]["ci95"][0] > 0
|
||||
assert "ndcg10_minus_depth" not in depth and "ndcg10_minus_random" not in summary["random"]
|
||||
|
||||
|
||||
def test_cluster_ci_weights_queries():
|
||||
out = t5.cluster_ci([1.0, 1.0, 1.0, 0.0, np.nan], ["A", "A", "A", "B", "B"], 500, 0)
|
||||
assert out["n"] == 4 and out["mean"] == pytest.approx(0.75)
|
||||
assert out["ci95"][0] <= 0.75 <= out["ci95"][1]
|
||||
|
||||
|
||||
def test_knn_scores_leave_group_out():
|
||||
features = pd.DataFrame({"well": ["A"] * 4 + ["B"] * 4, "md_top": [10.0, 20, 30, 40] * 2,
|
||||
"label_b": [1, 0, 0, 0, 1, 0, 0, 0]})
|
||||
scores = t5.knn_scores(features, "label_b", ["md_top"], k=1)
|
||||
assert list(scores) == [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
|
||||
result = t5.ap_ci(features["label_b"], scores, features["well"], 100, 0)
|
||||
assert result["ap"] == pytest.approx(1.0) and result["prevalence"] == 0.25
|
||||
229
volve_dia/m5_errors.py
Normal file
229
volve_dia/m5_errors.py
Normal file
@@ -0,0 +1,229 @@
|
||||
"""M5 error taxonomy by question family and RQ4 (protocol v4): the EGS proxy of TADI, adapted to the JSON answer
|
||||
format of the T4 baselines, against the automatic score from the XML answer. No human rater exists."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import spearmanr
|
||||
|
||||
from . import t4
|
||||
|
||||
FAMILIES = ("lookup", "aggregation", "temporal_event", "comparison", "multi_hop")
|
||||
ANSWERABLE_CLASSES = ("correct", "failed", "abstained", "wrong_wellbore", "no_citation", "evidence_missed",
|
||||
"wrong_with_evidence")
|
||||
UNANSWERABLE_CLASSES = ("correct", "failed", "answered_unanswerable")
|
||||
CLASSES = tuple(dict.fromkeys(ANSWERABLE_CLASSES + UNANSWERABLE_CLASSES))
|
||||
TADI_UNITS = ("m/hr", "g/cm3", "mPa", "ppm", "hrs", "days", "kN", "sg", "Pa", "m", "%")
|
||||
EXTENDED_UNITS = TADI_UNITS + ("ft/h", "hours", "hour", "hr", "h", "metres", "metre", "meters", "meter", "mMD",
|
||||
"mTVD", "inches", "inch", "in", "ft", "degrees", "degree", "deg", "bar", "psi", "pcf",
|
||||
"degC")
|
||||
NUMBER = r"(?<![\w.])-?\d+(?:[.,]\d+)*(?:\s+\d+/\d+)?"
|
||||
|
||||
|
||||
def unit_pattern(units):
|
||||
"""A number followed by one of `units` as a whole token (longest unit first), case-insensitive."""
|
||||
alternatives = "|".join(re.escape(u) for u in sorted(units, key=len, reverse=True))
|
||||
return re.compile(rf"{NUMBER}\s*(?:{alternatives})(?![\w/])", re.IGNORECASE)
|
||||
|
||||
|
||||
TADI_MEASUREMENT = unit_pattern(TADI_UNITS)
|
||||
EXTENDED_MEASUREMENT = unit_pattern(EXTENDED_UNITS)
|
||||
|
||||
|
||||
def answer_text(prediction):
|
||||
answer = prediction.get("answer")
|
||||
if isinstance(answer, (list, tuple)):
|
||||
answer = "; ".join(str(a) for a in answer)
|
||||
unit = prediction.get("unit") or ""
|
||||
return f"{'' if answer is None else answer} {unit}".strip()
|
||||
|
||||
|
||||
def has_measurement(prediction, pattern=TADI_MEASUREMENT):
|
||||
return bool(pattern.search(answer_text(prediction)))
|
||||
|
||||
|
||||
def has_ddr_reference(prediction, known_reports):
|
||||
"""At least one citation that resolves to a known DDR report id (wellbore and date)."""
|
||||
for c in prediction.get("citations") or []:
|
||||
parsed = t4.parse_citation(c)
|
||||
if parsed and len(parsed.split(":")) > 1 and parsed.split(":")[1] in known_reports:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def egs(prediction, known_reports, pattern=TADI_MEASUREMENT):
|
||||
"""TADI eq. 3 with the section term fixed at 0: (has_measurement + has_ddr_quote + 0/6) / 3."""
|
||||
return (has_measurement(prediction, pattern) + has_ddr_reference(prediction, known_reports)) / 3
|
||||
|
||||
|
||||
def error_class(row):
|
||||
"""One class per prediction, first matching rule (protocol v4)."""
|
||||
if row["correct"]:
|
||||
return "correct"
|
||||
if row["failed"]:
|
||||
return "failed"
|
||||
if not row["answerable"]:
|
||||
return "answered_unanswerable"
|
||||
if row["abstained"]:
|
||||
return "abstained"
|
||||
if row["wrong_wellbore"]:
|
||||
return "wrong_wellbore"
|
||||
if row["n_citations"] == 0:
|
||||
return "no_citation"
|
||||
if not (row["report_recall"] or 0) > 0:
|
||||
return "evidence_missed"
|
||||
return "wrong_with_evidence"
|
||||
|
||||
|
||||
def load_predictions(sources, digests, questions, known_reports):
|
||||
"""Rows for every prediction of the given checkpoints [(path, model)], with the EGS signals of the answer."""
|
||||
rows = []
|
||||
for db, model in sources:
|
||||
with closing(sqlite3.connect(f"{Path(db).resolve().as_uri()}?mode=ro", uri=True)) as con:
|
||||
meta = json.loads(con.execute("SELECT provenance FROM metadata").fetchone()[0])
|
||||
if digests is not None and meta["inputs"] != digests:
|
||||
raise ValueError(f"Stale T4 provenance for {db}.")
|
||||
query = ("SELECT mode, modality, seed, item, json_remove(data, '$.retrieved', '$.trace') "
|
||||
"FROM predictions")
|
||||
for mode, modality, seed, item, data in con.execute(query):
|
||||
d = json.loads(data)
|
||||
q = questions[item]
|
||||
p = d.get("prediction") or {}
|
||||
rows.append({
|
||||
"model": model, "mode": mode, "modality": modality, "seed": int(seed), "item": item,
|
||||
"well": q["well"], "family": q["family"], "template": q["template_id"], "scope": q["scope"],
|
||||
"answer_type": q["answer_type"], "answerable": bool(q["answerable"]),
|
||||
"failed": bool(d["failed"]), "correct": bool(d["correct"]),
|
||||
"wrong_wellbore": bool(d["wrong_wellbore"]), "report_recall": d["report_recall"],
|
||||
"abstained": t4.is_abstention(p.get("answer")),
|
||||
"n_citations": len(p.get("citations") or []),
|
||||
"measurement": has_measurement(p), "measurement_ext": has_measurement(p, EXTENDED_MEASUREMENT),
|
||||
"ddr_reference": has_ddr_reference(p, known_reports)})
|
||||
frame = pd.DataFrame(rows)
|
||||
if frame.empty:
|
||||
return frame
|
||||
frame["egs"] = (frame["measurement"].astype(int) + frame["ddr_reference"].astype(int)) / 3
|
||||
frame["egs_ext"] = (frame["measurement_ext"].astype(int) + frame["ddr_reference"].astype(int)) / 3
|
||||
frame["error_class"] = frame.apply(error_class, axis=1)
|
||||
return frame
|
||||
|
||||
|
||||
def complete_runs(frame, expected):
|
||||
"""Keep runs whose item set equals the locked set of their condition; `expected(mode)` gives that set."""
|
||||
keep, coverage = [], []
|
||||
for keys, run in frame.groupby(["model", "mode", "modality", "seed"], sort=True):
|
||||
want = expected(keys[1])
|
||||
ok = len(run) == len(want) and set(run["item"]) == want
|
||||
coverage.append(dict(zip(("model", "mode", "modality", "seed"), keys)) | {
|
||||
"n": len(run), "expected": len(want), "complete": ok})
|
||||
if ok:
|
||||
keep.append(run)
|
||||
return (pd.concat(keep, ignore_index=True) if keep else frame.iloc[:0]), coverage
|
||||
|
||||
|
||||
def taxonomy(frame):
|
||||
"""Class shares per run: per family and macro over families (mean of family shares), with counts."""
|
||||
out = []
|
||||
for keys, run in frame.groupby(["model", "mode", "modality", "seed"], sort=True):
|
||||
counts = run.groupby(["family", "error_class"]).size().unstack(fill_value=0).reindex(columns=CLASSES,
|
||||
fill_value=0)
|
||||
shares = counts.div(counts.sum(axis=1), axis=0)
|
||||
base = dict(zip(("model", "mode", "modality", "seed"), keys))
|
||||
for family, row in shares.iterrows():
|
||||
out.append(base | {"family": family, "n": int(counts.loc[family].sum()),
|
||||
**{c: float(row[c]) for c in CLASSES},
|
||||
**{f"n_{c}": int(counts.loc[family, c]) for c in CLASSES}})
|
||||
out.append(base | {"family": "macro", "n": int(counts.values.sum()),
|
||||
**{c: float(shares[c].mean()) for c in CLASSES},
|
||||
**{f"n_{c}": int(counts[c].sum()) for c in CLASSES}})
|
||||
return pd.DataFrame(out)
|
||||
|
||||
|
||||
def by_answer_type(frame):
|
||||
"""Class shares among incorrect answerable predictions, by answer type, per run."""
|
||||
wrong = frame[frame["answerable"] & ~frame["correct"]]
|
||||
counts = wrong.groupby(["model", "mode", "modality", "seed", "answer_type", "error_class"]).size()
|
||||
table = counts.unstack(fill_value=0)
|
||||
return table.div(table.sum(axis=1), axis=0).reset_index()
|
||||
|
||||
|
||||
def mean_over_seeds(table, keys, columns):
|
||||
grouped = table.groupby(keys, sort=True)[list(columns)]
|
||||
mean, low, high = grouped.mean(), grouped.min(), grouped.max()
|
||||
out = mean.reset_index()
|
||||
for c in columns:
|
||||
out[f"{c}_min"] = low[c].to_numpy()
|
||||
out[f"{c}_max"] = high[c].to_numpy()
|
||||
out["seeds"] = table.groupby(keys, sort=True)["seed"].nunique().to_numpy()
|
||||
return out
|
||||
|
||||
|
||||
def spearman(x, y):
|
||||
x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float)
|
||||
if len(x) < 3 or np.ptp(x) == 0 or np.ptp(y) == 0:
|
||||
return None
|
||||
return float(spearmanr(x, y).statistic)
|
||||
|
||||
|
||||
def spearman_ci(x, y, wells, resamples, seed):
|
||||
"""Whole-well cluster bootstrap of Spearman rho (percentile 95% interval)."""
|
||||
x, y, wells = np.asarray(x, dtype=float), np.asarray(y, dtype=float), pd.Series(wells).to_numpy()
|
||||
names = np.unique(wells)
|
||||
index = {w: np.flatnonzero(wells == w) for w in names}
|
||||
rng = np.random.default_rng(seed)
|
||||
values = []
|
||||
for _ in range(resamples):
|
||||
rows = np.concatenate([index[w] for w in rng.choice(names, size=len(names), replace=True)])
|
||||
r = spearman(x[rows], y[rows])
|
||||
if r is not None and np.isfinite(r):
|
||||
values.append(r)
|
||||
if not values:
|
||||
return None, 0
|
||||
return [float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))], len(values)
|
||||
|
||||
|
||||
def rq4_block(frame, score, resamples, seed):
|
||||
rho = spearman(frame[score], frame["correct"])
|
||||
ci, finite = spearman_ci(frame[score], frame["correct"], frame["well"], resamples, seed) if rho is not None \
|
||||
else (None, 0)
|
||||
levels = {f"{k:.3f}": {"n": int(len(g)), "accuracy": float(g["correct"].mean())}
|
||||
for k, g in frame.groupby(score)}
|
||||
return {"n": int(len(frame)), "rho": rho, "ci95": ci, "finite_resamples": finite,
|
||||
"accuracy": float(frame["correct"].mean()), "mean_egs": float(frame[score].mean()),
|
||||
"by_level": levels}
|
||||
|
||||
|
||||
def rq4(frame, resamples, seed):
|
||||
"""Spearman between EGS and correctness: pooled per (model, seed) and within each run; sensitivities."""
|
||||
base = frame[frame["answerable"] & ~frame["failed"]]
|
||||
variants = {"primary": (base, "egs"), "no_abstentions": (base[~base["abstained"]], "egs"),
|
||||
"extended_units": (base, "egs_ext")}
|
||||
out = []
|
||||
for variant, (data, score) in variants.items():
|
||||
for (model, s), run in data.groupby(["model", "seed"], sort=True):
|
||||
out.append({"variant": variant, "model": model, "seed": int(s), "mode": "pooled", "modality": "all",
|
||||
**rq4_block(run, score, resamples, seed)})
|
||||
for (mode, modality), cell in run.groupby(["mode", "modality"], sort=True):
|
||||
out.append({"variant": variant, "model": model, "seed": int(s), "mode": mode,
|
||||
"modality": modality, **rq4_block(cell, score, resamples, seed)})
|
||||
return out
|
||||
|
||||
|
||||
def h4_reading(rows, model, threshold=0.3):
|
||||
pooled = [r["rho"] for r in rows if r["variant"] == "primary" and r["model"] == model and r["mode"] == "pooled"]
|
||||
if not pooled or any(r is None for r in pooled):
|
||||
return {"model": model, "pooled_rho": pooled, "reading": None}
|
||||
if all(abs(r) < threshold for r in pooled):
|
||||
reading = "supported"
|
||||
elif all(abs(r) >= threshold for r in pooled):
|
||||
reading = "not supported"
|
||||
else:
|
||||
reading = "mixed"
|
||||
return {"model": model, "pooled_rho": pooled, "threshold": threshold, "reading": reading}
|
||||
209
volve_dia/m5_t5.py
Normal file
209
volve_dia/m5_t5.py
Normal file
@@ -0,0 +1,209 @@
|
||||
"""T5 similar-interval retrieval and the neighbour forecast of protocol v5.
|
||||
|
||||
Relevance labels come from the XML-derived T3 intervals, the T1 section and the formation picks, all by code.
|
||||
No representation reads activity codes, causes, labels, section or formation fields."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||||
from sklearn.metrics import average_precision_score
|
||||
|
||||
WITSML_COLUMNS = tuple(f"witsml_{stat}_{channel}" for stat in ("mean", "sd")
|
||||
for channel in ("hkld", "rop", "rpm", "sppa"))
|
||||
PRE_EVENT = ("depth", "witsml_pre", "text_pre")
|
||||
REPRESENTATIONS = ("random",) + PRE_EVENT + ("text_event", "rrf_pre", "rrf_all")
|
||||
METRICS = ("ndcg10", "mrr", "p10", "section10", "formation10", "cause10")
|
||||
ATTRIBUTES = ("section", "formation", "cause")
|
||||
RRF_K, CUTOFF, RANDOM_ORDERS = 60, 10, 100
|
||||
DELIMITER = " [SEP] "
|
||||
|
||||
|
||||
def normalise_unit(unit):
|
||||
"""'Hugin Fm. VOLVE' -> 'hugin', 'Heather Fm. Sand VOLVE' -> 'heather', 'NORDLAND GP.' -> 'nordland'."""
|
||||
text = re.sub(r"\b(volve|sand)\b", " ", str(unit).casefold())
|
||||
text = re.sub(r"\b(fm|gp)\.", " ", text)
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def formation_at(picks, wellbore, md):
|
||||
"""Normalised unit of the deepest pick with md <= `md` for the DDR wellbore, or None above the first pick."""
|
||||
own = picks[picks["wellbore"].eq(wellbore) & picks["md"].le(md)]
|
||||
if own.empty:
|
||||
return None
|
||||
return normalise_unit(own.sort_values(["md", "unit"]).iloc[-1]["unit"])
|
||||
|
||||
|
||||
def eligible_intervals(intervals, cells, sections, picks, wellbores, definition):
|
||||
"""Eligible T3 intervals of one definition with section, formation and cause set (protocol v5 items)."""
|
||||
frame = intervals[intervals["definition"].eq(definition) & intervals["wellbore"].isin(wellbores)].copy()
|
||||
own_top = cells.groupby("wellbore")["own_hole_top_md"].first()
|
||||
frame = frame[frame["md_top"].ge(frame["wellbore"].map(own_top))]
|
||||
frame["first_act"] = frame["act_ids"].map(lambda ids: sorted(ids)[0])
|
||||
frame["report_id"] = frame["first_act"].str.rsplit(":", n=1).str[0]
|
||||
frame["section"] = frame["report_id"].map(sections)
|
||||
frame["formation"] = [formation_at(picks, w, md) for w, md in zip(frame["wellbore"], frame["md_top"])]
|
||||
frame["cause_set"] = frame["causes"].fillna("").map(lambda c: frozenset(x for x in c.split("|") if x))
|
||||
frame = frame[frame["section"].notna() & frame["formation"].notna()]
|
||||
return frame.sort_values("interval_id").reset_index(drop=True)
|
||||
|
||||
|
||||
def gains(query, candidates):
|
||||
"""g = [same section] + [same formation] + [cause sets intersect], per candidate, with the three parts."""
|
||||
section = candidates["section"].to_numpy() == query["section"]
|
||||
formation = candidates["formation"].to_numpy() == query["formation"]
|
||||
cause = np.array([bool(query["cause_set"] & c) for c in candidates["cause_set"]], dtype=bool)
|
||||
return section.astype(int) + formation.astype(int) + cause.astype(int), {
|
||||
"section": section, "formation": formation, "cause": cause}
|
||||
|
||||
|
||||
def order(scores, tiebreak):
|
||||
"""Candidate indices by descending score; equal scores follow the fixed random tie order."""
|
||||
return np.lexsort((tiebreak, -np.asarray(scores, dtype=float)))
|
||||
|
||||
|
||||
def ranking_metrics(ranked, gain, parts, k=CUTOFF):
|
||||
"""nDCG@k (linear gain, ideal over all candidates), reciprocal rank of the first g = 3, P@k and attribute shares."""
|
||||
discount = 1 / np.log2(np.arange(2, k + 2))
|
||||
top = ranked[:k]
|
||||
ideal = np.sort(gain)[::-1][:k]
|
||||
idcg = float((ideal * discount[:len(ideal)]).sum())
|
||||
ndcg = float((gain[top] * discount[:len(top)]).sum()) / idcg if idcg > 0 else np.nan
|
||||
full = np.flatnonzero(gain[ranked] == 3)
|
||||
out = {"ndcg10": ndcg, "mrr": 1 / (full[0] + 1) if len(full) else np.nan,
|
||||
"p10": float((gain[top] == 3).sum()) / k}
|
||||
for name in ATTRIBUTES:
|
||||
out[f"{name}10"] = float(parts[name][top].sum()) / k
|
||||
return out
|
||||
|
||||
|
||||
def rrf(score_lists, tiebreak):
|
||||
"""Reciprocal rank fusion: sum of 1 / (RRF_K + rank) with ranks starting at 1."""
|
||||
fused = np.zeros(len(tiebreak))
|
||||
for scores in score_lists:
|
||||
ranks = np.empty(len(tiebreak))
|
||||
ranks[order(scores, tiebreak)] = np.arange(1, len(tiebreak) + 1)
|
||||
fused += 1 / (RRF_K + ranks)
|
||||
return fused
|
||||
|
||||
|
||||
def standardise(train, test):
|
||||
"""Median imputation and z-scores fitted on `train`; constant columns are set to 0."""
|
||||
train, test = train.astype(float), test.astype(float)
|
||||
median = train.median().fillna(0.0)
|
||||
train, test = train.fillna(median), test.fillna(median)
|
||||
mean, sd = train.mean(), train.std(ddof=0).replace(0, 1.0)
|
||||
return ((train - mean) / sd).to_numpy(), ((test - mean) / sd).to_numpy()
|
||||
|
||||
|
||||
def text_similarity(train_text, test_text):
|
||||
"""Cosine similarity of TF-IDF vectors fitted on the candidate pool; empty pools give zeros."""
|
||||
vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=1, sublinear_tf=True)
|
||||
try:
|
||||
pool = vectorizer.fit_transform(train_text)
|
||||
except ValueError:
|
||||
return np.zeros((len(test_text), len(train_text)))
|
||||
return (vectorizer.transform(test_text) @ pool.T).toarray()
|
||||
|
||||
|
||||
def fold_scores(queries, pool):
|
||||
"""Similarity of every query to every candidate (higher is closer) for the non-random representations."""
|
||||
depth = -np.abs(queries["md_top"].to_numpy()[:, None] - pool["md_top"].to_numpy()[None, :])
|
||||
z_pool, z_query = standardise(pool[list(WITSML_COLUMNS)], queries[list(WITSML_COLUMNS)])
|
||||
witsml = -np.sqrt(((z_query[:, None, :] - z_pool[None, :, :]) ** 2).sum(axis=2))
|
||||
return {"depth": depth, "witsml_pre": witsml,
|
||||
"text_pre": text_similarity(pool["text_pre"].tolist(), queries["text_pre"].tolist()),
|
||||
"text_event": text_similarity(pool["text_event"].tolist(), queries["text_event"].tolist())}
|
||||
|
||||
|
||||
def evaluate(items, group, seed, orders=RANDOM_ORDERS):
|
||||
"""Per-query metrics for every representation; candidates are the items of the other groups."""
|
||||
tie_rank = np.random.default_rng(seed).permutation(len(items))
|
||||
rng = np.random.default_rng(seed)
|
||||
rows = []
|
||||
for name in sorted(items[group].unique()):
|
||||
held = items[group].eq(name).to_numpy()
|
||||
queries, pool = items[held].reset_index(drop=True), items[~held].reset_index(drop=True)
|
||||
if pool.empty:
|
||||
continue
|
||||
tiebreak = tie_rank[~held]
|
||||
scores = fold_scores(queries, pool)
|
||||
for i, query in queries.iterrows():
|
||||
gain, parts = gains(query, pool)
|
||||
base = {"interval_id": query["interval_id"], "well": query["well"], "wellbore": query["wellbore"],
|
||||
"n_candidates": len(pool), "n_fully_relevant": int((gain == 3).sum())}
|
||||
per = {r: scores[r][i] for r in scores}
|
||||
per["rrf_pre"] = rrf([per[r] for r in PRE_EVENT], tiebreak)
|
||||
per["rrf_all"] = rrf([per[r] for r in PRE_EVENT + ("text_event",)], tiebreak)
|
||||
for rep, s in per.items():
|
||||
rows.append(base | {"representation": rep} | ranking_metrics(order(s, tiebreak), gain, parts))
|
||||
draws = pd.DataFrame([ranking_metrics(rng.permutation(len(pool)), gain, parts) for _ in range(orders)])
|
||||
rows.append(base | {"representation": "random"} | draws.mean(skipna=False).to_dict())
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def cluster_ci(values, clusters, resamples, seed):
|
||||
"""Mean over non-missing values with a whole-cluster percentile bootstrap 95% interval."""
|
||||
values, clusters = np.asarray(values, dtype=float), np.asarray(clusters)
|
||||
keep = ~np.isnan(values)
|
||||
values, clusters = values[keep], clusters[keep]
|
||||
if not len(values):
|
||||
return {"n": 0, "mean": None, "ci95": None}
|
||||
names = np.unique(clusters)
|
||||
sums = np.array([values[clusters == c].sum() for c in names])
|
||||
counts = np.array([(clusters == c).sum() for c in names])
|
||||
rng = np.random.default_rng(seed)
|
||||
draws = rng.integers(0, len(names), size=(resamples, len(names)))
|
||||
means = sums[draws].sum(axis=1) / counts[draws].sum(axis=1)
|
||||
return {"n": int(len(values)), "mean": float(values.mean()),
|
||||
"ci95": [float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))]}
|
||||
|
||||
|
||||
def summarise(per_query, resamples, seed, metrics=METRICS):
|
||||
"""Mean and well-bootstrap interval per representation, plus paired differences against random and depth."""
|
||||
out = {}
|
||||
wide = {m: per_query.pivot(index="interval_id", columns="representation", values=m) for m in metrics}
|
||||
wells = per_query.drop_duplicates("interval_id").set_index("interval_id")["well"]
|
||||
for rep in [r for r in REPRESENTATIONS if r in set(per_query["representation"])]:
|
||||
block = {}
|
||||
for m in metrics:
|
||||
table = wide[m]
|
||||
block[m] = cluster_ci(table[rep], wells.loc[table.index], resamples, seed)
|
||||
for ref in ("random", "depth"):
|
||||
if ref != rep and m in ("ndcg10", "mrr", "p10"):
|
||||
block[f"{m}_minus_{ref}"] = cluster_ci(table[rep] - table[ref], wells.loc[table.index],
|
||||
resamples, seed)
|
||||
out[rep] = block
|
||||
return out
|
||||
|
||||
|
||||
def knn_scores(features, label, columns, group="well", k=CUTOFF):
|
||||
"""Leave-one-group-out k-nearest-neighbour score: the mean label of the k closest cells of the other groups."""
|
||||
scores = pd.Series(np.nan, index=features.index)
|
||||
y = features[label].astype(float).to_numpy()
|
||||
for name in sorted(features[group].unique()):
|
||||
held = features[group].eq(name).to_numpy()
|
||||
train, test = standardise(features.loc[~held, list(columns)], features.loc[held, list(columns)])
|
||||
distance = np.sqrt(((test[:, None, :] - train[None, :, :]) ** 2).sum(axis=2))
|
||||
nearest = np.argsort(distance, axis=1, kind="stable")[:, :k]
|
||||
scores[held] = y[~held][nearest].mean(axis=1)
|
||||
return scores
|
||||
|
||||
|
||||
def ap_ci(y, scores, clusters, resamples, seed):
|
||||
"""Pooled average precision with a whole-cluster percentile bootstrap 95% interval."""
|
||||
y, scores, clusters = np.asarray(y, dtype=int), np.asarray(scores, dtype=float), np.asarray(clusters)
|
||||
names = np.unique(clusters)
|
||||
index = {c: np.flatnonzero(clusters == c) for c in names}
|
||||
rng = np.random.default_rng(seed)
|
||||
values = []
|
||||
for _ in range(resamples):
|
||||
rows = np.concatenate([index[c] for c in rng.choice(names, size=len(names), replace=True)])
|
||||
if 0 < y[rows].sum() < len(rows):
|
||||
values.append(average_precision_score(y[rows], scores[rows]))
|
||||
return {"n": int(len(y)), "positives": int(y.sum()), "prevalence": float(y.mean()),
|
||||
"ap": float(average_precision_score(y, scores)),
|
||||
"ci95": [float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))] if values else None}
|
||||
Reference in New Issue
Block a user