Add protocol v6: planted-signal studies for T2 and T3

Locked protocol v6 (SHA-256 0376aa18...), cue lexicon, the 21_m5_synthetic
script with its module and 22 tests. Labels are drawn at random so the truth
is known; a signal of controlled strength is written into the model input.
Null checks pass for T2 f = 0.02 and T3 s = 0 and fail for T2 f = 0.10 under
the locked rule. A post-hoc diagnosis (--arm diagnose) shows that the failure
comes from the null definition (c = 0 < f makes the absence of a cue a
signal), and the true null c = f passes. The real masked T2 AP corresponds to
a cue rate of about 0.82 and the real T3 forecast AP to a depth hazard of
about 0.66. Docs, report and logs updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 01:50:28 +00:00
parent 5f780bab67
commit 8c924b7f0d
12 changed files with 965 additions and 11 deletions

View File

@@ -4,7 +4,7 @@ Volve-DIA: a public benchmark and baselines for drilling-context recognition, NP
Read first: `docs/plan.md` (plan, gates, decisions; §1 data facts, §6 roadmap, §10 forbidden claims, §12 decision log), `README.md` (setup, scripts, logging), `docs/danh-gia-huong-NCKH-2026-10-29.md` (why this direction, competitors, references; local only, not in git), `docs/technical_overview.md` (a lecture for newcomers: drilling, DDR, leakage, tasks, labels, OCR, evaluation, code map). Progress page: `report.html`. These docs are in Vietnamese. Read first: `docs/plan.md` (plan, gates, decisions; §1 data facts, §6 roadmap, §10 forbidden claims, §12 decision log), `README.md` (setup, scripts, logging), `docs/danh-gia-huong-NCKH-2026-10-29.md` (why this direction, competitors, references; local only, not in git), `docs/technical_overview.md` (a lecture for newcomers: drilling, DDR, leakage, tasks, labels, OCR, evaluation, code map). Progress page: `report.html`. These docs are in Vietnamese.
## Status (20/11/2026) ## Status (23/11/2026)
- **P0 (infrastructure) done and committed** (first commit on `main`, 29/10/2026). The project folder is `/home/jovyan/lamlvh/Volve-DIA`; remote `origin` `https://gitea.vts-ai.space/lamlvh/Volve-DIA` is **public**. `scripts/run_p0.sh` runs scripts 00–05 and the tests. - **P0 (infrastructure) done and committed** (first commit on `main`, 29/10/2026). The project folder is `/home/jovyan/lamlvh/Volve-DIA`; remote `origin` `https://gitea.vts-ai.space/lamlvh/Volve-DIA` is **public**. `scripts/run_p0.sh` runs scripts 00–05 and the tests.
- **M1 machine work committed** (17/11/2026, `1791665`). The M1 driver generated the machine outputs; its final pytest - **M1 machine work committed** (17/11/2026, `1791665`). The M1 driver generated the machine outputs; its final pytest
@@ -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 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 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. 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`. 204 tests (20/11). Track runs with `bash scripts/m34_status.sh`. 226 tests (23/11).
- **G2 v2 passed on 20/11/2026** (`outputs/m34/report.json` refreshed 06:32 UTC): `g2_v2.passed` True with no missing - **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 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 pages; `sha256sum -c configs/protocol_v2.yaml.sha256` OK. Headline T4 macro-family accuracy (well-scoped, mean of 3
@@ -113,12 +113,28 @@ Read first: `docs/plan.md` (plan, gates, decisions; §1 data facts, §6 roadmap,
section and formation follow depth in one field; cause overlap barely moves (0.70 random, 0.75 best). Neighbour forecast 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. 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. T5 is outside G2 and stays a diagnostic.
- **Protocol v6: planted-signal studies done (20/11/2026, plan §1.9, §12 item 37).** `configs/protocol_v6.yaml`
(+ `.sha256`, extends v5; never edit it; cue phrases in `configs/synth_cues.yaml`) was locked before any planted score.
`scripts/21_m5_synthetic.py` (`volve_dia/m5_synthetic.py`, 22 tests) writes `outputs/m5/synthetic/`; five `m5_synthetic`
runs finished `ok` on 20/11 (run on an uncommitted tree, `dirty` True in `logs/index.csv`). Labels are drawn at random
(known exactly), then a signal of known strength is written into the model input; real labels are not used. 5 seeds,
well-cluster CIs, no gate, no replacement for H3. **Null checks:** pass for T2 f = 0.02 (AP 0.182, pi 0.183) and T3
s = 0 (0.118, pi 0.114); **fail for T2 f = 0.10** (AP 0.193, off by 0.0101 against the 0.01 tolerance, seed-0 CI does
not contain pi), so that sensitivity setting is not interpreted under v6 (the locked verdict stays). Post-hoc diagnosis (23/11,
`scripts/21_m5_synthetic.py --arm diagnose`, `null_diagnosis_t2.csv`): the cause is the null definition, not the
pipeline. At c = 0 < f the absence of an own cue already marks planted rows; the no-cue indicator alone gives AP 0.2004
(theory 0.199) at f = 0.10 and 0.185 at f = 0.02. The true null is c = f: AP 0.1819 at f = c = 0.10 (passes). Using the
f = 0.10 curve would need a new locked protocol with the null at c = f. T2 (f = 0.02): AP 0.182 at
c = 0 rising monotonically to 0.521 at c = 1; the real masked TF-IDF AP 0.463 corresponds to c about 0.82 (0.78-0.84):
about 82% of NPT rows would need an explicit cue in the masked text. Cue spill into neighbouring activities makes this
slightly high. T3: real depth forecast AP 0.150 corresponds to s about 0.66 (0.55-0.72), oracle about 0.21, a very
weak depth hazard. This bounds detectability; it does not validate the labels.
## Next ## Next
Roadmap and gates: `docs/plan.md` §6, §12 item 1. Roadmap and gates: `docs/plan.md` §6, §12 item 1.
1. G2 v2, G3, the error taxonomy, RQ4 and T5 are done (20/11). Next: paper writing (M6) and release 1. G2 v2, G3, the error taxonomy, RQ4, T5 and the planted-signal studies 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. 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. 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). 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).

View File

@@ -192,6 +192,28 @@ trên 4.894 ô T3. Kết quả ghi ở `outputs/m5/t5/`: `report.json`, `per_que
`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 `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)). ([plan §1.8](docs/plan.md#18-m5-t5-truy-xuất-khoảng-tương-đồng-ngày-20112026)).
### Tín hiệu cấy (protocol v6)
`configs/protocol_v6.yaml` (khóa bằng `.sha256`, mở rộng v5; cụm từ cue trong `configs/synth_cues.yaml`) cố định nhãn cấy,
cường độ, mô hình và kiểm tra null trước mọi điểm số cấy. Nhãn được bốc ngẫu nhiên nên biết chính xác; nhãn và văn bản thật
không dùng làm chân lý.
```bash
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 \
scripts/runlog.sh -n m5_synthetic -- .venv/bin/python scripts/21_m5_synthetic.py --arm t3 # khoảng 4 phút
for i in 0 1 2 3; do # 4 tiến trình độc lập, mỗi tiến trình khoảng 2 giờ 30 phút; chạy nền bằng setsid nohup
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 \
scripts/runlog.sh -n m5_synthetic -- .venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard $i/4
done
.venv/bin/python scripts/21_m5_synthetic.py --arm report # dựng lại report.json và bảng từ các lượt đã xong
.venv/bin/python scripts/21_m5_synthetic.py --arm diagnose # sau sự kiện: vì sao null c = 0 trượt khi f > 0 (khoảng 3 giây)
```
Kết quả ở `outputs/m5/synthetic/` (`report.json`, `settings_t2.csv`, `settings_t3.csv`, `seeds_t2.csv`, `seeds_t3.csv`,
`t3_scores.parquet`, `t2_runs/`). Kết quả ngày 20/11: kiểm tra null đạt ở T2 f = 0,02 và T3, không đạt ở T2 f = 0,10; điểm
TF-IDF T2 thật tương ứng c ≈ 0,82, điểm T3 thật tương ứng s ≈ 0,66. Lỗi null ở f = 0,10 là do thiết kế (null thật là c = f, đạt), xem `null_diagnosis_t2.csv`
([plan §1.9](docs/plan.md#19-m5-nghiên-cứu-tín-hiệu-cấy-planted-signal-ngày-20112026)).
## Ba phiên bản của một DDR và parser OCR ## Ba phiên bản của một DDR và parser OCR
Mỗi DDR có ba phiên bản: Mỗi DDR có ba phiên bản:
@@ -241,6 +263,7 @@ Dịch vụ OCR:
| `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/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/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/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/21_m5_synthetic.py` | Tín hiệu cấy cho T2 (cue văn bản) và T3 (hazard theo độ sâu) theo protocol v6 → `outputs/m5/synthetic/` |
| `scripts/runlog.sh` | Bọc một lệnh để ghi log và runtime | | `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_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 | | `scripts/run_p0.sh` | Chạy toàn bộ P0: 00 `--check`, 01–05 (04 ở chế độ `--pilot`), pytest |

75
configs/protocol_v6.yaml Normal file
View File

@@ -0,0 +1,75 @@
# Protocol v6: planted-signal studies with known ground truth (T2 text cues, T3 depth hazard). Extends locked v5.
protocol: volve-dia
version: 6
status: locked
drafted: 2026-11-20
locked_before: any planted-signal score was computed; only the real masked T2 and T3 results (v1-v5) were known
extends:
file: configs/protocol_v5.yaml
sha256: c99bb91bdca9a4ab00ef065847ec095121944ddccbffde32c34dc6f8fc125047
deviation:
date: 2026-11-20
what: >-
H3 (label agreement with raters) was not met and the real T2/T3 labels are derived from the DDR activity codes, so
no result so far says whether the pipeline can recover a signal whose truth is known. v6 adds planted-signal
studies: the label is drawn by a fixed random rule and is therefore known exactly; a signal of controlled strength is
then written into the model input. The real labels and the real input text are not used as truth.
consequence: >-
The studies measure the null calibration and the power of the T2 and T3 pipelines and give an effective
signal strength for the real scores. They do not validate the real labels and do not replace H3. The planted
cues are synthetic phrases and the T3 hazard is a smooth function of depth, so they bound detectability, not realism.
unchanged:
- protocols v1 to v5 in full, including masking, splits, folds, regularisation grid and the real T2/T3 results
common:
seeds: 5 planting seeds, 20261117 + 0 ... 4 (numpy default_rng); one planting per seed and setting
split: leave-one-well-out as in v1 (primary grouping by well)
ci: whole-well cluster bootstrap, 2,000 resamples, seed 20261117, percentile 95% interval
reporting: mean and range over the 5 seeds, plus the pooled out-of-fold AP interval of seed 0
t2_cues:
universe: the 23,447 masked activities of outputs/labels/t2_inputs.parquet (all 11 wells)
planted_label: >-
y_i ~ Bernoulli(pi) independently per activity, pi = 0.183 (the real NPT (b) prevalence, 4,286 / 23,447); the real
code labels are never read
cue: >-
a planted activity receives, with probability c, one phrase chosen uniformly from configs/synth_cues.yaml appended
after its comment (one space); an unplanted activity receives a phrase with probability f (decoy rate). The phrase
class is independent of the real activity
settings:
c: [0.0, 0.1, 0.25, 0.5, 0.75, 1.0]
f_primary: 0.02
f_sensitivity: 0.10
model: >-
the T2 TF-IDF + logistic baseline of M3-M4 unchanged (configs/m34_baselines.yaml: word 1-2 grams, min_df 2, C chosen
by the same inner GroupKFold from [0.25, 1, 4]), leave-one-well-out, masked view plus the appended cue
metrics: pooled out-of-fold average precision (AP) with the interval above; AP lift over pi
null_check: >-
at c = 0 (any f) the mean AP over seeds lies within pi +/- 0.01 and the seed-0 95% interval contains pi; otherwise the
pipeline is reported as miscalibrated under the null and the cue results are not interpreted
effective_cue_rate: >-
the c at which the mean AP over seeds (f = 0.02) equals the real masked T2(b) TF-IDF AP by well (0.461 in the G2 v2
report), by linear interpolation between the grid points, reported with the range over seeds; if the real AP is
above the AP at c = 1 or below the AP at c = 0, the interpolation is reported as out of range
reading: >-
descriptive; no gate. The effective cue rate says what fraction of planted-NPT-like rows would have to carry an
explicit cue in the masked text to produce the real score. It is not a measure of label validity
t3_hazard:
universe: the 4,894 cells of outputs/m34/features_t3.parquet (10 wells)
covariate: z = (md_top - mean) / sd of md_top over the 4,894 cells
planted_label: >-
y_i ~ Bernoulli(p_i), p_i = sigmoid(a + s * z_i) with a solved by bisection so that mean(p) = pi = 0.114 (the real
NPT (b) cell prevalence 556 / 4,894); the real labels are never read
settings:
s: [0.0, 0.25, 0.5, 1.0, 2.0]
model: >-
the v5 neighbour forecast, depth representation (md_top; k = 10 nearest cells of the other wells, mean label), and
the oracle score p_i as the ceiling
metrics: pooled out-of-fold AP with the interval above; the oracle AP; AP lift over pi
null_check: at s = 0 the mean AP over seeds lies within pi +/- 0.01 and the seed-0 95% interval contains pi
effective_strength: >-
the s at which the mean AP of the depth forecast equals the real v5 depth forecast AP (0.150, NPT (b)), by linear
interpolation, with the range over seeds; out of range reported as such. Labels are independent across cells, so
the intervals of the real data (neighbouring cells of one episode) are not reproduced
code: scripts/21_m5_synthetic.py, volve_dia/m5_synthetic.py
outputs: outputs/m5/synthetic/
inputs_hashed:
configs/synth_cues.yaml: dfe395298a1f30b1fe6906a65bd03a06f83796206a19993beb530fa106b82107

View File

@@ -0,0 +1 @@
0376aa18ea7ace44fdb3fd1ccb4424aa3b8c5e89d44e04f160af38e036fd5f7c configs/protocol_v6.yaml

30
configs/synth_cues.yaml Normal file
View File

@@ -0,0 +1,30 @@
# Cue lexicon for the planted-signal T2 arm (protocol v6). Written before any planted-signal score; hashed in v6.
# Each phrase is appended to a masked activity comment. Phrases are generic drilling wording by cause class.
cues:
equipment:
- "Top drive failure, repair in progress."
- "Mud pump down, changed liner and swab."
- "Rig equipment breakdown, awaiting spare part."
- "Drawworks fault, troubleshooting."
- "Hydraulic leak on pipe handler, repaired."
- "BOP control system malfunction, tested again."
weather:
- "Waiting on weather, wind above operating limit."
- "Operations suspended due to high seas."
- "Standby for weather window, crane operations not possible."
- "Swell exceeded limit, held position."
stuck_fishing:
- "String stuck, worked pipe free."
- "Pack-off while pulling out, jarred to release."
- "Fishing operation to recover lost BHA component."
- "Lost tool in hole, ran fishing assembly."
well_control:
- "Well kick observed, shut in and circulated out."
- "Gas influx, killed well with weighted mud."
lost_circulation:
- "Partial losses to formation, pumped LCM pill."
- "Total losses while drilling, spotted cement plug."
waiting:
- "Waiting on orders from town."
- "Waiting on cement, standby."
- "Waiting on boat, delayed delivery."

View File

@@ -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. | | **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]. | | **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). | | **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. 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. | | **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. Ngày 20/11 protocol v6 (§12 ý 37, §1.9) cấy tín hiệu biết trước vào T2 và T3 để đo pipeline: kiểm tra null đạt ở cấu hình chính (T2 f = 0,02, T3) nhưng **không đạt ở T2 f = 0,10** (lệch 0,0101), nên cấu hình đó không được diễn giải (điều tra 23/11: lỗi do thiết kế null c = 0 < f, null thật c = f đạt; §1.9); điểm TF-IDF T2 thật tương ứng khoảng 82% hàng NPT mang cue rõ ràng, điểm T3 thật tương ứng hazard độ sâu rất yếu (s ≈ 0,66). 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, §1.9 và §6. |
--- ---
@@ -372,6 +372,53 @@ trên những ngày thiếu `diaHole` vẫn chưa xác định.
là phân tích chẩn đoá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). - Mã `volve_dia/m5_t5.py`, 12 test; lượt `20261120-073123_m5_t5` (1 phút 36 giây).
### 1.9 M5: nghiên cứu tín hiệu cấy (planted signal) ngày 20/11/2026
- **Thiết kế** [KT, protocol v6 khóa SHA-256 `0376aa18…` trước mọi điểm số cấy, `configs/synth_cues.yaml` `dfe39529…`,
`scripts/21_m5_synthetic.py`, `outputs/m5/synthetic/`, §12 ý 37]. Lý do: H3 không đạt và nhãn T2/T3 thật dẫn xuất từ mã
hoạt động DDR, nên chưa có kết quả nào cho biết pipeline có tìm lại được một tín hiệu mà ta biết chắc là có hay không. Ở đây
nhãn được bốc ngẫu nhiên theo luật cố định (biết chính xác), rồi một tín hiệu cường độ biết trước được ghi vào đầu vào mô
hình; nhãn thật và văn bản thật không dùng làm chân lý. T2: 23.447 hoạt động đã che mã, nhãn Bernoulli(0,183); hoạt động
được cấy nhận một cụm từ nhân tạo với xác suất c ∈ {0; 0,1; 0,25; 0,5; 0,75; 1}, hoạt động không cấy nhận cụm từ "mồi" với
xác suất f (0,02 chính; 0,10 độ nhạy); mô hình là TF-IDF + logistic của M3–M4, giữ nguyên, leave-one-well-out. T3: 4.894 ô,
hazard p = sigmoid(a + s·z) theo độ sâu chuẩn hóa, s ∈ {0; 0,25; 0,5; 1; 2}, prevalence 0,114; mô hình là dự báo láng giềng
theo độ sâu của v5, kèm điểm oracle p làm trần. 5 seed, CI bootstrap theo giếng. Không có cổng.
- **Kiểm tra null (c = 0 hoặc s = 0; điều kiện: AP trung bình trong π ± 0,01 và CI seed 0 chứa π):**
| Cấu hình | AP trung bình | π | Kết quả |
| --- | --- | --- | --- |
| T2, f = 0,02 (chính) | 0,1821 | 0,183 | đạt; CI seed 0 0,179–0,195 chứa π |
| T2, f = 0,10 (độ nhạy) | 0,1931 | 0,183 | **không đạt**: lệch 0,0101 (> 0,01 một chút); CI seed 0 0,193–0,208 không chứa π |
| T3, s = 0 | 0,1177 | 0,1136 | đạt; CI seed 0 0,107–0,124 chứa π |
Theo protocol, cấu hình không đạt được báo là lệch chuẩn dưới null và kết quả cue của f = 0,10 **không được diễn giải**;
phán quyết khóa này giữ nguyên. Mọi diễn giải T2 dưới đây dùng f = 0,02.
- **Điều tra nguyên nhân (23/11/2026, sau khi biết kết quả, không thuộc protocol v6; `scripts/21_m5_synthetic.py --arm diagnose`,
`outputs/m5/synthetic/null_diagnosis_t2.csv`).** Lỗi nằm ở định nghĩa "null" của v6, không ở pipeline. Hàng được cấy nhận cue
với xác suất c, hàng không cấy với xác suất f; khi c = 0 < f thì **không có cue ở chính comment đã là bằng chứng** cho hàng
cấy (mọi hàng cấy đều không có cue, 10% hàng không cấy có), nên c = 0 chỉ là null khi f = 0, hoặc khi c = f. Chỉ báo "không
có cue" tự nó (không qua mô hình) cho AP 0,2004 ở f = 0,10, c = 0 (lý thuyết π/(π + (1 − π)(1 − f)) = 0,199) và 0,1848
ở f = 0,02 (lý thuyết 0,186), cao hơn cả mô hình (0,193 và 0,182): mô hình không khai thác hết tín hiệu cấu trúc này. Khi
c = f, tức null thật, AP là 0,1819 ở f = c = 0,10 (CI seed 0 0,176–0,188 chứa π; chỉ báo không-cue 0,1830), nằm trong ngưỡng.
Kết luận: pipeline hiệu chuẩn đúng dưới null thật; sai lệch +0,010 ở f = 0,10 là tín hiệu cấu trúc của thiết kế, và ở
f = 0,02 nó chỉ +0,003 nên kiểm tra chính vẫn có ý nghĩa. Đường cong f = 0,10 vẫn không được diễn giải theo v6; nếu cần dùng,
phải khóa một protocol mới với null đặt tại c = f. Đây là kết quả điều tra sau sự kiện, báo riêng với kết quả theo protocol.
- **T2 (f = 0,02), AP trung bình trên 5 seed:** c = 0: 0,182; 0,1: 0,201; 0,25: 0,258; 0,5: 0,363; 0,75: 0,440; 1,0: 0,521
(lift 0,99 đến 2,85). Tức pipeline tìm lại tín hiệu cấy đơn điệu theo c. **Tỉ lệ cue hiệu dụng:** AP thật của TF-IDF T2(b) che
mã theo giếng (0,463) tương ứng c = 0,82 (0,78–0,84 giữa các seed; nằm trong lưới, không ngoài khoảng). Đọc: để tạo ra điểm
thật chỉ từ một cụm từ cấy, khoảng 82% hàng NPT phải mang một cue rõ ràng trong văn bản đã che mã. Đó là mức tín hiệu văn bản
rất cao, phù hợp với việc nhãn NPT được dựng từ mã hoạt động mà comment của chính hoạt động đó mô tả. **Không** phải đo độ
hợp lệ của nhãn. Hai hạn chế: cue nhân tạo là một cụm từ đơn, tín hiệu thật phân tán; và cue lan sang hoạt động kề
(mức phơi nhiễm ở hoạt động không cấy 0,35 khi c = 1), làm AP ở mỗi c thấp hơn thiết kế sạch nên c hiệu dụng bị ước hơi cao.
- **T3 (s), dự báo theo độ sâu, AP trung bình / oracle:** s = 0: 0,118 / 0,115; 0,25: 0,119 / 0,139; 0,5: 0,131 / 0,176;
1: 0,191 / 0,283; 2: 0,379 / 0,489. **Cường độ hiệu dụng:** AP thật 0,150 của dự báo theo độ sâu tương ứng s ≈ 0,66
(0,55–0,72 giữa các seed; 2 trong 5 seed có đoạn nội suy không đơn điệu). Ở s ≈ 0,66 oracle chỉ khoảng 0,21, nên điểm thật
0,150 phù hợp với một hazard theo độ sâu rất yếu; T3 vẫn là chẩn đoán. Nhãn cấy độc lập giữa các ô nên CI hẹp hơn dữ liệu thật
(các ô kề nhau cùng một sự kiện).
- Mã `volve_dia/m5_synthetic.py`, 22 test; 6 lượt `m5_synthetic` ngày 20/11 (arm T3 3 phút 30 giây, 4 shard T2 mỗi shard
khoảng 2 giờ 30 phút), tất cả `ok`. Các lượt chạy với cây mã chưa commit (`dirty` = True trong `logs/index.csv`, `code_sha`
`2845ef75…`); khi commit, ghi rõ mã đã commit là mã đã chạy.
## 2. Research gap ## 2. Research gap
### 2.1 Phát biểu ### 2.1 Phát biểu
@@ -525,7 +572,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 | — | | **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 | | **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 | | **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). 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) | | **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). Tín hiệu cấy cho T2/T3 xong 20/11 (protocol v6, §1.9, §12 ý 37) |
| **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 | | **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 |
--- ---
@@ -545,10 +592,11 @@ 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) | | `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 | | `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 | | `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/` | 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` | | `tests/` | 226 test đạt ngày 23/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, 12 test T5 và 22 test tín hiệu cấy). 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/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/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) | | `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) |
| `scripts/21_m5_synthetic.py`, `volve_dia/m5_synthetic.py`, `configs/protocol_v6.yaml` và `.sha256`, `configs/synth_cues.yaml` | Nghiên cứu tín hiệu cấy cho T2 (cue văn bản) và T3 (hazard theo độ sâu) → `outputs/m5/synthetic/` (§1.9, §12 ý 37) |
| `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 | | `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 | | `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 | | `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 |
@@ -610,7 +658,7 @@ 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 ## 12. Việc làm ngay và nhật ký quyết định
1. **Việc tiếp theo (từ 20/11/2026).** 1. **Việc tiếp theo (từ 20/11/2026).**
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ự 1. G2 v2 (ý 33), G3 (ý 34), phân loại lỗi và RQ4 (ý 35), T5 (ý 36), tín hiệu cấy (ý 37) đã 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. độ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. 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 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
@@ -818,3 +866,15 @@ Danh sách chính ở bản đánh giá mục 9. Ghi chú đọc và BibTeX: `do
wellbore). Comment của chính khoảng là góc nhìn mô tả, báo riêng. 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 - 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. 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.
37. **20/11/2026. Protocol v6: nghiên cứu tín hiệu cấy cho T2 và T3.**
- Lệch so với kế hoạch: H3 không đạt và nhãn T2/T3 thật dẫn xuất từ mã DDR, nên chưa đo được khả năng pipeline tìm lại một
tín hiệu biết chắc. `configs/protocol_v6.yaml` (khóa SHA-256 `0376aa18…`, mở rộng v5, không sửa v1–v5; cụm từ cue trong
`configs/synth_cues.yaml` `dfe39529…`) cố định nhãn cấy, cường độ, mô hình, metric, kiểm tra null và cách tính cường độ
hiệu dụng trước mọi điểm số cấy; trước khi khóa chỉ biết kết quả thật của v1–v5. Không có cổng, không thay H3.
- Kết quả ở §1.9: null đạt ở T2 f = 0,02 (AP 0,182) và T3 s = 0 (0,118); **không đạt ở T2 f = 0,10** (AP 0,193, lệch 0,0101
so với π = 0,183, CI seed 0 không chứa π), nên kết quả f = 0,10 không được diễn giải. Điều tra sau (23/11, không thuộc
v6): nguyên nhân là thiết kế, vì ở c = 0 < f việc không có cue đã là tín hiệu (chỉ báo không-cue một mình cho AP 0,2004);
null thật là c = f và cho AP 0,1819 (đạt). Pipeline không lệch chuẩn; phán quyết khóa của v6 giữ nguyên. Cue hiệu dụng của điểm T2 thật
c ≈ 0,82 (0,78–0,84); cường độ hiệu dụng của điểm T3 thật s ≈ 0,66 (0,55–0,72), oracle ≈ 0,21. Đây là giới hạn phát hiện
được, không phải kiểm định nhãn.

View File

@@ -1111,6 +1111,20 @@ Biểu diễn không được đọc mã, nguyên nhân, đoạn khoan hay forma
- 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 - 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. là phân tích chẩn đoán.
**Tín hiệu cấy (protocol v6, §1.9 của plan).** Vì H3 không đạt và nhãn T2/T3 thật dẫn xuất từ mã DDR, ta không biết pipeline có
tìm lại được một tín hiệu mà ta *biết chắc* là có hay không. Cách kiểm: tự bốc nhãn ngẫu nhiên (nên biết chính xác), rồi
ghi vào đầu vào một tín hiệu cường độ biết trước và xem điểm tăng bao nhiêu. Với T2, nhãn NPT cấy có xác suất 0,183 và mỗi hàng
được cấy nhận một cụm từ nhân tạo với xác suất c; với T3, xác suất NPT của ô phụ thuộc độ sâu với độ dốc s.
- **Kiểm tra null** (không cấy gì thì điểm phải bằng tần suất nền ± 0,01): T2 với 2% cụm từ mồi đạt (AP 0,182 so với 0,183); T3
đạt (0,118 so với 0,114); **T2 với 10% cụm từ mồi không đạt** (0,193; lệch 0,0101), nên kết quả của cấu hình đó không được diễn
giải theo v6. Điều tra sau cho thấy lỗi ở định nghĩa null, không ở pipeline: khi hàng cấy không nhận cue (c = 0) còn hàng
không cấy nhận cue với xác suất 10%, thì "không có cue" đã là dấu hiệu của hàng cấy (chỉ báo này một mình cho AP 0,200).
Null thật là c = f, và ở đó AP là 0,182, đạt.
- T2: AP tăng đơn điệu từ 0,182 (c = 0) lên 0,521 (c = 1). Điểm thật 0,463 tương ứng c ≈ 0,82: nếu chỉ dựa vào một cụm từ cấy,
phải có khoảng 82% hàng NPT mang cue rõ ràng. Điều này phù hợp với việc nhãn NPT được dựng từ mã mà comment của chính hoạt
động mô tả. Nó cho biết mức tín hiệu văn bản, không chứng minh nhãn đúng.
- T3: điểm thật 0,150 tương ứng hazard theo độ sâu s ≈ 0,66, rất yếu (trần oracle khoảng 0,21).
--- ---
## Bài 11. Được nói gì, không được nói gì ## Bài 11. Được nói gì, không được nói gì
@@ -1182,6 +1196,7 @@ Danh sách đầy đủ ở [plan.md](plan.md) §10.
| Hiệu chuẩn judge G3 | [m5_judge.py](../volve_dia/m5_judge.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) | | 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) | | T5 truy xuất khoảng tương đồng | [m5_t5.py](../volve_dia/m5_t5.py) |
| Tín hiệu cấy cho T2 và T3 | [m5_synthetic.py](../volve_dia/m5_synthetic.py) |
### 12.3 Chạy theo pha ### 12.3 Chạy theo pha
@@ -1196,6 +1211,7 @@ Cài đặt và bảng mô tả từng script ở [README.md](../README.md).
| 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/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/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) | | 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) |
| M5 | `scripts/21_m5_synthetic.py --arm t3` (khoảng 4 phút) và `--arm t2` (4 shard song song, khoảng 2 giờ 30 phút mỗi shard) | Tín hiệu cấy cho T3 và T2 (protocol v6) |
`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ẻ. `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ẻ.
@@ -1206,10 +1222,11 @@ Cài đặt và bảng mô tả từng script ở [README.md](../README.md).
### 12.4 Test quan trọng ### 12.4 Test quan trọng
- Test nằm trong [tests/](../tests/): 204 test đạt ngày 20/11. Test cần dữ liệu mang marker `data`. - Test nằm trong [tests/](../tests/): 226 test đạt ngày 23/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_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_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_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_m5_synthetic.py](../tests/test_m5_synthetic.py): nhãn cấy theo seed, cue và mức phơi nhiễm, hazard và bisection, kiểm tra null, nội suy cường độ hiệu dụng.
- [test_ddr_xml.py](../tests/test_ddr_xml.py): số lượng khóa (`EXPECTED`) và sentinel. - [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_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. - [test_witsml.py](../tests/test_witsml.py): số lượng WITSML và ghép tên wellbore.

View File

@@ -163,3 +163,9 @@ run_id,parent,name,status,exit_code,start,end,wall_s,wall,device,git,dirty,code_
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-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-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 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
20261120-084041_m5_synthetic,,m5_synthetic,ok,0,2026-11-20T08:40:41+00:00,2026-11-20T08:44:11+00:00,209.6,0:03:30,,5f780bab67ac,False,c27944f1218db019,runlog,.venv/bin/python scripts/21_m5_synthetic.py --arm t3
20261120-084446_m5_synthetic-2,,m5_synthetic,ok,0,2026-11-20T08:44:46+00:00,2026-11-20T11:13:52+00:00,8946.0,2:29:06,,5f780bab67ac,True,2845ef75e9c05096,runlog,.venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 0/4
20261120-084446_m5_synthetic,,m5_synthetic,ok,0,2026-11-20T08:44:46+00:00,2026-11-20T11:14:40+00:00,8993.9,2:29:54,,5f780bab67ac,True,2845ef75e9c05096,runlog,.venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 1/4
20261120-084446_m5_synthetic-4,,m5_synthetic,ok,0,2026-11-20T08:44:46+00:00,2026-11-20T11:14:50+00:00,9004.1,2:30:04,,5f780bab67ac,True,2845ef75e9c05096,runlog,.venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 2/4
20261120-084446_m5_synthetic-3,,m5_synthetic,ok,0,2026-11-20T08:44:46+00:00,2026-11-20T11:14:54+00:00,9008.1,2:30:08,,5f780bab67ac,True,2845ef75e9c05096,runlog,.venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 3/4
20261123-014852_m5_synthetic_diagnose,,m5_synthetic_diagnose,ok,0,2026-11-23T01:48:52+00:00,2026-11-23T01:48:54+00:00,2.8,0:00:03,,5f780bab67ac,True,96de7594148b7fdb,runlog,.venv/bin/python scripts/21_m5_synthetic.py --arm diagnose
1 run_id parent name status exit_code start end wall_s wall device git dirty code_sha source cmd
163 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
164 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
165 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
166 20261120-084041_m5_synthetic m5_synthetic ok 0 2026-11-20T08:40:41+00:00 2026-11-20T08:44:11+00:00 209.6 0:03:30 5f780bab67ac False c27944f1218db019 runlog .venv/bin/python scripts/21_m5_synthetic.py --arm t3
167 20261120-084446_m5_synthetic-2 m5_synthetic ok 0 2026-11-20T08:44:46+00:00 2026-11-20T11:13:52+00:00 8946.0 2:29:06 5f780bab67ac True 2845ef75e9c05096 runlog .venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 0/4
168 20261120-084446_m5_synthetic m5_synthetic ok 0 2026-11-20T08:44:46+00:00 2026-11-20T11:14:40+00:00 8993.9 2:29:54 5f780bab67ac True 2845ef75e9c05096 runlog .venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 1/4
169 20261120-084446_m5_synthetic-4 m5_synthetic ok 0 2026-11-20T08:44:46+00:00 2026-11-20T11:14:50+00:00 9004.1 2:30:04 5f780bab67ac True 2845ef75e9c05096 runlog .venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 2/4
170 20261120-084446_m5_synthetic-3 m5_synthetic ok 0 2026-11-20T08:44:46+00:00 2026-11-20T11:14:54+00:00 9008.1 2:30:08 5f780bab67ac True 2845ef75e9c05096 runlog .venv/bin/python scripts/21_m5_synthetic.py --arm t2 --shard 3/4
171 20261123-014852_m5_synthetic_diagnose m5_synthetic_diagnose ok 0 2026-11-23T01:48:52+00:00 2026-11-23T01:48:54+00:00 2.8 0:00:03 5f780bab67ac True 96de7594148b7fdb runlog .venv/bin/python scripts/21_m5_synthetic.py --arm diagnose

View File

@@ -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> <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> <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 đến D-20 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-21 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> <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> <h2>Phát hiện đã kiểm chứng (từ dữ liệu, plan §1)</h2>
@@ -196,9 +196,10 @@ 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:"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", {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 loại lỗi và tương quan EGS (<code>outputs/m5/errors/report.json</code>), T5 (<code>outputs/m5/t5/report.json</code>)", 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>), tín hiệu cấy (<code>outputs/m5/synthetic/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."}, 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:[ tasks:[
{id:"m5-synth", t:"Nghiên cứu tín hiệu cấy cho T2 và T3 (planted signal)", s:"done", n:"Protocol v6 (SHA-256 <code>0376aa18…</code>, khóa trước mọi điểm số cấy), <code>scripts/21_m5_synthetic.py</code>, 22 test, 5 lượt <code>m5_synthetic</code> và 1 lượt chẩn đoán đều ok. Nhãn bốc ngẫu nhiên nên biết chính xác; 5 seed, CI theo giếng. <b>Null:</b> đạt ở T2 f = 0,02 (AP 0,182, π 0,183) và T3 s = 0 (0,118, π 0,114); <b>không đạt ở T2 f = 0,10</b> (0,193; lệch 0,0101; CI seed 0 không chứa π), nên cấu hình đó không được diễn giải theo v6. Điều tra 23/11 (<code>--arm diagnose</code>, không thuộc protocol): nguyên nhân là định nghĩa null; ở c = 0 &lt; f việc không có cue đã là tín hiệu (chỉ báo không-cue một mình cho AP 0,2004, lý thuyết 0,199), null thật là c = f và cho AP 0,1819 (đạt). Pipeline không lệch chuẩn. T2 f = 0,02: AP 0,182 (c = 0) đến 0,521 (c = 1); điểm thật 0,463 ứng c ≈ 0,82 (0,78–0,84). T3: điểm thật 0,150 ứng s ≈ 0,66 (0,55–0,72), oracle ≈ 0,21. Đo giới hạn phát hiện, không kiểm định nhãn và không thay H3 (plan §1.9, §12 ý 37)."},
{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-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-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:"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)."}
@@ -253,6 +254,7 @@ const DECISIONS = [
{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-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-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)."}, {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)."},
{id:"D-21", q:"Nghiên cứu tín hiệu cấy cho T2 và T3", p:"Protocol v6 (mở rộng v5) khóa trước mọi điểm số cấy: nhãn Bernoulli độc lập với nhãn thật, cue nhân tạo cường độ c (T2) và hazard theo độ sâu s (T3), mô hình giữ nguyên như M3–M4 và v5, kiểm tra null AP ∈ π ± 0,01 và CI seed 0 chứa π, cường độ hiệu dụng nội suy từ điểm thật.", n:"Không có cổng, không thay H3. Null không đạt ở T2 f = 0,10 nên cấu hình đó không diễn giải theo v6; nguyên nhân là null c = 0 &lt; f, null thật c = f đạt (điều tra 23/11, plan §1.9, §12 ý 37)."},
]; ];
const FINDS = [ const FINDS = [
@@ -273,6 +275,7 @@ const FINDS = [
{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:"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)."}, {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)."},
{h:"Tín hiệu cấy: T2 thật cần cue ở khoảng 82% hàng NPT; T3 thật gần như không có tín hiệu (20/11)", p:"Protocol v6, 5 seed, CI theo giếng. Kiểm tra null đạt ở T2 f = 0,02 và T3, <b>không đạt ở T2 f = 0,10</b> (AP 0,193 so với π 0,183), nên cấu hình sau không diễn giải theo v6; điều tra sau cho thấy lỗi do thiết kế (c = 0 &lt; f làm việc không có cue thành tín hiệu), null thật c = f đạt (AP 0,1819). Pipeline T2 tìm lại tín hiệu cấy đơn điệu (AP 0,182 đến 0,521 khi c từ 0 đến 1); điểm thật 0,463 ứng c ≈ 0,82: văn bản đã che mã vẫn mang tín hiệu NPT rất mạnh, phù hợp với nhãn dựng từ mã mà comment mô tả. Điểm T3 thật 0,150 ứng hazard độ sâu s ≈ 0,66, oracle ≈ 0,21. Chỉ đo giới hạn phát hiện, không kiểm định nhãn (plan §1.9)."},
]; ];
const OCRQC = [ const OCRQC = [
@@ -330,7 +333,9 @@ const LOG = [
["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","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 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)."], ["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. 226 test đạt ngày 23/11 (plan §1.8, §1.9, §12 ý 36–37)."],
["2026-11-20","Protocol v6 khóa (SHA-256 <code>0376aa18…</code>) trước mọi điểm số cấy. <code>scripts/21_m5_synthetic.py</code>: arm T3 (3 phút 30 giây) và 4 shard T2 (khoảng 2 giờ 30 phút mỗi shard, 08:44–11:14 UTC), 5 lượt ok. Null đạt ở T2 f = 0,02 và T3, không đạt ở T2 f = 0,10; cue hiệu dụng T2 c ≈ 0,82, cường độ hiệu dụng T3 s ≈ 0,66 (plan §1.9, §12 ý 37)."],
["2026-11-23","Điều tra null T2 f = 0,10 (sau sự kiện, không thuộc protocol v6): <code>scripts/21_m5_synthetic.py --arm diagnose</code> (3 giây). Ở c = 0 &lt; f, không có cue đã là tín hiệu (chỉ báo không-cue AP 0,2004, lý thuyết 0,199); null thật c = f cho AP 0,1819 (đạt). Phán quyết khóa của v6 giữ nguyên. 22 test, tổng 226 test đạt (plan §1.9, §12 ý 37)."],
]; ];
/* ===================== HẾT DATA ===================== */ /* ===================== HẾT DATA ===================== */

259
scripts/21_m5_synthetic.py Normal file
View File

@@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""Planted-signal studies with known ground truth under protocol v6 (T2 text cues, T3 depth hazard).
scripts/21_m5_synthetic.py run both arms, write outputs/m5/synthetic/
scripts/21_m5_synthetic.py --arm t3 run one arm (the report is rebuilt from every finished run)
scripts/21_m5_synthetic.py --arm t2 --shard 0/4 run every fourth T2 planting (independent processes)
scripts/21_m5_synthetic.py --arm report rebuild report.json and the tables from finished runs only
scripts/21_m5_synthetic.py --arm diagnose post-hoc: why the T2 null check at c = 0 can fail when f > 0
Refuses to run unless configs/protocol_v6.yaml matches its checksum, its parent v5 matches the recorded checksum and
the cue lexicon matches inputs_hashed. Every T2 run is checkpointed in outputs/m5/synthetic/t2_runs/, so an
interrupted run resumes. The real activity codes and the real T2/T3 labels are never read.
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
import numpy as np
import pandas as pd
from volve_dia import m34, m5_synthetic as ms
ROOT = Path(__file__).resolve().parents[1]
PROTOCOL = ROOT / "configs/protocol_v6.yaml"
CUES = ROOT / "configs/synth_cues.yaml"
BASE_SEED, SEEDS, RESAMPLES, CI_SEED = 20261117, 5, 2000, 20261117
T2_PI, T3_PI = 0.183, 556 / 4894
T2_C = (0.0, 0.1, 0.25, 0.5, 0.75, 1.0)
T2_F_PRIMARY, T2_F_SENSITIVITY = 0.02, 0.10
T3_S = (0.0, 0.25, 0.5, 1.0, 2.0)
T2_UNIVERSE, T3_UNIVERSE = (23447, 11), (4894, 10)
T2_STATED, T3_STATED = 0.461, 0.150
def real_t2_reference(root):
rows = json.loads((root / "m34/report.json").read_text())["classification"]
match = [r for r in rows if r["task"] == "t2" and r["definition"] == "b" and r["mode"] == "masked"
and r["split"] == "well" and r["method"] == "tfidf_logistic" and r["modality"] == "xml"
and r["subset"] == "all"]
if len(match) != 1:
raise ValueError("Expected one masked T2(b) TF-IDF by-well XML row in outputs/m34/report.json")
return {"source": "outputs/m34/report.json classification: t2, b, masked, well, tfidf_logistic, xml, all",
"ap": match[0]["metrics"]["pr_auc_ap"]["estimate"], "stated_in_protocol": T2_STATED}
def real_t3_reference(root):
block = json.loads((root / "m5/t5/report.json").read_text())["knn_forecast"]["label_b"]["depth"]
return {"source": "outputs/m5/t5/report.json knn_forecast.label_b.depth.ap", "ap": block["ap"],
"stated_in_protocol": T3_STATED}
def check_universe(frame, expected, name):
if (len(frame), frame["well"].nunique()) != expected:
raise ValueError(f"{name} universe differs from protocol v6: {len(frame)} rows, "
f"{frame['well'].nunique()} wells")
def run_t2(root, dest, protocol, spec, digest, shard=(0, 1)):
acts = pd.read_parquet(root / "labels/t2_inputs.parquet", columns=ms.T2_COLUMNS)
check_universe(acts, T2_UNIVERSE, "T2")
phrases = ms.load_cues(CUES)
settings, n_splits = spec["classification"], protocol["splits"]["inner"]["n_splits"]
wells = acts["well"].to_numpy()
runs = dest / "t2_runs"
runs.mkdir(parents=True, exist_ok=True)
plan = t2_plan()
for i, (f, c, seed) in enumerate(plan):
if i % shard[1] != shard[0]:
continue
name = f"f{f:.2f}_c{c:.2f}_s{seed}"
meta = runs / f"{name}.json"
if meta.is_file() and json.loads(meta.read_text()).get("protocol_sha256") == digest:
continue
start = time.time()
y, cue = ms.plant_t2(len(acts), T2_PI, c, f, len(phrases), ms.planting_rng(seed, c, f))
text = ms.t2_text(ms.apply_cues(acts, cue, phrases))
scores, chosen = ms.t2_oof(ms.t2_inputs(acts, text), y, settings, n_splits)
exposure = ms.cue_exposure(text, y, phrases)
row = {"arm": "t2", "f": f, "c": c, "seed": seed, **ms.ap_row(y, scores, wells, RESAMPLES, CI_SEED),
"cue_rate_planted": float((cue[y] >= 0).mean()), "cue_rate_unplanted": float((cue[~y] >= 0).mean()),
"exposure_planted": exposure["planted"], "exposure_unplanted": exposure["unplanted"],
"logistic_c": chosen, "seconds": round(time.time() - start, 1), "protocol_sha256": digest}
m34.write_parquet(pd.DataFrame({"act_id": acts["act_id"], "well": wells, "planted": y, "cue": cue,
"score": scores}), runs / f"{name}.parquet")
m34.atomic_write(meta, json.dumps(row, indent=1).encode())
print(f"[{i + 1}/{len(plan)}] t2 {name}: AP {row['ap']:.4f} ({row['seconds']} s)", flush=True)
def t2_plan():
return [(f, c, BASE_SEED + k) for f in (T2_F_PRIMARY, T2_F_SENSITIVITY) for c in T2_C for k in range(SEEDS)]
def collect_t2(dest, digest):
"""Every finished T2 planting of the current protocol, in plan order."""
rows = []
for f, c, seed in t2_plan():
meta = dest / "t2_runs" / f"f{f:.2f}_c{c:.2f}_s{seed}.json"
if meta.is_file() and (row := json.loads(meta.read_text())).get("protocol_sha256") == digest:
rows.append(row)
return pd.DataFrame(rows)
def run_t3(root, dest):
cells = pd.read_parquet(root / "m34/features_t3.parquet", columns=ms.T3_COLUMNS)
check_universe(cells, T3_UNIVERSE, "T3")
z = ms.zscore(cells["md_top"])
wells = cells["well"].to_numpy()
rows, frames = [], []
for s in T3_S:
for k in range(SEEDS):
seed = BASE_SEED + k
a, p, y = ms.plant_t3(z, s, T3_PI, ms.planting_rng(seed, s))
scores = ms.t3_scores(cells, y)
oracle = ms.ap_row(y, p, wells, RESAMPLES, CI_SEED)
rows.append({"arm": "t3", "s": s, "seed": seed, "intercept": a, "mean_p": float(p.mean()),
**ms.ap_row(y, scores, wells, RESAMPLES, CI_SEED), "oracle_ap": oracle["ap"],
"oracle_ci_low": oracle["ci_low"], "oracle_ci_high": oracle["ci_high"]})
frames.append(pd.DataFrame({"item": cells["item"], "well": wells, "s": s, "seed": seed, "p": p,
"planted": y, "score": scores}))
print(f"t3 s={s} seed={seed}: AP {rows[-1]['ap']:.4f}, oracle {oracle['ap']:.4f}", flush=True)
m34.write_parquet(pd.concat(frames, ignore_index=True), dest / "t3_scores.parquet")
return pd.DataFrame(rows)
def diagnose_t2(dest):
"""Post-hoc (not part of protocol v6): the model AP against the AP of the no-own-cue indicator, per setting."""
rows = []
for path in sorted((dest / "t2_runs").glob("*.parquet")):
meta = json.loads(path.with_suffix(".json").read_text())
run = pd.read_parquet(path)
y = run["planted"].to_numpy()
rows.append({"f": meta["f"], "c": meta["c"], "seed": meta["seed"], "prevalence": float(y.mean()),
"model_ap": meta["ap"], "no_cue_indicator_ap": ms.no_cue_indicator_ap(y, run["cue"]),
"own_cue_rate_planted": float((run["cue"][y] >= 0).mean()),
"own_cue_rate_unplanted": float((run["cue"][~y] >= 0).mean())})
seeds = pd.DataFrame(rows)
table = seeds.groupby(["f", "c"], as_index=False).mean(numeric_only=True).drop(columns="seed")
table["seeds"] = seeds.groupby(["f", "c"])["seed"].nunique().to_numpy()
table["expected_no_cue_ap_at_c0"] = [ms.expected_no_cue_ap(T2_PI, f) if np.isclose(c, 0) else np.nan
for f, c in zip(table["f"], table["c"])]
return table
def t2_block(seeds, reference):
block = {"settings": {}, "null_checks": {}}
table = ms.summarise(seeds, ["f", "c"], T2_PI)
for f, g in table.groupby("f"):
block["settings"][f"f={f:.2f}"] = g.drop(columns="f").to_dict(orient="records")
null = g[np.isclose(g["c"], 0.0)]
if len(null):
r = null.iloc[0]
block["null_checks"][f"f={f:.2f}"] = ms.null_check(r["ap_mean"], [r["seed0_ci_low"], r["seed0_ci_high"]],
T2_PI) | {"seeds": int(r["seeds"])}
primary = seeds[np.isclose(seeds["f"], T2_F_PRIMARY)]
complete = primary.groupby("c")["seed"].nunique().reindex(T2_C).fillna(0).eq(SEEDS).all()
block["effective_cue_rate"] = {"f": T2_F_PRIMARY, "complete_grid": bool(complete)}
if complete:
block["effective_cue_rate"] |= {
"reference_report": ms.interpolate_with_seeds(primary, "c", reference["ap"]),
"reference_stated_0.461": ms.interpolate_with_seeds(primary, "c", T2_STATED)}
return block, table
def t3_block(seeds, reference):
table = ms.summarise(seeds, ["s"], T3_PI)
null = table[np.isclose(table["s"], 0.0)].iloc[0]
oracle_null = ms.null_check(null["oracle_ap_mean"], None, T3_PI)
block = {"settings": table.to_dict(orient="records"),
"null_checks": {"depth_knn": ms.null_check(null["ap_mean"], [null["seed0_ci_low"], null["seed0_ci_high"]],
T3_PI) | {"seeds": int(null["seeds"])},
"oracle_mean_ap_at_s0": oracle_null["mean_ap"]},
"effective_strength": {
"reference_report": ms.interpolate_with_seeds(seeds, "s", reference["ap"]),
"reference_stated_0.150": ms.interpolate_with_seeds(seeds, "s", T3_STATED)}}
return block, table
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--arm", choices=["t2", "t3", "all", "report", "diagnose"], default="all")
parser.add_argument("--shard", default="0/1", help="i/n: run the T2 plantings whose index modulo n is i")
args = parser.parse_args()
shard = tuple(int(v) for v in args.shard.split("/"))
try:
v6, digest = ms.verify_protocol(PROTOCOL, ROOT)
except ValueError as error:
raise SystemExit(str(error))
protocol, spec = m34.configuration()
root, digests = m34.inputs(protocol)
dest = root / "m5/synthetic"
dest.mkdir(parents=True, exist_ok=True)
if args.arm == "diagnose":
table = diagnose_t2(dest)
table.to_csv(dest / "null_diagnosis_t2.csv", index=False)
print(table.round(4).to_string(index=False))
references = {"t2": real_t2_reference(root), "t3": real_t3_reference(root)}
t3_path, t2_path = dest / "seeds_t3.csv", dest / "seeds_t2.csv"
if args.arm in ("t3", "all"):
run_t3(root, dest).to_csv(t3_path, index=False)
if args.arm in ("t2", "all"):
run_t2(root, dest, protocol, spec, digest, shard)
t2 = collect_t2(dest, digest)
if len(t2):
t2.drop(columns="logistic_c").assign(logistic_c=t2["logistic_c"].map(json.dumps)).to_csv(t2_path, index=False)
report = {"protocol": {"file": str(PROTOCOL.relative_to(ROOT)), "sha256": digest, "version": v6["version"],
"cues_sha256": v6["inputs_hashed"]["configs/synth_cues.yaml"]},
"inputs": digests, "references": references,
"design": {
"seeds": [BASE_SEED + k for k in range(SEEDS)], "rng": "numpy default_rng([seed, round(1000 x "
"setting) ...]); T2 settings (c, f), T3 setting s; one planting per seed and setting",
"ci": {"resamples": RESAMPLES, "seed": CI_SEED, "cluster": "well", "function": "m5_t5.ap_ci"},
"t2_pi": T2_PI, "t3_pi": T3_PI, "lift": "AP / pi (nominal pi)",
"t2_model": "m34_classify.fold_prediction (TF-IDF word 1-2 grams, min_df 2, sublinear tf, "
"max_features 60000; logistic C from [0.25, 1, 4] by inner GroupKFold(5) on wells, "
"average precision), leave-one-well-out, sequential folds",
"t2_inputs": "well + text_xml only: the real T2 frame has no numeric column in the model allowlist "
"(m34_classify.numeric_columns), so the baseline is text-only, as in M3-M4",
"t2_cue_placement": "phrase appended after the activity comment with one space before the text is "
"built; the real text construction (comments, previous, next, sum24Hr, "
"forecast24Hr joined by [SEP]) then also carries a cued comment into the "
"previous/next fields of adjacent activities of the same report "
"(see exposure_* columns)",
"t3_model": "m5_t5.knn_scores(features, planted, ['md_top']), k = 10, other wells",
"t3_covariate": "z-score of md_top over the 4,894 cells (population sd)"},
"outputs": {}}
if t3_path.is_file():
report["t3_hazard"], table = t3_block(pd.read_csv(t3_path), references["t3"])
table.to_csv(dest / "settings_t3.csv", index=False)
if t2_path.is_file():
seeds = pd.read_csv(t2_path)
report["t2_cues"], table = t2_block(seeds, references["t2"])
table.to_csv(dest / "settings_t2.csv", index=False)
report["t2_cues"]["runs"] = int(len(seeds))
report["t2_cues"]["seconds_total"] = float(seeds["seconds"].sum())
if (dest / "null_diagnosis_t2.csv").is_file():
report["t2_cues"]["null_diagnosis_post_hoc"] = {
"note": "not part of protocol v6: at c = 0 and f > 0 the absence of an own cue already points to a "
"planted row, so the setting is not a null; c = f is",
"rows": pd.read_csv(dest / "null_diagnosis_t2.csv").to_dict(orient="records")}
report["outputs"] = sorted(p.name for p in dest.iterdir() if p.is_file() and p.name != "report.json")
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()
if isinstance(value, np.bool_):
return bool(value)
raise TypeError(type(value))
if __name__ == "__main__":
main()

222
tests/test_m5_synthetic.py Normal file
View File

@@ -0,0 +1,222 @@
from __future__ import annotations
import hashlib
import numpy as np
import pandas as pd
import pytest
import yaml
from volve_dia import m5_synthetic as ms
from volve_dia.paths import REPO_ROOT
PHRASES = [("equipment", "Top drive failure."), ("weather", "Waiting on weather.")]
def toy_acts(n=60, wells=4):
rng = np.random.default_rng(0)
words = np.array(["drilled", "circulated", "tripped", "reamed", "logged", "cased"])
return pd.DataFrame({
"act_id": [f"A{i:03d}" for i in range(n)], "report_id": [f"R{i // 5:02d}" for i in range(n)],
"well": [f"W{i % wells}" for i in range(n)], "seq": [i % 5 for i in range(n)],
"comments": [" ".join(rng.choice(words, 4)) if i % 7 else None for i in range(n)],
"sum24Hr": ["day summary"] * n, "forecast24Hr": ["forecast"] * n})
@pytest.mark.parametrize("s", [0.0, 0.25, 1.0, 2.0, 5.0])
def test_bisection_hits_target_mean(s):
z = ms.zscore(np.random.default_rng(1).gamma(2.0, 1000.0, size=4000))
a = ms.solve_intercept(z, s, 0.114)
assert abs((1 / (1 + np.exp(-(a + s * z)))).mean() - 0.114) < 1e-9
if s == 0:
assert a == pytest.approx(np.log(0.114 / 0.886), abs=1e-9)
def test_zscore_is_standard():
z = ms.zscore([1.0, 2.0, 3.0, 10.0])
assert z.mean() == pytest.approx(0) and z.std() == pytest.approx(1)
def test_t2_planting_rates_within_tolerance():
n, pi, c, f = 200_000, 0.183, 0.5, 0.02
y, cue = ms.plant_t2(n, pi, c, f, 21, ms.planting_rng(20261117, c, f))
assert abs(y.mean() - pi) < 0.004
assert abs((cue[y] >= 0).mean() - c) < 0.01
assert abs((cue[~y] >= 0).mean() - f) < 0.003
counts = np.bincount(cue[cue >= 0], minlength=21) / (cue >= 0).sum()
assert np.abs(counts - 1 / 21).max() < 0.01
assert cue.min() >= -1 and cue.max() < 21
def test_t2_planting_extremes():
y, cue = ms.plant_t2(10_000, 0.183, 1.0, 0.0, 3, ms.planting_rng(1, 1.0, 0.0))
assert (cue[y] >= 0).all() and (cue[~y] == -1).all()
y, cue = ms.plant_t2(10_000, 0.183, 0.0, 0.0, 3, ms.planting_rng(1, 0.0, 0.0))
assert (cue == -1).all()
def test_t3_planting_prevalence():
z = ms.zscore(np.linspace(0, 5000, 50_000))
a, p, y = ms.plant_t3(z, 1.0, 0.114, ms.planting_rng(20261117, 1.0))
assert p.mean() == pytest.approx(0.114, abs=1e-9)
assert abs(y.mean() - 0.114) < 0.006
assert np.corrcoef(z, p)[0, 1] > 0.8
def test_seeds_are_deterministic_and_distinct():
first = ms.plant_t2(1000, 0.183, 0.5, 0.02, 21, ms.planting_rng(20261117, 0.5, 0.02))
again = ms.plant_t2(1000, 0.183, 0.5, 0.02, 21, ms.planting_rng(20261117, 0.5, 0.02))
other_seed = ms.plant_t2(1000, 0.183, 0.5, 0.02, 21, ms.planting_rng(20261118, 0.5, 0.02))
other_setting = ms.plant_t2(1000, 0.183, 0.5, 0.10, 21, ms.planting_rng(20261117, 0.5, 0.10))
assert all(np.array_equal(u, v) for u, v in zip(first, again))
assert not np.array_equal(first[0], other_seed[0])
assert not np.array_equal(first[0], other_setting[0])
def test_cue_appended_after_comment_only_where_specified():
acts = toy_acts()
cue = np.full(len(acts), -1)
cue[[1, 7, 12]] = [0, 1, 0] # row 7 has no comment
out = ms.apply_cues(acts, cue, PHRASES)
assert out.loc[1, "comments"] == acts.loc[1, "comments"] + " Top drive failure."
assert out.loc[7, "comments"] == "Waiting on weather."
assert out.loc[12, "comments"] == acts.loc[12, "comments"] + " Top drive failure."
untouched = np.setdiff1d(np.arange(len(acts)), [1, 7, 12])
pd.testing.assert_frame_equal(out.iloc[untouched], acts.iloc[untouched])
pd.testing.assert_frame_equal(out.drop(columns="comments"), acts.drop(columns="comments"))
assert acts.loc[1, "comments"] != out.loc[1, "comments"] # the input frame is not modified
def test_text_matches_the_real_construction():
acts = toy_acts()
cue = np.full(len(acts), -1)
cue[1] = 0
text = ms.t2_text(ms.apply_cues(acts, cue, PHRASES))
# Fields: comments, previous, next, sum24Hr, forecast24Hr of the same report.
assert text[1].split(" [SEP] ")[0].endswith("Top drive failure.")
assert text[2].split(" [SEP] ")[1].endswith("Top drive failure.")
assert text[0].split(" [SEP] ")[2].endswith("Top drive failure.")
assert "Top drive" not in text[5] # another report
x = ms.t2_inputs(acts, text)
assert list(x.columns) == ["well", "text"]
def test_null_calibration_on_toy_case():
rng = np.random.default_rng(3)
n, pi = 20_000, 0.2
y = rng.random(n) < pi
wells = np.repeat(np.arange(10), n // 10)
aps = [ms.ap_row(y, rng.random(n), wells, 200, 1) for _ in range(5)]
mean = np.mean([a["ap"] for a in aps])
check = ms.null_check(mean, [aps[0]["ci_low"], aps[0]["ci_high"]], y.mean())
assert check["null_check_passed"]
assert not ms.null_check(pi + 0.05, [pi + 0.02, pi + 0.08], pi)["null_check_passed"]
assert not ms.null_check(pi + 0.005, [pi + 0.001, pi + 0.01], pi)["null_check_passed"]
def test_null_calibration_of_the_t2_pipeline_on_toy_text():
acts = toy_acts(n=400, wells=4)
settings = {"tfidf_min_df": 2, "logistic_c": [1.0]}
y, cue = ms.plant_t2(len(acts), 0.25, 0.0, 0.2, len(PHRASES), ms.planting_rng(5, 0.0, 0.2))
x = ms.t2_inputs(acts, ms.t2_text(ms.apply_cues(acts, cue, PHRASES)))
scores, chosen = ms.t2_oof(x, y, settings, n_splits=3)
assert np.isfinite(scores).all() and set(chosen) == {"W0", "W1", "W2", "W3"}
y1, cue1 = ms.plant_t2(len(acts), 0.25, 1.0, 0.0, len(PHRASES), ms.planting_rng(5, 1.0, 0.0))
x1 = ms.t2_inputs(acts, ms.t2_text(ms.apply_cues(acts, cue1, PHRASES)))
strong, _ = ms.t2_oof(x1, y1, settings, n_splits=3)
from sklearn.metrics import average_precision_score
assert average_precision_score(y1, strong) > average_precision_score(y, scores) + 0.2
def test_t3_knn_scores_use_other_wells():
cells = pd.DataFrame({"well": ["A"] * 20 + ["B"] * 20, "md_top": np.tile(np.arange(20.0), 2)})
y = np.r_[np.ones(20), np.zeros(20)]
scores = ms.t3_scores(cells, y)
assert (scores[:20] == 0).all() and (scores[20:] == 1).all()
def test_interpolation_within_and_out_of_range():
grid = [0.0, 0.1, 0.25, 0.5, 0.75, 1.0]
values = [0.18, 0.2, 0.3, 0.4, 0.6, 0.8]
r = ms.interpolate(grid, values, 0.35)
assert r["value"] == pytest.approx(0.375) and r["out_of_range"] is None
assert ms.interpolate(grid, values, 0.18)["value"] == pytest.approx(0.0)
assert ms.interpolate(grid, values, 0.8)["value"] == pytest.approx(1.0)
assert ms.interpolate(grid, values, 0.9) == {"value": None, "out_of_range": "above_last_grid_point",
"target": 0.9}
assert ms.interpolate(grid, values, 0.1)["out_of_range"] == "below_first_grid_point"
# A non-monotone curve uses the first bracketing segment.
r = ms.interpolate([0, 1, 2, 3], [0.1, 0.5, 0.3, 0.6], 0.4)
assert r["value"] == pytest.approx(0.75) and r["monotone"] is False
def test_interpolation_with_seed_range():
rows = pd.DataFrame({"seed": np.repeat([0, 1], 3), "c": np.tile([0.0, 0.5, 1.0], 2),
"ap": [0.2, 0.4, 0.6, 0.2, 0.3, 0.4]})
r = ms.interpolate_with_seeds(rows, "c", 0.45)
assert r["value"] == pytest.approx(0.5 + 0.1 / 0.15 * 0.5)
assert r["per_seed"][0]["value"] == pytest.approx(0.625)
assert r["per_seed"][1]["out_of_range"] == "above_last_grid_point"
assert r["seed_range"] == [pytest.approx(0.625), pytest.approx(0.625)] and r["seeds_out_of_range"] == 1
mean = ms.interpolate([0.0, 0.5, 1.0], [0.2, 0.35, 0.5], 0.45)
assert r["value"] == pytest.approx(mean["value"])
def test_summarise_reports_mean_range_and_seed0():
rows = pd.DataFrame({"s": [0.0] * 3, "seed": [3, 1, 2], "ap": [0.12, 0.10, 0.11], "ci_low": [0.0, 0.09, 0.0],
"ci_high": [1.0, 0.13, 1.0], "prevalence": [0.11, 0.115, 0.112]})
table = ms.summarise(rows, ["s"], 0.114)
row = table.iloc[0]
assert row["ap_mean"] == pytest.approx(0.11) and row["ap_min"] == 0.10 and row["ap_max"] == 0.12
assert row["seed0_ap"] == 0.10 and row["seed0_ci_low"] == 0.09
assert row["lift_mean"] == pytest.approx(0.11 / 0.114)
def _locked_pair(tmp_path, cue_text="cues: {a: [x]}\n"):
(tmp_path / "configs").mkdir()
cues = tmp_path / "configs/synth_cues.yaml"
cues.write_text(cue_text)
parent = tmp_path / "configs/parent.yaml"
parent.write_text("version: 5\n")
protocol = tmp_path / "configs/protocol_test.yaml"
protocol.write_text(yaml.safe_dump({
"status": "locked", "version": 6,
"extends": {"file": "configs/parent.yaml", "sha256": hashlib.sha256(parent.read_bytes()).hexdigest()},
"inputs_hashed": {"configs/synth_cues.yaml": hashlib.sha256(cues.read_bytes()).hexdigest()}}))
protocol.with_suffix(".yaml.sha256").write_text(
hashlib.sha256(protocol.read_bytes()).hexdigest() + " configs/protocol_test.yaml\n")
return protocol, cues
def test_verify_protocol_accepts_and_refuses(tmp_path):
protocol, cues = _locked_pair(tmp_path)
parsed, digest = ms.verify_protocol(protocol, tmp_path)
assert parsed["version"] == 6 and len(digest) == 64
cues.write_text("cues: {a: [y]}\n")
with pytest.raises(ValueError, match="synth_cues.yaml"):
ms.verify_protocol(protocol, tmp_path)
def test_verify_protocol_refuses_edited_protocol(tmp_path):
protocol, _ = _locked_pair(tmp_path)
protocol.write_text(protocol.read_text() + "# edited\n")
with pytest.raises(ValueError, match="checksum"):
ms.verify_protocol(protocol, tmp_path)
def test_locked_v6_and_cues_verify():
protocol, _ = ms.verify_protocol(REPO_ROOT / "configs/protocol_v6.yaml", REPO_ROOT)
assert protocol["t2_cues"]["settings"]["c"] == [0.0, 0.1, 0.25, 0.5, 0.75, 1.0]
assert protocol["t3_hazard"]["settings"]["s"] == [0.0, 0.25, 0.5, 1.0, 2.0]
phrases = ms.load_cues(REPO_ROOT / "configs/synth_cues.yaml")
assert len(phrases) == 21 and len({p for _, p in phrases}) == 21
def test_absence_of_a_cue_is_signal_when_f_exceeds_c():
rng = np.random.default_rng(5)
n, pi, f = 200_000, 0.183, 0.10
y, cue = ms.plant_t2(n, pi, 0.0, f, 20, rng)
assert ms.no_cue_indicator_ap(y, cue) == pytest.approx(ms.expected_no_cue_ap(pi, f), abs=0.004)
assert ms.expected_no_cue_ap(pi, f) > pi + 0.01
y, cue = ms.plant_t2(n, pi, f, f, 20, rng) # c = f is the true null: the cue is independent of the label
assert ms.no_cue_indicator_ap(y, cue) == pytest.approx(pi, abs=0.004)

240
volve_dia/m5_synthetic.py Normal file
View File

@@ -0,0 +1,240 @@
"""Planted-signal studies with known ground truth under protocol v6 (T2 text cues, T3 depth hazard).
The planted label is drawn by a fixed random rule, so the truth is known exactly. The real activity codes and the
real T2/T3 labels are never read. The T2 model is the M3-M4 TF-IDF + logistic baseline unchanged; the T3 forecast is
the v5 depth neighbour forecast.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
import yaml
from scipy.special import expit
from sklearn.model_selection import LeaveOneGroupOut
from .m34_classify import fold_prediction, model_inputs
from .m34_features import TEXT, activity_text, strings
from .m5_judge import sha256_file
from .m5_t5 import ap_ci, knn_scores
T2_COLUMNS = ["act_id", "report_id", "well", "seq", "comments", "sum24Hr", "forecast24Hr"]
T3_COLUMNS = ["item", "well", "wellbore", "md_top"]
def verify_protocol(protocol_path, repo_root):
"""Return the parsed protocol, or raise if it or any hashed input differs from its locked checksum."""
expected = protocol_path.with_suffix(".yaml.sha256").read_text().split()[0]
actual = sha256_file(protocol_path)
if actual != expected:
raise ValueError(f"{protocol_path.name} does not match its checksum")
protocol = yaml.safe_load(protocol_path.read_text())
if protocol.get("status") != "locked":
raise ValueError(f"{protocol_path.name} is not locked")
parent = protocol.get("extends")
if parent and sha256_file(repo_root / parent["file"]) != parent["sha256"]:
raise ValueError(f"{parent['file']} does not match the checksum recorded in {protocol_path.name}")
for name, digest in protocol.get("inputs_hashed", {}).items():
if sha256_file(repo_root / name) != digest:
raise ValueError(f"{name} does not match the checksum recorded in {protocol_path.name}")
return protocol, actual
def load_cues(path):
"""Flat list of (class, phrase) in file order."""
cues = yaml.safe_load(path.read_text())["cues"]
return [(cls, phrase) for cls, phrases in cues.items() for phrase in phrases]
def planting_rng(seed, *settings):
"""Deterministic generator for one planting: the seed plus each setting in thousandths."""
return np.random.default_rng([int(seed), *(int(round(float(v) * 1000)) for v in settings)])
# T2 text cues ---------------------------------------------------------------------------------------------------
def plant_t2(n, pi, c, f, n_phrases, rng):
"""y ~ Bernoulli(pi); a cue with probability c (planted) or f (unplanted); phrase uniform. -1 means no cue."""
y = rng.random(n) < pi
u = rng.random(n)
cued = np.where(y, u < c, u < f)
phrase = rng.integers(0, n_phrases, size=n)
return y, np.where(cued, phrase, -1)
def apply_cues(acts, cue, phrases):
"""Append the chosen phrase after the comment with one space. Rows without a cue are unchanged."""
out = acts.copy()
cue = np.asarray(cue)
rows = np.flatnonzero(cue >= 0)
text = np.array([p for _, p in phrases], dtype=object)[cue[rows]]
base = out["comments"].iloc[rows]
out.iloc[rows, out.columns.get_loc("comments")] = np.where(
base.isna(), text, base.fillna("").astype(str).to_numpy(dtype=object) + " " + text)
return out
def t2_text(acts):
"""The masked XML text of the real T2 frame (m34_features.t2_frame), in the row order of acts."""
view = activity_text(acts)
return acts["act_id"].map(strings(view.set_index("act_id"), TEXT)).to_numpy()
def t2_inputs(acts, text):
"""Model inputs as m34_classify.model_inputs(frame, 'masked', 'xml'); the T2 frame has no numeric column."""
frame = pd.DataFrame({"well": acts["well"].to_numpy(), "text_xml": text})
return model_inputs(frame, "masked", "xml")
def t2_oof(x, y, settings, n_splits, group="well"):
"""Leave-one-well-out out-of-fold scores with the M3-M4 fold fit (inner GroupKFold over C)."""
scores = np.full(len(x), np.nan)
chosen = {}
groups = x[group].to_numpy()
for train_idx, test_idx in LeaveOneGroupOut().split(x, y, groups=groups):
train_wells = x["well"].iloc[train_idx]
tune = np.flatnonzero(~train_wells.isin(x["well"].iloc[test_idx]).to_numpy())
out, c, _ = fold_prediction(x.iloc[train_idx], y[train_idx], tune, {"xml": x.iloc[test_idx]}, "t2",
settings, n_splits, None)
scores[test_idx] = out["xml"][1]
chosen[str(groups[test_idx[0]])] = c
return scores, chosen
def cue_exposure(text, y, phrases):
"""Share of planted and unplanted rows whose model text contains any phrase (own comment or neighbour field)."""
contains = np.zeros(len(text), dtype=bool)
for _, phrase in phrases:
contains |= pd.Series(text).str.contains(phrase, regex=False).to_numpy()
return {"planted": float(contains[y].mean()) if y.any() else None,
"unplanted": float(contains[~y].mean()) if (~y).any() else None}
# T3 depth hazard ------------------------------------------------------------------------------------------------
def zscore(values):
values = np.asarray(values, dtype=float)
return (values - values.mean()) / values.std()
def solve_intercept(z, s, target, lo=-50.0, hi=50.0, tol=1e-12, iterations=200):
"""Bisection for a such that mean(sigmoid(a + s z)) = target (monotone increasing in a)."""
z = np.asarray(z, dtype=float)
for _ in range(iterations):
mid = (lo + hi) / 2
gap = expit(mid + s * z).mean() - target
if abs(gap) < tol:
break
lo, hi = (mid, hi) if gap < 0 else (lo, mid)
return mid
def plant_t3(z, s, pi, rng):
a = solve_intercept(z, s, pi)
p = expit(a + s * np.asarray(z, dtype=float))
return a, p, rng.random(len(p)) < p
def t3_scores(cells, y):
"""v5 depth neighbour forecast (k = 10 nearest md_top cells of the other wells, mean planted label)."""
frame = cells[["well", "md_top"]].reset_index(drop=True).assign(planted=np.asarray(y, dtype=int))
return knn_scores(frame, "planted", ["md_top"]).to_numpy()
# Summaries ------------------------------------------------------------------------------------------------------
def summarise(rows, key, pi):
"""Mean and range over seeds per setting; the seed-0 interval; the null check at the null setting."""
out = []
for setting, g in rows.groupby(key, sort=True):
g = g.sort_values("seed")
first = g.iloc[0]
ap = g["ap"]
row = dict(zip(key, setting if isinstance(setting, tuple) else (setting,)))
row |= {"seeds": int(len(g)), "ap_mean": float(ap.mean()), "ap_min": float(ap.min()),
"ap_max": float(ap.max()), "lift_mean": float(ap.mean() / pi),
"lift_min": float(ap.min() / pi), "lift_max": float(ap.max() / pi),
"ap_minus_pi_mean": float(ap.mean() - pi),
"seed0_ap": float(first["ap"]), "seed0_ci_low": float(first["ci_low"]),
"seed0_ci_high": float(first["ci_high"]),
"prevalence_mean": float(g["prevalence"].mean()), "prevalence_min": float(g["prevalence"].min()),
"prevalence_max": float(g["prevalence"].max())}
for extra in ("oracle_ap", "cue_rate_planted", "cue_rate_unplanted", "exposure_planted",
"exposure_unplanted"):
if extra in g:
row[f"{extra}_mean"] = float(g[extra].mean())
row[f"{extra}_min"] = float(g[extra].min())
row[f"{extra}_max"] = float(g[extra].max())
out.append(row)
return pd.DataFrame(out)
def null_check(mean_ap, ci, pi, tolerance=0.01):
within = abs(mean_ap - pi) <= tolerance
contains = ci is not None and ci[0] <= pi <= ci[1]
return {"mean_ap": float(mean_ap), "pi": float(pi), "tolerance": tolerance, "mean_within_tolerance": bool(within),
"seed0_ci": list(ci) if ci is not None else None, "seed0_ci_contains_pi": bool(contains),
"null_check_passed": bool(within and contains)}
def interpolate(grid, values, target):
"""Grid value at which the AP curve reaches target, by linear interpolation between grid points.
Out of range when target lies above the AP at the last grid point or below the AP at the first one. Within range,
the first segment that brackets target is used; a curve that never brackets it is also out of range.
"""
grid, values = np.asarray(grid, dtype=float), np.asarray(values, dtype=float)
if target > values[-1]:
return {"value": None, "out_of_range": "above_last_grid_point", "target": float(target)}
if target < values[0]:
return {"value": None, "out_of_range": "below_first_grid_point", "target": float(target)}
for i in range(len(grid) - 1):
lo, hi = values[i], values[i + 1]
if min(lo, hi) <= target <= max(lo, hi):
value = grid[i] if hi == lo else grid[i] + (target - lo) / (hi - lo) * (grid[i + 1] - grid[i])
return {"value": float(value), "out_of_range": None, "target": float(target), "segment": [
float(grid[i]), float(grid[i + 1])], "monotone": bool(np.all(np.diff(values) >= 0))}
return {"value": None, "out_of_range": "not_bracketed", "target": float(target)}
def interpolate_with_seeds(rows, axis, target, fixed=None):
"""Interpolation on the mean curve, plus per-seed interpolations and their range."""
if fixed:
for k, v in fixed.items():
rows = rows[np.isclose(rows[k], v)]
mean = rows.groupby(axis)["ap"].mean().sort_index()
result = interpolate(mean.index, mean.to_numpy(), target)
per_seed = {}
for seed, g in rows.groupby("seed"):
curve = g.set_index(axis)["ap"].sort_index()
per_seed[int(seed)] = interpolate(curve.index, curve.to_numpy(), target)
values = [r["value"] for r in per_seed.values() if r["value"] is not None]
result["per_seed"] = per_seed
result["seed_range"] = [float(min(values)), float(max(values))] if values else None
result["seeds_out_of_range"] = int(sum(r["value"] is None for r in per_seed.values()))
result["grid"] = [float(v) for v in mean.index]
result["mean_ap_curve"] = [float(v) for v in mean.to_numpy()]
return result
def no_cue_indicator_ap(planted, cue):
"""AP of the score "the row has no own cue" (1 without, 0 with); the structural signal of f > c.
Planted rows receive a cue with probability c and unplanted rows with probability f, so when f > c the absence
of a cue already points to a planted row and the setting is not a null even though the cue is independent of
the real text. At c = 0 every planted row has no cue and the expected AP is pi / (pi + (1 - pi)(1 - f)).
"""
from sklearn.metrics import average_precision_score
return float(average_precision_score(np.asarray(planted, dtype=bool), (np.asarray(cue) < 0).astype(float)))
def expected_no_cue_ap(pi, f):
"""Expected AP of the no-cue indicator at c = 0 (a two-tier ranking with all positives in the first tier)."""
return pi / (pi + (1 - pi) * (1 - f))
def ap_row(y, scores, wells, resamples, seed):
block = ap_ci(y, scores, wells, resamples, seed)
ci = block["ci95"] or [np.nan, np.nan]
return {"ap": block["ap"], "ci_low": ci[0], "ci_high": ci[1], "prevalence": block["prevalence"],
"positives": block["positives"], "n": block["n"]}