P2 diagnosis on dev, P3 dev experiments, lock protocol_p3

- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 06:03:33 +00:00
parent a76e61398a
commit cee2ff0859
84 changed files with 8793 additions and 460 deletions

View File

@@ -1,9 +1,9 @@
"""Ghi manifest SHA-256 cho một bộ dữ liệu và đối chiếu với manifest đã commit.
"""Write a SHA-256 manifest for a dataset and check it against the committed manifest.
python scripts/00_data_manifest.py # tạo/cập nhật manifest F3
python scripts/00_data_manifest.py --check # chỉ kiểm tra, exit 1 nếu lệch
python scripts/00_data_manifest.py --dataset volve # tương tự cho data/Volve
python scripts/00_data_manifest.py --dataset nlog # tương tự cho data/NLOG
python scripts/00_data_manifest.py # create/update the F3 manifest
python scripts/00_data_manifest.py --check # check only; exit 1 on mismatch
python scripts/00_data_manifest.py --dataset volve # same for data/Volve
python scripts/00_data_manifest.py --dataset nlog # same for data/NLOG
"""
from __future__ import annotations
@@ -20,8 +20,8 @@ from ml_porosity.paths import REPO_ROOT, f3_root, nlog_root, volve_root
DATASETS = {
"f3": (f3_root, "f3_demo_2023.json", "F3 Demo 2023 (dGB Earth Sciences / TerraNubis), CC BY-SA 3.0"),
"volve": (volve_root, "volve.json", "Volve data village (Equinor), giấy phép HRS / CC BY-NC-SA 4.0"),
"nlog": (nlog_root, "nlog.json", "NLOG (TNO), LAS và TD công khai của giếng F3; URL ở docs/research/f3-nlog-inventory.xlsx"),
"volve": (volve_root, "volve.json", "Volve data village (Equinor), HRS licence / CC BY-NC-SA 4.0"),
"nlog": (nlog_root, "nlog.json", "NLOG (TNO), public LAS and TD data for the F3 wells; URLs in docs/research/f3-nlog-inventory.xlsx"),
}
@@ -59,10 +59,10 @@ def main() -> int:
missing = sorted(set(ref) - set(current))
changed = sorted(k for k in set(ref) & set(current) if ref[k]["sha256"] != current[k]["sha256"])
extra = sorted(set(current) - set(ref))
for name, items in (("thiếu", missing), ("khác hash", changed), ("thừa", extra)):
for name, items in (("missing", missing), ("hash mismatch", changed), ("extra", extra)):
for k in items:
print(f"{name}: {k}")
print(f"{len(current)} file, {len(missing)} thiếu, {len(changed)} khác hash, {len(extra)} thừa")
print(f"{len(current)} files, {len(missing)} missing, {len(changed)} hash mismatch, {len(extra)} extra")
return 1 if (missing or changed) else 0
out = {

View File

@@ -1,14 +1,14 @@
"""Dựng bộ dữ liệu giếng F3 trong miền thời gian seismic.
"""Build the F3 well dataset in the seismic time domain.
python scripts/01_build_wells.py [--config configs/d1_f3.yaml]
Đầu ra (trong outputs/):
f3_wells.npz khóa phẳng "<giếng>/<mục>", không cần allow_pickle. Mọi chuỗi theo thời gian
nằm trên cửa sổ mở rộng `ext_window_ms`; `main_mask` đánh dấu cửa sổ chính:
Outputs (in outputs/):
f3_wells.npz flat keys "<well>/<item>", no allow_pickle needed. All time series lie on
the extended window `ext_window_ms`; `main_mask` marks the main window:
seismic_patch (C, L), times_ms (L,), main_mask (L,), il, xl, x, y,
anchors_md, anchors_twt_ms, tdr/<tên>/md, tdr/<tên>/twt_ms,
<tên TDR>/<curve> (L,), horizon/<tên> (TWT ms tại giếng)
f3_wells_summary.json vị trí giếng (thật và của luận văn), số anchor, độ phủ nhãn.
anchors_md, anchors_twt_ms, tdr/<name>/md, tdr/<name>/twt_ms,
<TDR name>/<curve> (L,), horizon/<name> (TWT ms at the well)
f3_wells_summary.json well locations (true and as used in the thesis), anchor counts, label coverage.
"""
from __future__ import annotations
@@ -43,7 +43,7 @@ def build_tdrs(well: Well, names: list[str]) -> dict[str, TDR]:
elif name == "wlt":
out[name] = TDR.from_pairs(load_td_source(well.name, "wlt"), "wlt", drop_flat=True)
else:
raise ValueError(f"TDR không hỗ trợ: {name}")
raise ValueError(f"unsupported TDR: {name}")
return out
@@ -64,7 +64,7 @@ def main() -> None:
main = (t_win >= t0) & (t_win <= t1)
for name in cfg["wells"]:
w = load_well(name)
# Nhãn hài hoà theo plan mục 1.2d / D-1: PHIE_DT = −0.2018 + 0.0011·DT cho cả 4 giếng.
# Harmonized label per plan §1.2d / D-1: PHIE_DT = −0.2018 + 0.0011·DT for all 4 wells.
w.logs["PHIE_DT"] = -0.2018 + 0.0011 * w.logs["DT"]
il, xl = geom.nearest_bin(w.x, w.y)
patch = cube.patch(il, xl, cfg["patch_radius"])[:, win]
@@ -101,10 +101,10 @@ def main() -> None:
info["legacy_offset_km"] = round(float(np.hypot(lx - w.x, ly - w.y)) / 1000, 2)
summary["wells"][name] = info
print(f"{name}: IL/XL {il}/{xl}"
+ (f" (luận văn {info['legacy_il_xl'][0]}/{info['legacy_il_xl'][1]}, lệch {info['legacy_offset_km']} km)"
+ (f" (thesis {info['legacy_il_xl'][0]}/{info['legacy_il_xl'][1]}, offset {info['legacy_offset_km']} km)"
if "legacy_il_xl" in info else "")
+ f", {info['n_anchors_in_window']} anchor trong cửa sổ, "
+ f"phủ PHIE (calibrated) {coverage.get('calibrated/PHIE', float('nan')):.0%}")
+ f", {info['n_anchors_in_window']} anchors in window, "
+ f"PHIE coverage (calibrated) {coverage.get('calibrated/PHIE', float('nan')):.0%}")
out = outputs_dir()
np.savez_compressed(out / "f3_wells.npz", **arrays)

View File

@@ -1,8 +1,8 @@
"""QC các nguồn TD so với marker TD (bản nháp hình F2 và bảng mục 1.2b–c).
"""QC of the TD sources against the TD markers (draft of figure F2 and the tables in §1.2b–c).
python scripts/02_td_qc.py
Đầu ra: outputs/figures/td_drift.png, outputs/td_qc.csv
Outputs: outputs/figures/td_drift.png, outputs/td_qc.csv
"""
from __future__ import annotations
@@ -20,7 +20,7 @@ from ml_porosity.paths import outputs_dir
WINDOW_MS = (600.0, 1100.0)
SOURCES = {
"legacy": "Tích phân DT (luận văn)",
"legacy": "Integrated DT (thesis)",
"wlt": "OpendTect .wlt",
"dt_model": "DT_model",
}
@@ -50,13 +50,13 @@ def main() -> None:
})
ax.axvline(0, color="k", lw=0.8)
ax.axhspan(*WINDOW_MS, color="#f0c040", alpha=0.15, lw=0)
ax.set_title(f"{name} ({int(inwin.sum())} anchor trong cửa sổ)", fontsize=10)
ax.set_xlabel("TWT nguồn − TWT marker (ms)")
ax.set_title(f"{name} ({int(inwin.sum())} anchors in window)", fontsize=10)
ax.set_xlabel("source TWT − marker TWT (ms)")
ax.grid(alpha=0.3)
axes[0].set_ylabel("TWT marker (ms)")
axes[0].set_ylim(1300, 400)
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=3, fontsize=9)
fig.suptitle("Lệch của các nguồn TD so với marker TD; dải vàng: cửa sổ 600–1100 ms", fontsize=11)
fig.suptitle("Offset of the TD sources from the TD markers; yellow band: 600–1100 ms window", fontsize=11)
out = outputs_dir()
(out / "figures").mkdir(exist_ok=True)

View File

@@ -1,10 +1,10 @@
"""Huấn luyện CNN–GRU v2 với loss gốc trên bộ dữ liệu từ 01_build_wells.py (B2).
"""Train CNN–GRU v2 with the original loss on the dataset from 01_build_wells.py (B2).
python scripts/03_train.py --config configs/b2_smoke.yaml [--epochs N] [--seed S]
So với `test 2/train_open_patch_v2.py`: vị trí giếng đúng, TDR chọn được, giếng validation
tách khỏi giếng train, không clip nhãn, không ước lượng lag bằng tương quan seismic–PHIE,
metric tính ở thang thật. Đầu ra: outputs/runs/<tên config>_s<seed>/.
Differences from `test 2/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well
separate from the train wells, no label clipping, no lag estimated from seismic–PHIE correlation,
metrics computed on the true scale. Outputs: outputs/runs/<config name>_s<seed>/.
"""
from __future__ import annotations
@@ -34,7 +34,7 @@ def load_split(D, wells: list[str], tdr: str, label: str):
X = np.stack([zscore_rows(D[f"{w}/seismic_patch"].astype(np.float64)) for w in wells])
Y = np.stack([D[f"{w}/{tdr}/{label}"] for w in wells])
if not np.all(np.isfinite(Y)):
raise ValueError(f"nhãn {tdr}/{label} có NaN trong cửa sổ ở {wells}; cần chọn cửa sổ khác")
raise ValueError(f"label {tdr}/{label} contains NaN in the window at {wells}; choose a different window")
return X, Y
@@ -52,7 +52,7 @@ def main() -> None:
test, val, train = cfg["test_well"], cfg["val_well"], cfg["train_wells"]
if test in train or val in train or test == val:
raise ValueError("giếng train, validation và test phải tách rời")
raise ValueError("train, validation and test wells must be disjoint")
torch.manual_seed(cfg["seed"])
np.random.seed(cfg["seed"])
@@ -62,7 +62,7 @@ def main() -> None:
Xtr, Ytr = load_split(D, train, cfg["tdr"], cfg["label"])
Xva, Yva = load_split(D, [val], cfg["tdr"], cfg["label"])
Xte, Yte = load_split(D, [test], cfg["tdr"], cfg["label"])
mu, sd = float(Ytr.mean()), float(Ytr.std() + 1e-8) # chỉ dùng thống kê train
mu, sd = float(Ytr.mean()), float(Ytr.std() + 1e-8) # train statistics only
def T(a):
return torch.tensor(a, dtype=torch.float32, device=device)
@@ -82,7 +82,7 @@ def main() -> None:
model.train()
opt.zero_grad()
pred = model(xtr)
if ep <= 50: # nhiễu nhỏ những epoch đầu như luận văn
if ep <= 50: # small noise in the first epochs, as in the thesis
pred = pred + 0.01 * torch.randn_like(pred)
loss = loss_fn(pred, ytr)
loss.backward()
@@ -105,7 +105,7 @@ def main() -> None:
yp = model(T(Xte)).cpu().numpy()[0, 0] * sd + mu
yt = Yte[0]
m = point_metrics(yt, yp)
m_const = point_metrics(yt, np.full_like(yt, mu)) # dự đoán bằng trung bình train
m_const = point_metrics(yt, np.full_like(yt, mu)) # prediction = train mean
result = {"config": cfg, "device": device, "best_epoch": best_ep, "best_val_loss": best,
"train_seconds": round(time.time() - t_start, 1),
@@ -113,7 +113,7 @@ def main() -> None:
(run_dir / "metrics.json").write_text(json.dumps(result, indent=1, ensure_ascii=False))
np.savez_compressed(run_dir / "pred_test.npz", times_ms=D[f"{test}/times_ms"], y_true=yt, y_pred=yp)
print(f"[test {test}] RMSE {m['rmse']:.4f} PCC {m['pcc']:.3f} R² {m['r2']:.2f} "
f"(hằng số: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
f"(constant: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
if __name__ == "__main__":

View File

@@ -1,13 +1,13 @@
"""Wavelet, synthetic seismogram 4 giếng và misregistration còn lại sau tie (P1, cổng G-A).
"""Wavelets, synthetic seismograms for the 4 wells, and residual misregistration after the tie (P1, gate G-A).
python scripts/04_wavelet_tie.py
Với mỗi giếng và mỗi TDR: synthetic = wavelet ∗ r(AI theo TDR), so với trace seismic tại giếng.
Báo cáo tương quan với pha chung ở shift 0, tie tốt nhất theo từng giếng (pha hằng + bulk shift)
và lệch cục bộ còn lại sau tie tốt nhất (cửa sổ trượt 120 ms, chỉ tính cửa sổ có r > 0.5).
Phép đo dùng log của cả 4 giếng nên chỉ là QC/audit, không dùng cho huấn luyện.
For each well and each TDR: synthetic = wavelet ∗ r(AI under the TDR), compared with the seismic trace at the well.
Reports the correlation with a common phase at zero shift, the best per-well tie (constant phase + bulk shift),
and the residual local shift after the best tie (120 ms sliding window, only windows with r > 0.5 counted).
The measurement uses the logs of all 4 wells, so it is QC/audit only and is not used for training.
Đầu ra: outputs/tie_qc.csv, outputs/tie_local_shifts.csv, outputs/figures/ties.png,
Outputs: outputs/tie_qc.csv, outputs/tie_local_shifts.csv, outputs/figures/ties.png,
outputs/figures/wavelets.png, outputs/wavelets.npz
"""
@@ -27,7 +27,7 @@ from ml_porosity.paths import outputs_dir
DT = 4.0
TDRS = ["calibrated", "wlt", "anchors", "legacy"]
F_DOM_HZ = 50.0 # tần số trội trung bình đo ở plan mục 2.3 (49–60 Hz)
F_DOM_HZ = 50.0 # mean dominant frequency measured in plan §2.3 (49–60 Hz)
def main() -> None:
@@ -39,18 +39,18 @@ def main() -> None:
def refl(w, tdr):
return reflectivity_from_ai(np.nan_to_num(D[f"{w}/{tdr}/AI"], nan=np.nanmean(D[f"{w}/{tdr}/AI"])))
# Wavelet thống kê (chỉ seismic) và wavelet LS từ 4 giếng với tie calibrated.
# Statistical wavelet (seismic only) and LS wavelet from the 4 wells with the calibrated tie.
w_stat = statistical_wavelet(np.stack([seis[w][main_m] for w in F3_WELLS]), DT)
w_ls = estimate_wavelet_ls([refl(w, "calibrated")[main_m] for w in F3_WELLS],
[seis[w][main_m] for w in F3_WELLS], DT)
# Pha hằng chung cho wavelet thống kê: cực đại tương quan trung bình (calibrated, shift 0).
# Common constant phase for the statistical wavelet: maximizes the mean correlation (calibrated, zero shift).
phases = np.arange(-180, 180, 5)
score = [np.mean([ncc(convolve_same(refl(w, "calibrated"), rotate_phase(w_stat, p))[main_m], seis[w][main_m])
for w in F3_WELLS]) for p in phases]
phase = float(phases[int(np.argmax(score))])
w_use = rotate_phase(w_stat, phase)
print(f"Pha hằng tốt nhất của wavelet thống kê: {phase:+.0f}°, r trung bình {max(score):.3f}")
print(f"Best constant phase of the statistical wavelet: {phase:+.0f}°, mean r {max(score):.3f}")
rows, lrows = [], []
fig, axes = plt.subplots(1, 2 * len(F3_WELLS), figsize=(16, 8), sharey=True,
@@ -63,7 +63,7 @@ def main() -> None:
for tdr in TDRS:
r_w = refl(w, tdr)
r0 = ncc(convolve_same(r_w, w_use)[main_m], s[main_m])
# Tie tốt nhất theo từng giếng: pha hằng và bulk shift tìm đồng thời (lưới 10° × 0.5 ms).
# Best per-well tie: constant phase and bulk shift searched jointly (10° × 0.5 ms grid).
best = (-np.inf, 0.0, 0.0)
for p in range(-180, 180, 10):
syn_p = convolve_same(r_w, rotate_phase(w_stat, p))
@@ -73,7 +73,7 @@ def main() -> None:
best = (rr, float(p), float(sh))
r_best, p_best, sh_best = best
syn = shift_signal(convolve_same(r_w, rotate_phase(w_stat, p_best)), sh_best, DT)
# Lệch còn lại sau tie tốt nhất: lệch cục bộ của synthetic đã dịch bulk và xoay pha.
# Residual shift after the best tie: local shift of the bulk-shifted, phase-rotated synthetic.
c, ls, lr = local_shifts(syn, s, DT, win_ms=120, hop_ms=20, max_ms=24)
tc = t[c]
inwin = (tc >= t[main_m][0] + 60) & (tc <= t[main_m][-1] - 60)
@@ -83,8 +83,8 @@ def main() -> None:
"local_n": int(good.sum()), "local_n_total": int(inwin.sum()),
"local_rms_ms": round(float(np.sqrt(np.mean(ls[good] ** 2))), 1) if good.any() else np.nan,
"local_range_ms": round(float(np.ptp(ls[good])), 1) if good.any() else np.nan})
# Ngưỡng nhiễu của phép đo: synthetic + nhiễu băng hạn chế (nhiễu trắng ∗ wavelet) sao cho
# tương quan toàn cục bằng r_best_tie; lệch thật = 0 nên RMS đo được là sai số của phép đo.
# Noise floor of the measurement: synthetic + band-limited noise (white noise ∗ wavelet) such that
# the global correlation equals r_best_tie; the true shift is 0, so the measured RMS is the measurement error.
rng = np.random.default_rng(0)
floor = []
for _ in range(20):
@@ -107,7 +107,7 @@ def main() -> None:
ax_sh.axvline(0, color="k", lw=0.7)
ax_sh.axvspan(-1000 / F_DOM_HZ / 8, 1000 / F_DOM_HZ / 8, color="#f0c040", alpha=0.3, lw=0)
ax_sh.set_xlim(-26, 26)
ax_sh.set_xlabel("lệch cục bộ (ms)", fontsize=8)
ax_sh.set_xlabel("local shift (ms)", fontsize=8)
for a in (ax_tr, ax_sh):
a.axhspan(t[main_m][0], t[main_m][-1], color="#eee", zorder=-1, lw=0)
axes[0].set_ylim(t[-1], t[0])
@@ -115,16 +115,16 @@ def main() -> None:
h1, l1 = axes[0].get_legend_handles_labels()
h2, l2 = axes[1].get_legend_handles_labels()
fig.legend(h1 + h2, l1 + l2, loc="outside lower center", ncol=7, fontsize=9)
fig.suptitle("Synthetic (tie tốt nhất từng giếng) vs seismic; "
"cột hẹp: lệch cục bộ còn lại, dải vàng ±T/8 ở 50 Hz", fontsize=11)
fig.suptitle("Synthetic (best per-well tie) vs seismic; "
"narrow column: residual local shift, yellow band ±T/8 at 50 Hz", fontsize=11)
out = outputs_dir()
(out / "figures").mkdir(exist_ok=True)
fig.savefig(out / "figures" / "ties.png", dpi=130)
fw, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
tw = (np.arange(len(w_stat)) - len(w_stat) // 2) * DT
ax.plot(tw, w_use / np.abs(w_use).max(), label=f"thống kê, pha {phase:+.0f}°")
ax.plot(tw, w_ls / np.abs(w_ls).max(), label="LS từ 4 giếng (calibrated)")
ax.plot(tw, w_use / np.abs(w_use).max(), label=f"statistical, phase {phase:+.0f}°")
ax.plot(tw, w_ls / np.abs(w_ls).max(), label="LS from 4 wells (calibrated)")
ax.set_xlabel("ms")
ax.legend()
ax.grid(alpha=0.3)
@@ -135,9 +135,9 @@ def main() -> None:
df.to_csv(out / "tie_qc.csv", index=False)
pd.DataFrame(lrows).to_csv(out / "tie_local_shifts.csv", index=False)
print(df.to_string(index=False))
print(f"T/8 ở {F_DOM_HZ:.0f} Hz = {1000 / F_DOM_HZ / 8:.1f} ms")
print(f"T/8 at {F_DOM_HZ:.0f} Hz = {1000 / F_DOM_HZ / 8:.1f} ms")
# Đối chiếu thời gian marker với horizon tại giếng (mốc thời gian SEG-Y, XM delay 4 ms).
# Compare marker times with horizons at the wells (SEG-Y time datum, XM delay 4 ms).
names = {"FS8": "FS8", "FS7": "FS7", "Truncation": "Truncation 1", "FS6": "FS6", "MFS4": "MFS4"}
from ml_porosity.data.las_io import load_well
hrows = []
@@ -155,7 +155,7 @@ def main() -> None:
hd = pd.DataFrame(hrows)
hd.to_csv(out / "marker_vs_horizon.csv", index=False)
print(hd.to_string(index=False))
print(f"horizon − marker: trung vị {hd.diff_ms.median():+.1f} ms, |Δ| trung vị {hd.diff_ms.abs().median():.1f} ms")
print(f"horizon − marker: median {hd.diff_ms.median():+.1f} ms, median |Δ| {hd.diff_ms.abs().median():.1f} ms")
if __name__ == "__main__":

View File

@@ -1,10 +1,10 @@
"""LOWO cho các baseline P1 theo configs/protocol.yaml (B0a, B0b, B1, B2, B3a, B3b).
"""LOWO for the P1 baselines per configs/protocol.yaml (B0a, B0b, B1, B2, B3a, B3b).
python scripts/05_lowo.py [--workers 12] [--device cuda] [--only B2,B3a]
Từ chối chạy nếu SHA-256 của protocol.yaml khác configs/protocol.sha256.
Đầu ra: outputs/p1/results.csv (mỗi dòng: method, label, test_well, seed, reference, metric),
outputs/p1/preds.npz (μ, σ cho từng method/label/giếng/seed), outputs/p1/selection.csv.
Refuses to run if the SHA-256 of protocol.yaml differs from configs/protocol.sha256.
Outputs: outputs/p1/results.csv (one row per method, label, test_well, seed, reference, metric),
outputs/p1/preds.npz (μ, σ per method/label/well/seed), outputs/p1/selection.csv.
"""
from __future__ import annotations
@@ -30,7 +30,7 @@ def check_protocol() -> dict:
expected = (REPO_ROOT / "configs" / "protocol.sha256").read_text().split()[0]
actual = hashlib.sha256(PROTO.read_bytes()).hexdigest()
if actual != expected:
raise SystemExit(f"protocol.yaml đã đổi sau khi khoá ({actual[:12]} ≠ {expected[:12]}); tạo phiên bản mới và khoá lại")
raise SystemExit(f"protocol.yaml changed after locking ({actual[:12]} ≠ {expected[:12]}); create a new version and lock it again")
return yaml.safe_load(PROTO.read_text()) | {"sha256": actual}
@@ -44,7 +44,7 @@ class Data:
self.D = {k: D[k] for k in D.files}
def X(self, w):
"""Patch z-score theo kênh trên cửa sổ chính, shape (C, L)."""
"""Per-channel z-scored patch over the main window, shape (C, L)."""
p = self.D[f"{w}/seismic_patch"][:, self.m].astype(np.float64)
return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8)
@@ -92,11 +92,11 @@ def run_classical(d: Data, label: str, test: str, seeds: list[int]):
def ytrain(ws):
return np.concatenate([d.y(w, "calibrated", label) for w in ws])
# B0a: trend tuyến tính theo TWT
# B0a: linear trend in TWT
lr = LinearRegression().fit(np.tile(tt, len(train))[:, None], ytrain(train))
out.append(("B0a", -1, lr.predict(tt[:, None]), None))
# B0b: attribute từ trace trung bình của patch (z-score), tính trên cửa sổ mở rộng
# B0b: attributes from the patch mean trace (z-scored), computed on the extended window
def feats(w):
p = d.ext(w, "seismic_patch").astype(float)
p = (p - p[:, d.m].mean(1, keepdims=True)) / (p[:, d.m].std(1, keepdims=True) + 1e-8)
@@ -178,7 +178,7 @@ def run_cnn(job):
Y = np.stack([d.y(w, tdr_train, label) for w in ws])
return X, Y
# vòng inner: chọn epoch
# inner loop: epoch selection
curves = []
for v in train:
tr2 = [w for w in train if w != v]
@@ -187,7 +187,7 @@ def run_cnn(job):
Xv, Yv = XY([v])
_, c = train_cnn(Xa, (Ya - mu_) / sd_, cfg, kind, seed, cfg["max_epochs"], device,
Xv, (Yv - mu_) / sd_, cfg["eval_every"])
curves.append([m * sd_**2 for _, m in c]) # MSE theo đơn vị nhãn gốc
curves.append([m * sd_**2 for _, m in c]) # MSE in original label units
eps = [e for e, _ in c]
best_ep = int(eps[int(np.argmin(np.mean(curves, axis=0)))])
@@ -235,7 +235,7 @@ def main() -> None:
sel += s
for method, seed, mu, sigma in out:
record(method, label, test, seed, mu, sigma)
print(f"B0a/B0b/B1 xong sau {time.time() - t0:.0f} s")
print(f"B0a/B0b/B1 done after {time.time() - t0:.0f} s")
cnn = [m for m in ("B2", "B3a", "B3b") if not only or m in only]
jobs = [(m, lab, w, s, args.device, proto) for m in cnn for lab in labels for w in d.wells for s in seeds]
@@ -253,7 +253,7 @@ def main() -> None:
pd.DataFrame(rows).assign(protocol_sha256=proto["sha256"][:12]).to_csv(out_dir / f"results_{tag}.csv", index=False)
pd.DataFrame(sel).to_csv(out_dir / f"selection_{tag}.csv", index=False)
np.savez_compressed(out_dir / f"preds_{tag}.npz", **preds)
print(f"-> {out_dir} ({len(rows)} dòng, {time.time() - t0:.0f} s)")
print(f"-> {out_dir} ({len(rows)} rows, {time.time() - t0:.0f} s)")
if __name__ == "__main__":

View File

@@ -1,8 +1,8 @@
"""Tổng hợp kết quả LOWO P1: bảng theo giếng và macro, độ nhạy tham chiếu, calibration B3, cổng G-A.
"""Summarize the P1 LOWO results: per-well and macro tables, reference sensitivity, B3 calibration, gate G-A.
python scripts/06_summarize_p1.py
Đầu ra: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
Outputs: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
"""
from __future__ import annotations
@@ -43,7 +43,7 @@ def per_well(res, label, ref):
def macro(res, label, ref):
mean, _, r = per_well(res, label, ref)
# macro theo giếng cho từng seed rồi lấy mean ± sd theo seed (phương pháp tất định có sd = 0)
# macro over wells for each seed, then mean ± sd over seeds (deterministic methods have sd = 0)
cols = ["rmse", "pcc", "r2", "band_pcc", "skill"]
by_seed = r.groupby(["method", "seed"])[cols].mean()
out = by_seed.groupby("method").agg(["mean", "std"]).fillna(0.0)
@@ -68,16 +68,16 @@ def main() -> None:
key = f"{label}/{ref}"
summary[key] = {m: {c: [round(mt.loc[m, (c, "mean")], 3), round(mt.loc[m, (c, "std")], 3)]
for c in ("rmse", "pcc", "r2", "band_pcc", "skill")} for m in mt.index}
lines.append(f"\n### Macro 4 giếng: nhãn {label}, tham chiếu {ref}\n")
lines.append("| Phương pháp | RMSE (p.u.) | PCC | R² | PCC băng seismic | Skill vs B0a |")
lines.append(f"\n### Macro over 4 wells: label {label}, reference {ref}\n")
lines.append("| Method | RMSE (p.u.) | PCC | R² | Seismic-band PCC | Skill vs B0a |")
lines.append("| --- | --- | --- | --- | --- | --- |")
for m in mt.index:
lines.append("| " + " | ".join([m] + [fmt(mt.loc[m, (c, "mean")], mt.loc[m, (c, "std")])
for c in ("rmse", "pcc", "r2", "band_pcc", "skill")]) + " |")
mean, sd, _ = per_well(res, lab1, "calibrated")
lines.append(f"\n### Theo giếng: nhãn {lab1}, tham chiếu calibrated (RMSE p.u. / PCC / PCC băng)\n")
lines.append("| Phương pháp | " + " | ".join(wells) + " |")
lines.append(f"\n### Per well: label {lab1}, calibrated reference (RMSE p.u. / PCC / band PCC)\n")
lines.append("| Method | " + " | ".join(wells) + " |")
lines.append("| --- |" + " --- |" * len(wells))
summary["per_well"] = {}
for m in ORDER:
@@ -95,7 +95,7 @@ def main() -> None:
if len(cal):
cc = ["nll", "crps", "coverage_50", "coverage_80", "coverage_90", "coverage_95", "mean_sigma"]
cm = cal.groupby(["method", "seed"])[cc].mean().groupby("method").agg(["mean", "std"])
lines.append(f"\n### Calibration B3 (nhãn {lab1}, macro)\n")
lines.append(f"\n### B3 calibration (label {lab1}, macro)\n")
lines.append("| | " + " | ".join(cc) + " |")
lines.append("| --- |" + " --- |" * len(cc))
summary["calibration"] = {}
@@ -103,7 +103,7 @@ def main() -> None:
lines.append(f"| {m} | " + " | ".join(fmt(cm.loc[m, (c, 'mean')], cm.loc[m, (c, 'std')]) for c in cc) + " |")
summary["calibration"][m] = {c: round(cm.loc[m, (c, "mean")], 3) for c in cc}
# G-A: B3a so với B3b
# G-A: B3a vs B3b
mt = macro(res, lab1, "calibrated")
if {"B3a", "B3b"} <= set(mt.index):
ra, rb = mt.loc["B3a", ("rmse", "mean")], mt.loc["B3b", ("rmse", "mean")]
@@ -113,9 +113,9 @@ def main() -> None:
summary["G-A"] = {"B3a_vs_B3b_rmse_pct": round(d_rmse, 1), "B3a_minus_B3b_pcc": round(pa - pb, 3),
"B3a_approx_B3b": bool(equal)}
lines.append(f"\n**G-A:** RMSE B3a − B3b = {d_rmse:+.1f}%, PCC B3a − B3b = {pa - pb:+.3f} → "
f"{'B3a ≈ B3b' if equal else 'B3a khác B3b'} theo ngưỡng protocol (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
f"{'B3a ≈ B3b' if equal else 'B3a differs from B3b'} under the protocol thresholds (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
# QC nhãn trong cửa sổ (D-1)
# Label QC within the window (D-1)
m_ = D[f"{wells[0]}/main_mask"].astype(bool)
lq = {}
for w in wells:
@@ -123,8 +123,8 @@ def main() -> None:
lq[w] = {"r2": round(float(np.corrcoef(a, b)[0, 1] ** 2), 4), "max_abs_diff_pu": round(float(np.max(np.abs(a - b)) * 100), 2),
"std_pu": round(float(np.std(b) * 100), 2)}
summary["label_qc"] = lq
lines.append("\n### QC nhãn trong 600–1100 ms (PHIE so với PHIE_DT, calibrated)\n")
lines.append("| Giếng | R² | max |Δ| (p.u.) | std PHIE_DT (p.u.) |\n| --- | --- | --- | --- |")
lines.append("\n### Label QC in 600–1100 ms (PHIE vs PHIE_DT, calibrated)\n")
lines.append("| Well | R² | max |Δ| (p.u.) | std PHIE_DT (p.u.) |\n| --- | --- | --- | --- |")
for w, v in lq.items():
lines.append(f"| {w} | {v['r2']} | {v['max_abs_diff_pu']} | {v['std_pu']} |")
@@ -133,20 +133,20 @@ def main() -> None:
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
print("\n".join(lines))
# Hình: dự đoán tại 4 giếng (nhãn chính)
# Figure: predictions at the 4 wells (primary label)
t = D[f"{wells[0]}/times_ms"][m_]
fig, axes = plt.subplots(1, 4, figsize=(14, 7), sharey=True, constrained_layout=True)
style = {"B0a": ("#8a93a3", "--"), "B0b-ridge": ("#2a9d8f", "-"), "B1": ("#8a5cc2", "-"),
"B2": ("#c47a00", "-"), "B3b": ("#1f5fbf", "-")}
for ax, w in zip(axes, wells):
ax.plot(100 * D[f"{w}/calibrated/{lab1}"][m_], t, "k", lw=1.6, label="tham chiếu (calibrated)")
ax.plot(100 * D[f"{w}/wlt/{lab1}"][m_], t, color="k", lw=0.8, ls=":", label="tham chiếu (.wlt)")
ax.plot(100 * D[f"{w}/calibrated/{lab1}"][m_], t, "k", lw=1.6, label="reference (calibrated)")
ax.plot(100 * D[f"{w}/wlt/{lab1}"][m_], t, color="k", lw=0.8, ls=":", label="reference (.wlt)")
for meth, (c, ls) in style.items():
ks = [k for k in preds if k.startswith(f"{lab1}/{w}/{meth}/") and k.endswith("/mu")]
if not ks:
continue
mu = 100 * np.mean([preds[k] for k in ks], axis=0)
ax.plot(mu, t, color=c, ls=ls, lw=1.1, label=meth + (" (TB 5 seed)" if len(ks) > 1 else ""))
ax.plot(mu, t, color=c, ls=ls, lw=1.1, label=meth + (" (mean of 5 seeds)" if len(ks) > 1 else ""))
if meth == "B3b":
sig = 100 * np.mean([preds[k.replace("/mu", "/sigma")] for k in ks], axis=0)
ax.fill_betweenx(t, mu - 1.645 * sig, mu + 1.645 * sig, color=c, alpha=0.12, lw=0, label="B3b 90%")
@@ -156,7 +156,7 @@ def main() -> None:
axes[0].set_ylim(t[-1], t[0])
axes[0].set_ylabel("TWT (ms)")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=8, fontsize=8.5)
fig.suptitle(f"LOWO P1, nhãn {lab1}: dự đoán tại giếng test", fontsize=11)
fig.suptitle(f"LOWO P1, label {lab1}: predictions at the test wells", fontsize=11)
fig.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130)

View File

@@ -1,11 +1,11 @@
"""QC dữ liệu minh giải Volve (Geophysical_Interpretations) trước khi có cube.
"""QC of the Volve interpretation data (Geophysical_Interpretations) before the cube is available.
python scripts/07_volve_interp_qc.py
Kiểm tra: lưới các horizon, số anchor TWT của well picks tại 10 giếng D3 (9 giếng PHIF và F-15 A), độ lệch pick − horizon
tại toạ độ pick, độ lệch pick − checkshot (F-11 T2, F-15 A), ROI theo IL/XL của lưới ST10010; nếu đã có cube:
toạ độ header so với lưới horizon, và lag của cực trị biên độ trung bình dọc mỗi horizon (≈ 0 nếu trục thời gian đúng).
Đầu ra: outputs/volve/{horizons,anchors,pick_vs_horizon,pick_vs_checkshot,horizon_lag}.csv, summary.json
Checks: horizon grids, number of TWT anchors from the well picks at the 10 D3 wells (9 PHIF wells and F-15 A), pick − horizon
offset at the pick coordinates, pick − checkshot offset (F-11 T2, F-15 A), ROI in IL/XL of the ST10010 grid; if the cube is present:
header coordinates vs the horizon grid, and the lag of the mean-amplitude extremum along each horizon (≈ 0 if the time axis is correct).
Outputs: outputs/volve/{horizons,anchors,pick_vs_horizon,pick_vs_checkshot,horizon_lag}.csv, summary.json
"""
from __future__ import annotations
@@ -28,7 +28,7 @@ def main() -> None:
hdir = root / cfg["horizons_twt"]
summary = {}
# lưới horizon
# horizon grids
rows, hors = [], {}
for f in sorted(hdir.parent.rglob("*.dat")):
h = read_horizon(f)
@@ -46,7 +46,7 @@ def main() -> None:
summary["grid"] = {"x_coef": geom.x_coef, "y_coef": geom.y_coef, "bin_m": geom.bin_spacing(),
"max_affine_residual_m_all_horizons": float(H.affine_res_m.max())}
# anchor TWT tại giếng chính
# TWT anchors at the main wells
P = read_well_picks(root / cfg["picks"])
P["il"], P["xl"] = geom.xy_to_bin(P.x, P.y)
ok = (P.twt_ms.notna() & ~P.qlf.isin(cfg["anchor_exclude_qlf"])
@@ -60,12 +60,12 @@ def main() -> None:
"n_faulted": int((a.qlf == "FP").sum())}
summary["anchors"] = per_well
# TWT nông: cùng MD, khác nhánh khoan
# shallow TWT: same MD, different well branches
sh = P[P.surface.isin(["Utsira Fm. Top", "HORDALAND GP. Top"]) & P.twt_ms.notna()]
summary["shallow_twt_spread_ms"] = {s: [float(g.twt_ms.min()), float(g.twt_ms.max())]
for s, g in sh.groupby("surface")}
# pick − horizon tại toạ độ pick
# pick − horizon at the pick coordinates
C = []
for s, f in cfg["pick_horizons"].items():
h = hors[f"{hdir.name}/{f}"]
@@ -81,7 +81,7 @@ def main() -> None:
s: {"n": len(g), "median": round(float(g.d_ms.median()), 1), "mad": round(float((g.d_ms - g.d_ms.median()).abs().median()), 1),
"max_abs": round(float(g.d_ms.abs().max()), 1)} for s, g in clean.groupby("surface")}
# pick − checkshot (theo TVDSS để không phụ thuộc mốc MD)
# pick − checkshot (in TVDSS, independent of the MD datum)
D = []
for w, files in cfg["checkshots"].items():
p = P[(P.well == w) & P.twt_ms.notna()]
@@ -98,14 +98,14 @@ def main() -> None:
summary["pick_minus_checkshot_ms"] = {f"{w} {k}": [round(float(g.d_tvd_ms.min()), 1), round(float(g.d_tvd_ms.max()), 1)]
for (w, k), g in deep.groupby(["well", "checkshot"])}
# ROI theo IL/XL
# ROI in IL/XL
x0, x1, y0, y1 = cfg["roi_xy"]
il, xl = geom.xy_to_bin([x0, x1, x1, x0], [y0, y0, y1, y1])
summary["roi_ilxl"] = {"il": [int(np.floor(il.min())), int(np.ceil(il.max()))],
"xl": [int(np.floor(xl.min())), int(np.ceil(xl.max()))]}
summary["anchor_twt_range_ms"] = [float(A.twt_ms.min()), float(A.twt_ms.max())]
# cube: header so với lưới horizon; horizon pick trên peak/trough nên cực trị phải ở lag ≈ 0
# cube: header vs horizon grid; horizons are picked on peaks/troughs, so the extremum should be at lag ≈ 0
cube_path = root / cfg["cube"]
if cube_path.exists():
(i0, i1), (j0, j1) = summary["roi_ilxl"]["il"], summary["roi_ilxl"]["xl"]

View File

@@ -1,15 +1,15 @@
"""Kiểm tra D-1 (định nghĩa nhãn F3) bằng density đo của NLOG.
"""Check D-1 (the F3 label definition) against the measured NLOG density.
python scripts/08_d1_label_check.py
PHIE của bộ demo ở F03-2, F03-4, F06-1 là hàm tuyến tính của DT (plan mục 1.2d). Script so porosity theo density đo
φ_D = (2650 − RHOB)/1600 (RHOB từ LAS NLOG) với nhãn sonic PHIE_DT = −0.2018 + 0.0011·DT trong cửa sổ 600–1100 ms,
trên lưới 4 ms như nhãn huấn luyện:
- F02-1, F03-4: giếng demo, TD calibrated từ outputs/f3_wells.npz; độ sâu NLOG căn theo tương quan DT;
- F03-03, F03-06: giếng NLOG ngoài bộ demo, TD theo file TZ (giả định MD − APD ≈ TVDSS ở đoạn nông);
- F03-2, F06-1: RHOB đo của NLOG bắt đầu ở 1641 và 1836 m MD, dưới cửa sổ, nên không có φ_D.
Kèm chỉ số chất lượng trong cửa sổ: |DRHO| và caliper (từ composite LAS; chưa có bit size nên chưa kết luận washout).
Đầu ra: outputs/d1/label_check.csv, summary.json
The demo PHIE at F03-2, F03-4, F06-1 is a linear function of DT (plan §1.2d). This script compares the porosity from
measured density φ_D = (2650 − RHOB)/1600 (RHOB from the NLOG LAS) with the sonic label PHIE_DT = −0.2018 + 0.0011·DT
in the 600–1100 ms window, on the same 4 ms grid as the training labels:
- F02-1, F03-4: demo wells, calibrated TD from outputs/f3_wells.npz; NLOG depth aligned by DT correlation;
- F03-03, F03-06: NLOG wells outside the demo set, TD from the TZ file (assuming MD − APD ≈ TVDSS in the shallow section);
- F03-2, F06-1: measured NLOG RHOB starts at 1641 and 1836 m MD, below the window, so no φ_D.
Also reports in-window quality indicators: |DRHO| and caliper (from the composite LAS; no bit size yet, so no washout conclusion).
Outputs: outputs/d1/label_check.csv, summary.json
"""
from __future__ import annotations
@@ -26,7 +26,7 @@ from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import TDR
from ml_porosity.paths import REPO_ROOT, nlog_root, outputs_dir
# (LAS composite có RHOB/DRHO, LAS composite có CALI theo feet, file TZ); tên gốc NLOG có tiền tố giếng
# (composite LAS with RHOB/DRHO, composite LAS with CALI in feet, TZ file); original NLOG names carry a well prefix
NLOG_FILES = {
"F02-1": ("F02-01__8727_f0201_1976_comp.las", "F02-01-S1__F021_Composite-TOTAL~LF1.las", None),
"F03-4": ("F03-04__7035_f0304_1976_comp.las", "F03-04__F034_Composite-TOTAL~LF1.las", None),
@@ -35,7 +35,7 @@ NLOG_FILES = {
}
WINDOW_MS = (600.0, 1100.0)
T = np.arange(WINDOW_MS[0], WINDOW_MS[1] + 0.1, 4.0)
SOS_BAND = signal.butter(4, 6 / 125, "high", output="sos") # băng seismic > 6 Hz (plan mục 2.3) trên lưới 4 ms
SOS_BAND = signal.butter(4, 6 / 125, "high", output="sos") # seismic band > 6 Hz (plan §2.3) on the 4 ms grid
def phi_d(rhob):
@@ -47,7 +47,7 @@ def phi_dt(dt):
def read_nlog(comp: str, composite: str) -> tuple[pd.DataFrame, float]:
"""MD (m, từ LMF) → DT µs/m, RHOB và DRHO kg/m³, CALI inch; kèm APD (m trên MSL)."""
"""MD (m, from LMF) → DT µs/m, RHOB and DRHO kg/m³, CALI inch; plus APD (m above MSL)."""
raw = nlog_root() / "raw"
las = lasio.read(raw / comp)
df = las.df().sort_index()
@@ -71,7 +71,7 @@ def corr(a: np.ndarray, b: np.ndarray) -> float:
def compare(a: np.ndarray, b: np.ndarray) -> dict:
"""a, b theo p.u. trên lưới T; r băng tính trên đoạn liên tục chung."""
"""a, b in p.u. on grid T; band r computed over the common contiguous segment."""
ok = np.isfinite(a) & np.isfinite(b)
r = corr(a, b)
i = np.flatnonzero(ok)
@@ -99,7 +99,7 @@ def main() -> None:
for w, (comp, composite, tz) in NLOG_FILES.items():
df, apd = read_nlog(comp, composite)
info = {"apd_m": apd}
if tz is None: # giếng demo: căn độ sâu NLOG theo DT, so với LAS demo
if tz is None: # demo well: align NLOG depth by DT against the demo LAS
W = load_well(w)
tdr = TDR(Z[f"{w}/tdr/calibrated/md"], Z[f"{w}/tdr/calibrated/twt_ms"], "calibrated")
d0, d1 = tdr.depth_at(WINDOW_MS)
@@ -116,7 +116,7 @@ def main() -> None:
"rms": round(float(np.sqrt(np.mean(d ** 2))), 1)}
labels = {"PHIE_DT": log_to_time(W.md, phi_dt(W.curve("DT")), tdr, T),
"PHIE": log_to_time(W.md, W.curve("PHIE"), tdr, T)}
else: # giếng NLOG mới: chỉ có DT của NLOG
else: # new NLOG well: only the NLOG DT is available
tdr = read_tz(tz, apd)
d0, d1 = tdr.depth_at(WINDOW_MS)
md, shift = df.index.to_numpy(), 0.0
@@ -134,7 +134,7 @@ def main() -> None:
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
print(R.to_string(index=False))
print(json.dumps(summary["wells"], indent=1, ensure_ascii=False))
print("ghi:", out.relative_to(REPO_ROOT) if out.is_relative_to(REPO_ROOT) else out)
print("written:", out.relative_to(REPO_ROOT) if out.is_relative_to(REPO_ROOT) else out)
if __name__ == "__main__":

View File

@@ -0,0 +1,103 @@
"""Fit the GP warp prior (plan §4.1) on the F3 anchors and run a leave-one-anchor-out check (§5.4).
python scripts/09_fit_warp_prior_f3.py
τ = integrated DT passing through the first TD marker (as for the base of the calibrated TDR); anchors = TD markers
in the extended 400–1300 ms window; d_k = t_k − τ_k. Type-II ML fit on all 4 wells (used to calibrate the D2 drift)
and on each LOWO fold (3 train wells). Outputs: outputs/p2/warp_prior_f3.json, figures/p2_f3_drift.png.
"""
from __future__ import annotations
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import yaml
from ml_porosity.data.las_io import load_well
from ml_porosity.data.tdr import sonic_tdr
from ml_porosity.paths import REPO_ROOT, outputs_dir
from ml_porosity.registration.warp_prior import (WarpGrid, WarpHyper, fit_hyper, linear_posterior,
loao_zscores)
TAU_RANGE = (300.0, 1400.0)
def f3_anchor_wells(cfg: dict) -> list[dict]:
e0, e1 = cfg["ext_window_ms"]
out = []
for name in cfg["wells"]:
w = load_well(name)
cs = w.checkshot
base = sonic_tdr(w.md, w.curve("DT"), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
tk = cs.twt_ms.to_numpy()
tau = base.time_at(cs.md.to_numpy())
m = (tk >= e0) & (tk <= e1)
out.append({"name": name, "grid": WarpGrid(*TAU_RANGE, 4.0), "tau_k": tau[m], "d_k": tk[m] - tau[m]})
return out
def z_summary(z: np.ndarray) -> dict:
return {"n": int(len(z)), "mean_z2": round(float(np.mean(z**2)), 3),
"coverage_90": round(float(np.mean(np.abs(z) < 1.6449)), 3),
"max_abs_z": round(float(np.max(np.abs(z))), 2)}
def main() -> None:
cfg = yaml.safe_load(open(REPO_ROOT / "configs" / "d1_f3.yaml"))
wells = f3_anchor_wells(cfg)
# The "tau" and "note" strings below are written verbatim into warp_prior_f3.json, whose SHA-256 is locked in
# protocol_p2/protocol_p3; they are deliberately left untranslated so that a re-run reproduces the locked file.
res = {"tau": "sonic_tdr qua marker TD đầu tiên", "anchors_window_ms": cfg["ext_window_ms"],
"tau_range_ms": TAU_RANGE, "n_anchors": {w["name"]: int(len(w["tau_k"])) for w in wells}, "fits": {}}
for kern in ["matern32", "se"]:
h, info = fit_hyper(wells, WarpHyper(kernel=kern), n_starts=8)
z = loao_zscores(wells, h)
folds = {}
for i, w in enumerate(wells):
hi, _ = fit_hyper([v for j, v in enumerate(wells) if j != i], WarpHyper(kernel=kern), n_starts=6)
zi = loao_zscores([w], hi)[0]
folds[w["name"]] = {"hyper": hi.as_dict(), "loao_test_well": z_summary(zi)}
res["fits"][kern] = {"hyper": h.as_dict(), "log_marginal": round(info["log_marginal"], 3),
"at_bound": info["at_bound"],
"loao": z_summary(np.concatenate(z)) | {"per_well": {w["name"]: z_summary(zw) for w, zw in zip(wells, z)}},
"lowo_folds": folds}
print(kern, h, "logML", round(info["log_marginal"], 2), "LOAO", z_summary(np.concatenate(z)))
best = max(res["fits"], key=lambda k: res["fits"][k]["log_marginal"])
res["selected_kernel"] = "matern32"
res["note"] = ("Chọn Matérn-3/2 (chốt trước trong configs/d2_synth.yaml) — log-marginal hai kernel chênh "
f"{abs(res['fits']['matern32']['log_marginal'] - res['fits']['se']['log_marginal']):.2f} "
f"(cao hơn: {best}).")
out = outputs_dir() / "p2"
out.mkdir(parents=True, exist_ok=True)
(out / "warp_prior_f3.json").write_text(json.dumps(res, indent=2, ensure_ascii=False))
h = WarpHyper(**res["fits"]["matern32"]["hyper"])
fig, axes = plt.subplots(1, 4, figsize=(14, 4), sharey=True)
for ax, w in zip(axes, wells):
grid = w["grid"]
mu, S = linear_posterior(grid, h, w["tau_k"], w["d_k"])
A = grid.anchor_operator(grid.tau)
m = A @ mu
sd = np.sqrt(np.einsum("ij,jk,ik->i", A, S, A))
ax.fill_between(grid.tau, m - 2 * sd, m + 2 * sd, color="C0", alpha=0.25, label="±2σ posterior")
ax.plot(grid.tau, m, "C0", label="posterior mean")
ax.plot(w["tau_k"], w["d_k"], "ko", ms=3, label="anchor")
ax.set_title(w["name"])
ax.set_xlabel("τ sonic (ms)")
ax.set_xlim(380, 1320)
axes[0].set_ylabel("t − τ (ms)")
axes[0].legend(fontsize=7)
fig.suptitle(f"F3 drift under the GP prior (Matérn-3/2, σ_g={h.sigma_g:.3f}, ℓ={h.ell_ms:.0f} ms, σ_a={h.sigma_a_ms:.2f} ms)")
fig.tight_layout()
(outputs_dir() / "figures").mkdir(exist_ok=True)
fig.savefig(outputs_dir() / "figures" / "p2_f3_drift.png", dpi=130)
print("→", out / "warp_prior_f3.json")
if __name__ == "__main__":
main()

177
scripts/10_build_d2.py Normal file
View File

@@ -0,0 +1,177 @@
"""QC of D2 against F3 (plan §5.1, §5.5): label, anchor and drift statistics; figure of one example well.
Labels on the extended 400–1300 ms window, 4 ms grid. F3: calibrated PHIE_DT of the 4 wells (linear in DT).
D2: anti-aliased φ of the central trace in true time, all wells (8 test + 16 pool) of the main realizations.
Per-well statistics: residual std after a linear trend, std of the > 6 Hz band, τ_c (rml.effective_lambda), PSD slope
over 10–80 Hz (log–log, Hann periodogram of the residual). Drift: max − min range of t − τ at the anchors in the extended
window (F3: TD markers as in scripts/09; D2: true warp at unit boundaries, no pick noise) and anchors per well.
python scripts/10_build_d2.py
→ outputs/d2/qc.json, outputs/figures/p2_d2_qc.png
"""
from __future__ import annotations
import importlib.util
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import yaml
from scipy import signal
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.eval import figstyle as fs
from ml_porosity.eval.metrics import split_bands
from ml_porosity.losses.rml import effective_lambda
from ml_porosity.paths import REPO_ROOT, outputs_dir
from ml_porosity.registration.labels import antialias
from ml_porosity.registration.warp_prior import WarpHyper
STATS = {"resid_std": "residual std (linear trend)", "band_std": "std of > 6 Hz band",
"tau_c": "τ_c (samples)", "psd_slope": "PSD slope 10–80 Hz"}
def label_stats(y: np.ndarray, dt: float = 4.0, f_c: float = 6.0) -> dict:
k = np.arange(len(y))
res = y - np.polyval(np.polyfit(k, y, 1), k)
f, P = signal.periodogram(res, fs=1000.0 / dt, window="hann")
m = (f >= 10) & (f <= 80)
return {"resid_std": float(res.std()), "band_std": float(split_bands(y, f_c, dt)[1].std()),
"tau_c": effective_lambda([y], f_c, dt)[1], "psd_slope": float(np.polyfit(np.log10(f[m]), np.log10(P[m]), 1)[0])}
def summary(v) -> dict:
v = np.asarray(v, dtype=float)
return {"n": int(len(v)), "median": float(np.median(v)), "q05": float(np.quantile(v, 0.05)),
"q95": float(np.quantile(v, 0.95)), "min": float(v.min()), "max": float(v.max())}
def f3_side() -> dict:
spec = importlib.util.spec_from_file_location("fit09", REPO_ROOT / "scripts" / "09_fit_warp_prior_f3.py")
fit09 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fit09)
cfg = yaml.safe_load(open(REPO_ROOT / "configs" / "d1_f3.yaml"))
z = np.load(outputs_dir() / "f3_wells.npz", allow_pickle=True)
out = {}
for w in fit09.f3_anchor_wells(cfg):
y = z[f"{w['name']}/calibrated/PHIE_DT"].astype(float)
out[w["name"]] = label_stats(y) | {"n_anchors": int(len(w["tau_k"])),
"drift_range_ms": float(np.ptp(w["d_k"]))}
return out
def main() -> None:
P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2.yaml"))
cfg = yaml.safe_load(open(REPO_ROOT / P["inputs"]["d2_config"]["path"]))
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
drift = WarpHyper(**prior["hyper"])
cs = [c for c in P["grid"]["drift_factors"] if c > 0]
sa, f = cfg["anchors"]["sigma_a_ms"], cfg["fine_dt_ms"]
d2 = {k: [] for k in STATS} | {"n_anchors": [], **{f"drift_range_ms_c{c:g}": [] for c in cs},
**{f"max_abs_g_c{c:g}": [] for c in cs}}
example = None
for rid in P["grid"]["realizations"]:
R = D2Realization(cfg, rid, hg, drift, wav)
win = (R.grid.tau >= R.t_ext[0]) & (R.grid.tau <= R.t_ext[-1])
for w in R.wells:
y = np.interp(R.t_ext, R.t_fine, antialias(w.phi_t, f, R.dt))
for k, v in label_stats(y).items():
d2[k].append(v)
for c in cs:
o = R.observe(w, c, P["grid"]["snr_db"], sa)
d2[f"drift_range_ms_c{c:g}"].append(float(np.ptp(w.boundaries_t - o["tau_k"])))
d2[f"max_abs_g_c{c:g}"].append(float(np.abs(o["g"][win]).max()))
d2["n_anchors"].append(len(w.boundaries_t))
if example is None:
w = R.pool[0]
example = {"R": R, "w": w, "obs": {c: R.observe(w, c, P["grid"]["snr_db"], sa) for c in cs}}
print(f"realization {rid}: {len(R.wells)} wells", flush=True)
f3 = f3_side()
qc = {"window_ms": cfg["ext_window_ms"], "realizations": P["grid"]["realizations"],
"d2": {k: summary(v) for k, v in d2.items()},
"f3": f3, "f3_range": {k: [min(w[k] for w in f3.values()), max(w[k] for w in f3.values())]
for k in list(STATS) + ["n_anchors", "drift_range_ms"]}}
out = outputs_dir() / "d2"
out.mkdir(parents=True, exist_ok=True)
(out / "qc.json").write_text(json.dumps(qc, indent=1, ensure_ascii=False))
for k in list(STATS) + ["n_anchors"]:
s = qc["d2"][k]
print(f"{k:12s} D2 median {s['median']:.4g} [5–95%: {s['q05']:.4g}, {s['q95']:.4g}] F3 {qc['f3_range'][k]}")
for c in cs:
s = qc["d2"][f"drift_range_ms_c{c:g}"]
print(f"drift c={c:g}: D2 median {s['median']:.1f} ms [{s['q05']:.1f}, {s['q95']:.1f}] F3 {qc['f3_range']['drift_range_ms']}")
plot(example, d2, f3, cs, outputs_dir() / "figures" / "p2_d2_qc.png")
def plot(ex, d2, f3, cs, path) -> None:
fs.apply()
R, w, obs = ex["R"], ex["w"], ex["obs"]
fig = plt.figure(figsize=(12, 6.4))
gs = fig.add_gridspec(2, 4, height_ratios=[1.15, 1], hspace=0.55, wspace=0.35)
ax = fig.add_subplot(gs[0, :2])
m = (R.t_fine >= R.t_ext[0]) & (R.t_fine <= R.t_ext[-1])
o1 = obs[1.0] if 1.0 in obs else obs[cs[0]]
ax.plot(R.t_fine[m], 100 * w.phi_t[m], color=fs.INK, lw=1.0, label="true φ in t")
sel = (o1["tau_fine"] >= R.t_ext[0]) & (o1["tau_fine"] <= R.t_ext[-1])
ax.plot(o1["tau_fine"][sel], 100 * o1["phi_log"][sel], color=fs.ORANGE, lw=1.0, label="log placed at τ (no tie, c = 1)")
ax.axvspan(*R.t_main[[0, -1]], color=fs.GRID, alpha=0.5, lw=0)
ax.text(R.t_main[0] + 5, ax.get_ylim()[1], "main window", va="top", fontsize=8, color=fs.INK2)
ax.set(xlabel="time (ms)", ylabel="φ (p.u.)", title=f"(a) Example well {w.name}, realization {R.rid}")
ax.legend(loc="lower left")
ax = fig.add_subplot(gs[0, 2])
gt = R.grid.tau
for c, col in zip(cs, fs.ORDINAL_BLUE):
o = obs[c]
dd = np.interp(gt, o["tau_fine"], o["t_of_tau_true"]) - gt
k = (gt >= R.t_ext[0]) & (gt <= R.t_ext[-1])
ax.plot(gt[k], dd[k], color=col, lw=1.5)
ax.annotate(f"c = {c:g}", (gt[k][-1], dd[k][-1]), xytext=(3, 0), textcoords="offset points",
va="center", fontsize=8, color=fs.INK2)
ax.plot(o1["tau_k"], o1["t_k"] - o1["tau_k"], "o", ms=4, mfc=fs.SURFACE, mec=fs.INK, mew=1.0, label="anchor (c = 1, σ_a = 7 ms)")
ax.set(xlabel="τ sonic (ms)", ylabel="t − τ (ms)", title="(b) True warp and anchors")
ax.set_xlim(R.t_ext[0], R.t_ext[-1] + 120)
lo, hi = ax.get_ylim()
ax.set_ylim(lo, hi + 0.25 * (hi - lo))
ax.legend(loc="upper left")
ax = fig.add_subplot(gs[0, 3])
mid = w.seis_clean.shape[0] // 2
ax.plot(R.t_ext, o1["seis"][mid], color=fs.INK, lw=0.9, label="SNR 10 dB")
ax.plot(R.t_ext, w.seis_clean[mid], color=fs.BLUE, lw=0.9, label="noise-free")
ax.set(xlabel="time (ms)", title="(c) Central seismic trace", yticks=[])
ax.legend(loc="lower left")
rng = np.random.default_rng(0)
for j, (k, lab) in enumerate(STATS.items()):
ax = fig.add_subplot(gs[1, j])
v = np.asarray(d2[k])
x = rng.uniform(-0.18, 0.18, len(v))
ax.plot(x, v, "o", ms=2.5, color=fs.BLUE, alpha=0.35, mec="none")
q = np.quantile(v, [0.05, 0.5, 0.95])
ax.plot([0.28, 0.28], q[[0, 2]], color=fs.INK2, lw=1.2)
ax.plot([0.22, 0.34], [q[1], q[1]], color=fs.INK2, lw=1.2)
fv = [f3[n][k] for n in f3]
ax.plot(np.full(len(fv), 1.0), fv, "D", ms=6, color=fs.ORANGE, mec=fs.SURFACE, mew=1.0)
ax.set_xticks([0, 1], [f"D2 ({len(v)} wells)", "F3 (4 wells)"])
ax.set_xlim(-0.5, 1.5)
ax.grid(axis="x", visible=False)
ax.set_title(f"({'defg'[j]}) {lab}")
fig.suptitle("D2 vs F3: labels over 400–1300 ms (F3: PHIE_DT, linear in DT); D2 shown with median and 5–95% range",
x=0.06, ha="left", fontsize=10, color=fs.INK2)
path.parent.mkdir(exist_ok=True)
fig.savefig(path, dpi=140, bbox_inches="tight")
print("→", path)
if __name__ == "__main__":
main()

217
scripts/11_run_d2.py Normal file
View File

@@ -0,0 +1,217 @@
"""P2 on D2: register the train wells, train every method, score on the 8 test wells (plan §5–6).
python scripts/11_run_d2.py --dev # dev realizations 900, 901: select step budgets → outputs/p2/dev/budgets.json
python scripts/11_run_d2.py --main # main grid (protocol_p2 must match the locked hash) → outputs/p2/main/
Each job is one cell (realization, c, N); seeds run sequentially within a job. Each cell's results are written
immediately to outputs/p2/<mode>/cells/, so a re-run skips completed cells. Cell (c = 1, N = 4) of the main grid also
includes the anchor-free variants M1-na/M2-na (H4).
"""
from __future__ import annotations
import argparse
import dataclasses
import hashlib
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
PROTO = REPO_ROOT / "configs" / "protocol_p2.yaml"
METHODS = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M1", "M2"]
def load_protocol(check: bool) -> dict:
actual = hashlib.sha256(PROTO.read_bytes()).hexdigest()
if check:
f = REPO_ROOT / "configs" / "protocol_p2.sha256"
expected = f.read_text().split()[0] if f.exists() else "(not locked)"
if actual != expected:
raise SystemExit(f"protocol_p2.yaml is not locked or changed after locking ({actual[:12]} ≠ {expected[:12]})")
proto = yaml.safe_load(PROTO.read_text())
for v in proto["inputs"].values():
h = hashlib.sha256((REPO_ROOT / v["path"]).read_bytes()).hexdigest()
if h != v["sha256"]:
raise SystemExit(f"{v['path']} differs from the version recorded in protocol_p2 ({h[:12]} ≠ {v['sha256'][:12]})")
return proto | {"sha256": actual}
def reg_settings(P: dict) -> dict:
r = P["registration"]
keys = ("S", "g_max", "sigma_a_ms", "sigma_b_ms", "kernel", "hyperprior", "hyper_starts", "ess_min_frac",
"shift_K", "wavelet_ms")
return {k: r[k] for k in keys}
def method_specs(out: dict, P: dict, names: list[str]) -> dict:
"""Training spec (bank_train.train_predict) for each method, with normalized labels."""
m0, s0 = out["norm"]
nb = lambda a: (a - m0) / s0
B, lam = out["banks"], out["lam"]
N = len(out["wells"])
T = P["training"]
specs = {}
for m in names:
base = m.removesuffix("-na")
if base in ("Oracle", "B3a", "B3b", "B3c", "B3d"):
specs[m] = {"kind": "bank", "Y": nb(B[base]), "logpi": np.zeros((N, 1)), "lam": lam}
elif base in ("B4a", "B4b"):
K = B["B4"].shape[1]
specs[m] = {"kind": "bank", "Y": nb(B["B4"]), "logpi": np.full((N, K), -np.log(K)),
"lam": None if base == "B4a" else lam}
elif base == "B4c":
specs[m] = {"kind": "softdtw", "Y": nb(B["B3b"])} | T["softdtw"]
elif base == "B4d":
specs[m] = {"kind": "dilate", "Y": nb(B["B3b"])} | T["dilate"]
elif base in ("M1", "M2"):
specs[m] = {"kind": "bank", "Y": nb(B[base]), "logpi": out["logpi"][base], "lam": lam}
elif base == "MSE0": # H1 with σ_δ = 0: Oracle labels, windowed MSE
from ml_porosity.models.bank_train import WIN, window_starts_fixed
Y = nb(B["Oracle"][:, 0])
specs[m] = {"kind": "mse_win", "Ywin": np.stack([Y[:, j: j + WIN] for j in window_starts_fixed(Y.shape[1])], 1)}
else:
raise ValueError(m)
return specs
def evaluate(yt: np.ndarray, mu: np.ndarray, sigma: np.ndarray, f_c: float) -> list[dict]:
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
return [point_metrics(a, m) | band_metrics(a, m, f_c) | gaussian_metrics(a, m, s) for a, m, s in zip(yt, mu, sigma)]
def run_cell(job) -> tuple[list[dict], list[dict], float]:
rid, c, N, seeds, budgets, P, device, out_dir = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.models.bank_train import train_predict, zscore_patch
from ml_porosity.registration.pipeline import register
from ml_porosity.registration.warp_prior import WarpHyper
t0 = time.time()
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
drift = WarpHyper(**prior["hyper"])
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, drift, wav)
G = P["grid"]
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, c, G["snr_db"], sa, G["anchor_density"]) for w in R.pool[:N]]
test = [R.observe(w, c, G["snr_db"], sa) for w in R.test]
X = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test])
yt = 100 * np.stack([o["y_true"] for o in test])
reg = reg_settings(P)
h4 = "M1-na" in budgets
tcfg = P["training"]["model"] | P["training"]["optimizer"]
rows, diag, preds = [], [], {}
key = dict(rid=rid, c=c, n_train=N)
for seed in seeds:
out = register(R, obs, reg, seed)
specs = method_specs(out, P, [m for m in budgets if not m.endswith("-na")])
info = key | {"seed": seed, "phase": out["phase"], "lam": out["lam"], "tau_c": out["tau_c"]} | \
{f"hyper_{k}": v for k, v in out["hyper"].items() if k != "kernel"} | \
{"hyper_log_marginal": out["hyper_info"]["log_marginal"], "hyper_at_bound": ",".join(out["hyper_info"]["at_bound"])}
diag += [info | {"variant": "anchor"} | d for d in out["diag"]]
if h4:
na = register(R, obs, reg, seed, prior=dataclasses.replace(drift.scaled(c), sigma_b_ms=reg["sigma_b_ms"]))
specs |= method_specs(na, P, ["M1-na", "M2-na"])
diag += [key | {"seed": seed, "phase": na["phase"], "lam": na["lam"], "tau_c": na["tau_c"], "variant": "no_anchor"} | d
for d in na["diag"]]
m0, s0 = out["norm"]
for m, sp in specs.items():
bud = budgets[m] if isinstance(budgets[m], list) else [budgets[m]]
for b, (mu, sg) in train_predict(X, Xte, sp, tcfg, seed, bud, device).items():
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
for w, r in zip(R.test, evaluate(yt, mu_p, sg_p, P["metrics"]["bands"]["f_c_hz"])):
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": w.name} | r)
preds[f"{m}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32)
preds[f"{m}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32)
tag = f"r{rid}_c{c:g}_n{N}"
np.savez_compressed(out_dir / f"{tag}.npz", y_true=yt.astype(np.float32), test_wells=np.array([w.name for w in R.test]), **preds)
pd.DataFrame(diag).to_csv(out_dir / f"{tag}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{tag}.csv", index=False) # written last: marks the cell as done
return rows, diag, time.time() - t0
def select_budgets(df: pd.DataFrame) -> dict:
"""For each method: the budget with the smallest mean total RMSE (macro over test wells → mean over rid × N × seed)."""
run = df.groupby(["method", "budget", "rid", "n_train", "seed"])["rmse"].mean().groupby(["method", "budget"]).mean()
return {m: int(run.loc[m].idxmin()) for m in run.index.get_level_values(0).unique()}
def main() -> None:
ap = argparse.ArgumentParser()
mode = ap.add_mutually_exclusive_group(required=True)
mode.add_argument("--dev", action="store_true")
mode.add_argument("--main", action="store_true")
ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--only-cells", default="", help="cell filter, e.g. 'c=1,n=4' (testing only)")
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "3"}.items():
os.environ.setdefault(k, v)
P = load_protocol(check=args.main)
G = P["grid"]
if args.dev:
tag, rids, cs, ns, seeds = "dev", G["dev_realizations"], [G["realistic_drift"]], [4, 16], [0, 1]
budgets = {m: P["training"]["budget_candidates"] for m in METHODS + ["MSE0"]}
else:
tag, rids, cs, ns, seeds = "main", G["realizations"], G["drift_factors"], G["n_train"], G["seeds"]
budgets = dict(P["training"]["budgets"])
missing = [m for m in METHODS if m not in budgets]
if missing:
raise SystemExit(f"missing budgets for {missing} in protocol_p2")
out_dir = outputs_dir() / "p2" / tag
(out_dir / "cells").mkdir(parents=True, exist_ok=True)
flt = dict(kv.split("=") for kv in args.only_cells.split(",") if kv)
jobs = []
for rid in rids:
for c in cs:
for N in ns:
if ("c" in flt and float(flt["c"]) != c) or ("n" in flt and int(flt["n"]) != N):
continue
if (out_dir / "cells" / f"r{rid}_c{c:g}_n{N}.csv").exists():
continue
b = {m: budgets[m] for m in METHODS + (["MSE0"] if args.dev else [])}
if args.main and c == G["realistic_drift"] and N == 4:
b |= {"M1-na": budgets["M1"], "M2-na": budgets["M2"]}
jobs.append((rid, c, N, seeds, b, P, args.device, out_dir / "cells"))
jobs.sort(key=lambda j: -j[2]) # cells with large N run first for load balancing
print(f"{len(jobs)} cells to run, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(run_cell, j): j[:3] for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
_, _, dt = f.result()
print(f"[{i}/{len(jobs)}] cell r{futs[f][0]} c={futs[f][1]:g} N={futs[f][2]} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
cells = sorted((out_dir / "cells").glob("r*_n*.csv"))
df = pd.concat([pd.read_csv(f) for f in cells if not f.name.endswith("_diag.csv")], ignore_index=True)
dg = pd.concat([pd.read_csv(f) for f in cells if f.name.endswith("_diag.csv")], ignore_index=True)
df.assign(protocol_sha256=P["sha256"][:12]).to_csv(out_dir / "results.csv", index=False)
dg.to_csv(out_dir / "diag.csv", index=False)
if args.dev:
sel = select_budgets(df)
(out_dir / "budgets.json").write_text(json.dumps(sel, indent=1))
print("selected budgets:", sel)
print(f"-> {out_dir} ({len(df)} rows, {time.time() - t0:.0f} s)")
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

154
scripts/12_h1_blur.py Normal file
View File

@@ -0,0 +1,154 @@
"""H1 (Prop 1): MSE training on labels with a random time shift δ ~ N(0, σ²) yields blurred predictions with
transfer function exp(−2π²σ²f²).
c = 0, N = 16, Oracle labels. Each (well, sub-window) receives one shift δ = σ·z held fixed throughout training
(z shared across all σ: common random numbers); MSE loss on μ. The transfer function is estimated on the test wells:
Ĥ(f) = Σ Re[Y* P_σ] / Σ Re[Y* P_0] (pooled over test wells, realizations, seeds; Hann taper)
and r(σ) = geometric mean of Ĥ/theory over the frequencies used (protocol_p2, hypotheses.H1).
python scripts/12_h1_blur.py [--workers 6] [--device cuda:1]
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
_spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
run_d2 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(run_d2)
NFFT = 256
def run_job(job) -> dict:
rid, seed, sigmas, budget, P, device = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.models.bank_train import WIN, train_predict, window_starts_fixed, zscore_patch
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.pipeline import label_norm
from ml_porosity.registration.warp_prior import WarpHyper
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
G, H = P["grid"], P["hypotheses"]["H1"]
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, 0.0, G["snr_db"], sa) for w in R.pool[:16]]
test = [R.observe(w, 0.0, G["snr_db"], sa) for w in R.test]
X = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test])
m0, s0 = label_norm(R, obs)
starts = window_starts_fixed(len(R.t_main))
tw = R.t_main[starts[:, None] + np.arange(WIN)] # (J, WIN)
z = np.random.default_rng([rid, seed, 7]).standard_normal((len(obs), len(starts)))
f = cfg["fine_dt_ms"]
tcfg = P["training"]["model"] | P["training"]["optimizer"]
preds = {}
for sg in sigmas:
Yw = np.stack([labels_for_warps(R.tau_fine, antialias(o["phi_log"], f, R.dt), o["t_of_tau_true"],
(tw + sg * z[i][:, None]).ravel()).reshape(tw.shape)
for i, o in enumerate(obs)])
mu = train_predict(X, Xte, {"kind": "mse_win", "Ywin": (Yw - m0) / s0}, tcfg, seed, [budget], device)[budget][0]
preds[sg] = 100 * (mu * s0 + m0)
return {"rid": rid, "seed": seed, "y_true": 100 * np.stack([o["y_true"] for o in test]),
"wells": [w.name for w in R.test], "preds": preds}
def cross_spectrum(Y: np.ndarray, Pr: np.ndarray) -> np.ndarray:
w = np.hanning(Y.shape[1])
Fy = np.fft.rfft((Y - Y.mean(1, keepdims=True)) * w, NFFT)
Fp = np.fft.rfft((Pr - Pr.mean(1, keepdims=True)) * w, NFFT)
return np.real(np.conj(Fy) * Fp).sum(0)
def transfer(S: dict, f: np.ndarray, f_c: float) -> dict:
"""S[σ]: accumulated cross-spectrum Re[Y* P_σ]. Returns Ĥ, the theoretical curve, r(σ) and the number of frequencies used."""
band = f >= f_c
out = {"H_hat": {}, "theory": {}, "r": {}, "n_freq": {}}
for sg, Ss in S.items():
th = np.exp(-2 * np.pi**2 * (sg / 1000.0) ** 2 * f**2)
use = band & (th >= 0.1) & (S[0.0] >= 0.1 * S[0.0][band].max())
Hh = Ss / S[0.0]
out["H_hat"][sg], out["theory"][sg] = Hh.tolist(), th.tolist()
out["r"][sg] = float(np.exp(np.mean(np.log(np.clip(Hh[use] / th[use], 1e-3, None))))) if use.any() else float("nan")
out["n_freq"][sg] = int(use.sum())
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
H = P["hypotheses"]["H1"]
sigmas = [float(s) for s in H["sigma_ms"]]
budget = int(P["training"]["budgets"]["MSE0"])
rids, seeds = P["grid"]["realizations"], P["grid"]["seeds"]
out_dir = outputs_dir() / "p2" / "h1"
out_dir.mkdir(parents=True, exist_ok=True)
jobs = [(rid, s, sigmas, budget, P, args.device) for rid in rids for s in seeds]
t0 = time.time()
results = []
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
for i, fut in enumerate(as_completed([ex.submit(run_job, j) for j in jobs]), 1):
results.append(fut.result())
print(f"[{i}/{len(jobs)}] {time.time() - t0:.0f} s", flush=True)
results.sort(key=lambda r: (r["rid"], r["seed"]))
from ml_porosity.eval.metrics import band_metrics, point_metrics
f_c = P["metrics"]["bands"]["f_c_hz"]
rows = [{"rid": r["rid"], "seed": r["seed"], "sigma_ms": sg, "test_well": w} | point_metrics(y, p) | band_metrics(y, p, f_c)
for r in results for sg in sigmas for w, y, p in zip(r["wells"], r["y_true"], r["preds"][sg])]
pd.DataFrame(rows).assign(protocol_sha256=P["sha256"][:12]).to_csv(out_dir / "results.csv", index=False)
np.savez_compressed(out_dir / "preds.npz", **{f"r{r['rid']}/s{r['seed']}/sigma{sg:g}": r["preds"][sg] for r in results for sg in sigmas},
**{f"r{r['rid']}/y_true": r["y_true"] for r in results})
f = np.fft.rfftfreq(NFFT, 4.0 / 1000.0)
cs = {r["rid"]: {sg: 0.0 for sg in sigmas} for r in results} # cross-spectrum accumulated per realization
for r in results:
for sg in sigmas:
cs[r["rid"]][sg] = cs[r["rid"]][sg] + cross_spectrum(r["y_true"], r["preds"][sg])
tf = {"f_hz": f.tolist()} | transfer({sg: sum(cs[i][sg] for i in cs) for sg in sigmas}, f, f_c)
rng = np.random.default_rng(0)
boot = {sg: [] for sg in sigmas}
for _ in range(args.n_boot): # bootstrap over realizations
pick = rng.choice(list(cs), len(cs))
for sg, v in transfer({sg: sum(cs[i][sg] for i in pick) for sg in sigmas}, f, f_c)["r"].items():
boot[sg].append(v)
tf["r_ci95"] = {sg: [float(np.nanpercentile(boot[sg], 2.5)), float(np.nanpercentile(boot[sg], 97.5))] for sg in sigmas}
lo, hi = 0.5, 2.0
tf["reject_H1"] = bool(any(not (lo <= tf["r"][sg] <= hi) for sg in sigmas if sg > 0))
tf["budget"] = budget
tf["protocol_sha256"] = P["sha256"][:12]
(out_dir / "h1.json").write_text(json.dumps(tf, indent=1))
print("r(σ):", {sg: round(v, 3) for sg, v in tf["r"].items()}, "CI:", tf["r_ci95"], "reject H1:", tf["reject_H1"])
print(f"-> {out_dir} ({time.time() - t0:.0f} s)")
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

494
scripts/13_summarize_p2.py Normal file
View File

@@ -0,0 +1,494 @@
"""P2 summary per protocol_p2: gate G-B, v1 phase map, H1, H3, H4 and warp diagnostics.
Reads each cell in outputs/p2/<mode>/cells, so it can run before the grid is finished (the gate then records
complete = false). A run is (realization, c, N, method, seed); a run's metric is the mean over the 8 test wells at
the method's locked budget. 95% CIs are bootstrapped over realizations (each realization averaged over seeds); the
cell's best competitor is held fixed during bootstrapping.
python scripts/13_summarize_p2.py [--mode main|dev] [--n-boot 2000]
→ outputs/p2/summary/<mode>/: gate_gb.json, cells.csv, methods.csv, h3.csv, h3.json, h4.json, warp.csv, h1.csv, summary.md
figures outputs/figures/p2_{phase,band_lines,h3,h1}.png (dev mode: in the summary directory)
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import math
import re
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import Rectangle
from ml_porosity.eval import figstyle as fs
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
from ml_porosity.paths import REPO_ROOT, outputs_dir
METRICS = ["rmse", "pcc", "low_rmse", "band_rmse", "band_pcc", "band_std_ratio", "nll", "crps", "mean_sigma",
"coverage_50", "coverage_80", "coverage_90", "coverage_95"]
LEVELS = (50, 80, 90, 95)
# thresholds stated verbally in protocol_p2 (gates.G-B, hypotheses.H3, H4)
RATIO_MAX, DPCC_MIN, GUARD, SEED_FRAC, N_FRAC = 0.90, 0.05, 1.02, 4 / 5, 3 / 4
H3_WIDTH, H4_WARP, H4_BAND = 1.2, 1.10, 1.02
RAMP4 = ["#86b6ef", "#5598e7", "#256abf", "#104281"] # 4-step ordinal ramp (σ of H1), validated
def load_script(name: str):
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def parse_tag(stem: str) -> tuple[int, float, int]:
rid, c, n = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)", stem).groups()
return int(rid), float(c), int(n)
def ce(d):
"""Calibration error: mean |coverage − nominal| over 50/80/90/95%."""
return sum(abs(d[f"coverage_{q}"] - q / 100) for q in LEVELS) / len(LEVELS)
def boot(num: np.ndarray, den: np.ndarray | None, n_boot: int, rng) -> list[float]:
"""95% CI of mean(num)/mean(den) (den = None: of mean(num)) under resampling of realizations."""
idx = rng.integers(0, len(num), (n_boot, len(num)))
s = num[idx].mean(1) if den is None else num[idx].mean(1) / den[idx].mean(1)
return np.percentile(s, [2.5, 97.5]).tolist()
def load_runs(cell_dir, budgets: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
files = sorted(f for f in cell_dir.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv"))
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
df = df[df["budget"] == df["method"].map(lambda m: budgets[m.removesuffix("-na")])]
run = df.groupby(["rid", "c", "n_train", "method", "seed"], as_index=False)[METRICS].mean()
diag = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True)
return run, diag
# ---------------------------------------------------------------- G-B
def improves(m2: pd.DataFrame, best: pd.DataFrame) -> pd.Series:
return (m2["band_rmse"] <= RATIO_MAX * best["band_rmse"]) | (m2["band_pcc"] >= best["band_pcc"] + DPCC_MIN)
def gate_gb(run: pd.DataFrame, P: dict, n_boot: int, rng) -> tuple[pd.DataFrame, dict]:
G, grid = P["gates"]["G-B"], P["grid"]
rows = []
for (c, N), d in run.groupby(["c", "n_train"]):
mean = d.groupby("method")[["band_rmse", "band_pcc"]].mean()
comp = mean.loc[mean.index.intersection(G["competitors"]), "band_rmse"].sort_values()
best = comp.index[0]
a = d[d.method == "M2"].set_index(["rid", "seed"])[["band_rmse", "band_pcc"]]
b = d[d.method == best].set_index(["rid", "seed"])[["band_rmse", "band_pcc"]].reindex(a.index)
ok = b.notna().all(axis=1)
a, b = a[ok], b[ok]
imp = {lvl: improves(a.groupby(lvl).mean(), b.groupby(lvl).mean()) for lvl in ("seed", "rid")}
ar, br = a.groupby("rid").mean(), b.groupby("rid").mean()
n_s, n_r = len(imp["seed"]), len(imp["rid"])
rows.append({
"c": c, "n_train": N, "best": best, "runner_up": comp.index[1], "n_rid": n_r, "n_seed": n_s,
"m2_band_rmse": a["band_rmse"].mean(), "best_band_rmse": b["band_rmse"].mean(),
"ratio": a["band_rmse"].mean() / b["band_rmse"].mean(),
**dict(zip(("ratio_lo", "ratio_hi"), boot(ar["band_rmse"].to_numpy(), br["band_rmse"].to_numpy(), n_boot, rng))),
"dpcc": a["band_pcc"].mean() - b["band_pcc"].mean(),
**dict(zip(("dpcc_lo", "dpcc_hi"), boot((ar["band_pcc"] - br["band_pcc"]).to_numpy(), None, n_boot, rng))),
"seeds_improve": int(imp["seed"].sum()), "rids_improve": int(imp["rid"].sum()),
"cell_pass": bool(imp["seed"].sum() >= math.ceil(SEED_FRAC * n_s - 1e-9) and imp["rid"].sum() > n_r / 2),
"ratio_vs_B3b": a["band_rmse"].mean() / mean.loc["B3b", "band_rmse"],
})
cells = pd.DataFrame(rows)
real, zero = cells[cells.c == grid["realistic_drift"]], cells[cells.c == 0]
need = math.ceil(N_FRAC * len(grid["n_train"]) - 1e-9)
macro = zero.m2_band_rmse.mean() / zero.best_band_rmse.mean() if len(zero) else float("nan")
guard = bool(len(zero) == len(grid["n_train"]) and macro <= GUARD and (zero.ratio <= GUARD).all())
complete = bool(len(cells) == len(grid["drift_factors"]) * len(grid["n_train"])
and (cells.n_rid == len(grid["realizations"])).all() and (cells.n_seed == len(grid["seeds"])).all())
verdict = {
"complete": complete, "cells": len(cells),
"realistic_cells_pass": f"{int(real.cell_pass.sum())}/{len(real)}",
"realistic_pass": bool(real.cell_pass.sum() >= need),
"zero_drift_macro_ratio": macro, "zero_drift_ratio_per_N": {int(r.n_train): r.ratio for r in zero.itertuples()},
"zero_drift_guard": guard,
}
verdict["pass"] = verdict["realistic_pass"] and guard
return cells, verdict
# ---------------------------------------------------------------- H3, H4, warp
def h3_table(cell_dir, P: dict, budgets: dict, pairs=(("B5", "B3b"), ("M2-ens", "M2")), pattern=None) -> pd.DataFrame:
"""B5 / M2-ens: μ = mean of μ_s, σ² = mean of σ_s² + variance of μ_s over 5 seeds (from saved predictions).
pairs: (ensemble name, method); pattern: defaults to the c = 1 cells."""
f_c, c1 = P["metrics"]["bands"]["f_c_hz"], P["grid"]["realistic_drift"]
rows = []
for f in sorted(cell_dir.glob(pattern or f"r*_c{c1:g}_n*.npz")):
rid, c, N = parse_tag(f.stem)
z = np.load(f)
yt = z["y_true"].astype(float)
for name, m in pairs:
ks = sorted(k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{budgets[m]}/mu"))
if not ks:
continue
mu = np.stack([z[k] for k in ks]).astype(float)
sg = np.stack([z[k[:-2] + "sigma"] for k in ks]).astype(float)
mu_e, sg_e = mu.mean(0), np.sqrt((sg**2).mean(0) + mu.var(0))
per_well = [point_metrics(y, a) | band_metrics(y, a, f_c) | gaussian_metrics(y, a, s) for y, a, s in zip(yt, mu_e, sg_e)]
rows.append({"rid": rid, "c": c, "n_train": N, "method": name, "members": len(ks)}
| pd.DataFrame(per_well)[METRICS].mean().to_dict())
e = pd.DataFrame(rows)
return e.assign(ce=ce(e))
def h3_verdict(e: pd.DataFrame, run: pd.DataFrame, P: dict, n_boot: int, rng) -> dict:
def judge(d):
m = d.groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean()
a, b = m.loc["M2-ens"], m.loc["B5"]
width = a.mean_sigma / b.mean_sigma
return {"ce_m2ens": a.ce, "ce_b5": b.ce, "width_ratio": width, "nll_m2ens": a.nll, "nll_b5": b.nll,
"crps_m2ens": a.crps, "crps_b5": b.crps,
"reject_H3": bool(a.ce >= b.ce or (width > H3_WIDTH and a.nll >= b.nll and a.crps >= b.crps))}
out = {"pooled": judge(e), "per_N": {int(N): judge(d) for N, d in e.groupby("n_train")}}
per_rid = e.groupby(["method", "rid"])["ce"].mean()
diff = (per_rid.loc["M2-ens"] - per_rid.loc["B5"]).to_numpy()
out["pooled"] |= {"dce": float(diff.mean()), "dce_ci95": boot(diff, None, n_boot, rng)}
s = run[(run.c == P["grid"]["realistic_drift"]) & run.method.isin(["B3b", "M2"])]
out["single_model"] = s.assign(ce=ce(s)).groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean().to_dict("index")
return out
def h4(run: pd.DataFrame, diag: pd.DataFrame, n_boot: int, rng) -> dict:
d = diag[(diag.c == 1) & (diag.n_train == 4)]
if "no_anchor" not in set(d.variant):
return {"available": False}
w = d.groupby(["variant", "rid"])[["M1_warp_rmse_ms", "M2_warp_rmse_ms", "M1_warp_cov90", "M2_warp_cov90"]].mean()
r = run[(run.c == 1) & (run.n_train == 4)].groupby(["method", "rid"])[["band_rmse", "band_pcc"]].mean()
out = {"available": True}
for m in ("M1", "M2"):
wa, wn = w.loc["anchor", f"{m}_warp_rmse_ms"].to_numpy(), w.loc["no_anchor", f"{m}_warp_rmse_ms"].to_numpy()
ba, bn = r.loc[m, "band_rmse"].to_numpy(), r.loc[f"{m}-na", "band_rmse"].to_numpy()
out[m] = {"warp_rmse_anchor_ms": wa.mean(), "warp_rmse_no_anchor_ms": wn.mean(), "warp_ratio": wn.mean() / wa.mean(),
"warp_ratio_ci95": boot(wn, wa, n_boot, rng),
"warp_cov90_anchor": w.loc["anchor", f"{m}_warp_cov90"].mean(),
"warp_cov90_no_anchor": w.loc["no_anchor", f"{m}_warp_cov90"].mean(),
"band_rmse_anchor": ba.mean(), "band_rmse_no_anchor": bn.mean(), "band_ratio": bn.mean() / ba.mean(),
"band_ratio_ci95": boot(bn, ba, n_boot, rng),
"band_pcc_anchor": r.loc[m, "band_pcc"].mean(), "band_pcc_no_anchor": r.loc[f"{m}-na", "band_pcc"].mean()}
out["reject_H4"] = bool(out["M2"]["warp_ratio"] <= H4_WARP and out["M2"]["band_ratio"] <= H4_BAND)
return out
def warp_table(diag: pd.DataFrame) -> pd.DataFrame:
"""Means per (variant, c, N): per-well warp error; phase, λ, τ_c and hyperparameters per registration run."""
cols = [c for c in diag.columns if c.endswith("_warp_rmse_ms")] + \
["M1_warp_cov90", "M2_warp_cov90", "M2_warp_width90_ms", "n_anchor", "n_valid", "gamma", "ess", "ess_gamma1"]
per_well = diag.groupby(["variant", "c", "n_train"])[cols].mean()
reg = diag.drop_duplicates(["variant", "rid", "c", "n_train", "seed"])
per_reg = reg.groupby(["variant", "c", "n_train"]).agg(
phase_zero=("phase", lambda p: float(np.mean(p == 0))), phase_within15=("phase", lambda p: float(np.mean(np.abs(p) <= 15))),
lam=("lam", "mean"), tau_c=("tau_c", "mean"), m_g=("hyper_m_g", "mean"), sigma_g=("hyper_sigma_g", "mean"),
ell_ms=("hyper_ell_ms", "mean"), at_bound=("hyper_at_bound", lambda s: float(s.notna().mean())))
return per_well.join(per_reg).reset_index()
# ---------------------------------------------------------------- H1
def h1_summary(P: dict, s12) -> dict | None:
d = outputs_dir() / "p2" / "h1"
if not (d / "h1.json").exists():
return None
h = json.loads((d / "h1.json").read_text())
res = pd.read_csv(d / "results.csv")
tab = res.groupby(["rid", "seed", "sigma_ms"])[["rmse", "band_rmse", "band_pcc", "band_std_ratio"]].mean() \
.groupby("sigma_ms").mean()
# cross-spectrum rebuilt from saved predictions to recover the frequencies used (same rule as scripts/12) and to check r(σ)
z = np.load(d / "preds.npz")
f, f_c = np.array(h["f_hz"]), P["metrics"]["bands"]["f_c_hz"]
S = {}
for k in z.files:
rid, _, sg = k.split("/") if k.count("/") == 2 else (None, None, None)
if sg is not None:
S[float(sg[5:])] = S.get(float(sg[5:]), 0.0) + s12.cross_spectrum(z[f"{rid}/y_true"], z[k])
tf = s12.transfer(S, f, f_c)
assert all(abs(tf["r"][sg] - h["r"][str(sg)]) < 1e-9 for sg in S), "rebuilt r(σ) differs from h1.json"
use = {sg: (f >= f_c) & (np.array(tf["theory"][sg]) >= 0.1) & (S[0.0] >= 0.1 * S[0.0][f >= f_c].max()) for sg in S}
tab["r"] = [h["r"][str(sg)] for sg in tab.index]
tab["r_lo"], tab["r_hi"] = zip(*[h["r_ci95"][str(sg)] for sg in tab.index])
tab["n_freq"] = [h["n_freq"][str(sg)] for sg in tab.index]
return {"json": h, "table": tab, "f": f, "use": use, "H": tf["H_hat"], "theory": tf["theory"]}
# ---------------------------------------------------------------- figures
def text_on(rgba) -> str:
lum = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]
return fs.INK if lum > 0.55 else fs.SURFACE
def plot_phase(cells: pd.DataFrame, verdict: dict, P: dict, path) -> None:
fs.apply()
cs, Ns = sorted(cells.c.unique()), sorted(cells.n_train.unique())
fig, axes = plt.subplots(1, 2, figsize=(13, 1.2 + 1.25 * len(cs)), layout="constrained") # leave room for colorbar labels
panels = [("ratio", "(a) Band RMSE: M2 / best competitor", fs.diverging_norm(0.8, 1.0, 1.2), fs.DIVERGING,
"{:.3f}", [RATIO_MAX, 1.0], "ratio (< 1: M2 better; threshold 0.90)"),
("dpcc", "(b) Band PCC: M2 − best competitor", fs.diverging_norm(-0.1, 0.0, 0.1), fs.DIVERGING.reversed(),
"{:+.3f}", [0.0, DPCC_MIN], "difference (> 0: M2 better; threshold +0.05)")]
ix = cells.set_index(["c", "n_train"])
for ax, (k, title, norm, cmap, fmt, ticks, clabel) in zip(axes, panels):
Z = ix[k].unstack("n_train").reindex(index=cs, columns=Ns).to_numpy()
im = ax.imshow(Z, cmap=cmap, norm=norm, origin="lower", aspect="auto")
for i, c in enumerate(cs):
for j, N in enumerate(Ns):
if (c, N) not in ix.index:
continue
r = ix.loc[(c, N)]
col = text_on(cmap(norm(r[k])))
ax.text(j, i + 0.2, fmt.format(r[k]), ha="center", va="center", fontsize=11, color=col)
ax.text(j, i - 0.02, f"[{fmt.format(r[k + '_lo'])}, {fmt.format(r[k + '_hi'])}]", ha="center",
va="center", fontsize=7, color=col)
if k == "ratio":
ax.text(j, i - 0.22, f"vs {r.best}", ha="center", va="center", fontsize=8, color=col)
ax.text(j, i - 0.38, f"{'✓' if r.cell_pass else '✗'} {r.seeds_improve}/{r.n_seed} seed · "
f"{r.rids_improve}/{r.n_rid} rz", ha="center", va="center", fontsize=6.5, color=col)
c1 = P["grid"]["realistic_drift"]
ax.set_xticks(range(len(Ns)), [str(n) for n in Ns])
ax.set_yticks(range(len(cs)), [f"{c:g}" + ("\n(realistic)" if c == c1 else "") for c in cs])
ax.set(xlabel="number of training wells N", ylabel="drift factor c (× F3 prior)", title=title)
ax.grid(False)
if c1 in cs:
ax.add_patch(Rectangle((-0.5, cs.index(c1) - 0.5), len(Ns), 1, fill=False, ec=fs.INK, lw=1.6))
cb = fig.colorbar(im, ax=ax, shrink=0.9, extend="both", pad=0.1)
for t in ticks:
cb.ax.axhline(t, color=fs.INK, lw=1.0)
cb.set_label(clabel, color=fs.INK2)
cb.outline.set_visible(False)
v = verdict
head = (f"Gate G-B: {'PASS' if v['pass'] else 'FAIL'} — c = 1: {v['realistic_cells_pass']} cells pass (required ≥ 3/4); "
f"c = 0: macro ratio {v['zero_drift_macro_ratio']:.3f} (required ≤ 1.02 both macro and per N) → "
f"{'held' if v['zero_drift_guard'] else 'violated'}{'' if v['complete'] else ' · INCOMPLETE GRID'}")
fig.suptitle(head, x=0.02, ha="left", fontsize=10, color=fs.INK)
fig.text(0.02, -0.02, "Each cell: mean over 8 realizations × 5 seeds (8 test wells per run); [95% CI, bootstrap over realizations, "
"competitor fixed]; ✓/✗: a cell passes if M2 improves (ratio ≤ 0.90 or PCC +0.05) in ≥ 4/5 seeds and > 1/2 of realizations (rz).",
fontsize=7.5, color=fs.INK2)
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
def direct_labels(ax, items, x, gap_frac=0.08) -> None:
"""items: [(y, label)] at the right edge; spread vertically to avoid overlap, in ink colour."""
lo, hi = ax.get_ylim()
items = sorted(items)
ys = [items[0][0]]
for y, _ in items[1:]:
ys.append(max(y, ys[-1] + gap_frac * (hi - lo)))
for (y0, t), y in zip(items, ys):
ax.annotate(t, (x, y0), xytext=(x + 0.12, y), textcoords="data", fontsize=8, color=fs.INK2, va="center",
annotation_clip=False)
def plot_lines(run: pd.DataFrame, cells: pd.DataFrame, path, n_boot: int, rng) -> None:
fs.apply()
cs, Ns = sorted(run.c.unique()), sorted(run.n_train.unique())
per_rid = run.groupby(["c", "n_train", "method", "rid"])[["band_rmse", "band_pcc"]].mean()
best = cells.set_index(["c", "n_train"])["best"]
series = [("M2", fs.BLUE, "o", "-", "M2"), ("best", fs.ORANGE, "s", "-", "best competitor in cell"),
("B3b", fs.AQUA, "^", "-", "B3b (tie marker)"), ("Oracle", fs.MUTED, None, "--", "Oracle (true warp; upper bound)")]
fig, axes = plt.subplots(2, len(Ns), figsize=(2.7 * len(Ns) + 1.2, 6.0), sharey="row", squeeze=False)
for i, (k, ylab) in enumerate([("band_rmse", "band RMSE (p.u.)"), ("band_pcc", "band PCC")]):
for j, N in enumerate(Ns):
ax = axes[i, j]
ends = []
for name, col, mk, ls, lab in series:
pts = []
for c in cs:
m = best.get((c, N)) if name == "best" else name
if m is None or (c, N, m) not in per_rid.index:
continue
v = per_rid.loc[(c, N, m), k].to_numpy()
pts.append((c, v.mean(), *boot(v, None, n_boot, rng), m))
if not pts:
continue
x, y, lo, hi, who = zip(*pts)
ax.plot(x, y, color=col, marker=mk, ls=ls, ms=5, lw=1.0 if name == "Oracle" else 1.5, label=lab,
zorder=3 if name == "M2" else 2)
if name != "Oracle":
ax.vlines(x, lo, hi, color=col, lw=1.0, zorder=2)
if name == "best":
for xx, yy, ww in zip(x, y, who):
ax.annotate(ww, (xx, yy), xytext=(0, -11 if i == 0 else 7), textcoords="offset points",
ha="center", fontsize=6.5, color=fs.INK2)
ends.append((y[-1], lab.split(" (")[0] if name != "best" else "best"))
ax.axvspan(0.85, 1.15, color=fs.GRID, alpha=0.45, lw=0, zorder=0)
ax.set_xticks(cs, [f"{c:g}" for c in cs])
ax.set_xlim(min(cs) - 0.15, max(cs) + 0.15)
if i == 0:
ax.set_title(f"N = {N} training wells")
if i == 1:
ax.set_xlabel("drift factor c")
if j == 0:
ax.set_ylabel(ylab)
if j == len(Ns) - 1 and ends:
direct_labels(ax, ends, max(cs))
h, l = axes[0, 0].get_legend_handles_labels()
fig.legend(h, l, loc="upper left", ncol=4, bbox_to_anchor=(0.06, 1.02))
fig.text(0.06, -0.03, "Markers: mean over 8 realizations × 5 seeds; bars: 95% CI, bootstrap over realizations. "
"Grey band: realistic drift (c = 1). Labels at orange squares: the competitor with the lowest band RMSE in the cell.",
fontsize=7.5, color=fs.INK2)
fig.tight_layout()
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
def plot_h3(e: pd.DataFrame, path) -> None:
fs.apply()
Ns = sorted(e.n_train.unique())
fig, axes = plt.subplots(1, len(Ns), figsize=(2.6 * len(Ns) + 1.0, 3.2), sharey=True, squeeze=False)
nom = np.array(LEVELS) / 100
for ax, N in zip(axes[0], Ns):
d = e[e.n_train == N].groupby("method")[[f"coverage_{q}" for q in LEVELS] + ["ce"]].mean()
ax.plot([0.4, 1], [0.4, 1], color=fs.AXIS, lw=1.0, ls="--")
for m, col, mk in (("M2-ens", fs.BLUE, "o"), ("B5", fs.ORANGE, "s")):
if m in d.index:
ax.plot(nom, d.loc[m].iloc[:4].to_numpy(), color=col, marker=mk, ms=5, label=m)
ax.set(title=f"N = {N}", xlabel="nominal level", xlim=(0.4, 1.0), ylim=(0, 1.0))
ax.text(0.42, 0.95, "\n".join(f"CE {m}: {d.loc[m, 'ce']:.3f}" for m in ("M2-ens", "B5") if m in d.index),
va="top", fontsize=7.5, color=fs.INK2)
axes[0, 0].set_ylabel("empirical coverage")
axes[0, 0].legend(loc="lower right")
fig.suptitle("H3 (c = 1): coverage of central intervals, 5-seed ensemble; dashed: perfect calibration",
x=0.02, ha="left", fontsize=10)
fig.tight_layout()
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
def plot_h1(h1: dict, path) -> None:
fs.apply()
f, tab = h1["f"], h1["table"]
fig, (ax, bx) = plt.subplots(1, 2, figsize=(11, 3.9), gridspec_kw={"width_ratios": [1.6, 1]})
sig = [s for s in sorted(h1["use"]) if s > 0]
for s, col in zip(sig, RAMP4):
th, H, u = np.array(h1["theory"][s]), np.array(h1["H"][s]), h1["use"][s]
ax.plot(f, th, color=col, lw=1.0, ls="--")
ax.plot(f[u], H[u], color=col, lw=1.8, marker="o", ms=2.5, label=f"σ = {s:g} ms")
ax.annotate(f"σ = {s:g} ms", (f[u][-1], H[u][-1]), xytext=(5, 0), textcoords="offset points", va="center",
fontsize=8, color=fs.INK2)
ax.axvspan(0, 6, color=fs.GRID, alpha=0.6, lw=0)
ax.text(3, -0.12, "< 6 Hz\nnot used", ha="center", fontsize=7, color=fs.INK2)
ax.set(xlim=(0, 80), ylim=(-0.2, 1.3), xlabel="frequency (Hz)", ylabel="transfer function",
title="(a) Estimated Ĥ(f) (solid, frequencies used) and exp(−2π²σ²f²) (dashed)")
ax.legend(loc="upper right")
s = tab.index[tab.index > 0]
bx.axhspan(0.5, 2.0, color=fs.GRID, alpha=0.6, lw=0)
bx.axhline(1.0, color=fs.AXIS, lw=1.0)
bx.vlines(s, tab.loc[s, "r_lo"], tab.loc[s, "r_hi"], color=fs.BLUE, lw=1.5)
bx.plot(s, tab.loc[s, "r"], "o", color=fs.BLUE, ms=6)
for x, r, n in zip(s, tab.loc[s, "r"], tab.loc[s, "n_freq"]):
bx.annotate(f"{r:.2f}\n{n} freq.", (x, r), xytext=(0, 9), textcoords="offset points", ha="center",
va="bottom", fontsize=8, color=fs.INK2)
bx.set_xscale("log", base=2)
bx.set_yscale("log", base=2)
bx.set_xticks(list(s), [f"{x:g}" for x in s])
bx.set_yticks([0.25, 0.5, 1, 2, 4], ["0.25", "0.5", "1", "2", "4"])
bx.set(xlim=(3, 50), ylim=(0.25, 4), xlabel="σ_δ (ms)", ylabel="r(σ) = geometric mean of Ĥ / theory",
title="(b) r(σ), 95% CI over realizations; shaded: non-rejection region [0.5, 2]")
rej = h1["json"]["reject_H1"]
fig.suptitle(f"H1 (Prop 1, c = 0, N = 16, MSE): {'rejected' if rej else 'not rejected'}", x=0.02, ha="left", fontsize=10)
fig.tight_layout()
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
# ---------------------------------------------------------------- markdown
def md(df: pd.DataFrame, fmt: str = ".3f") -> str:
return df.to_markdown(floatfmt=fmt)
def write_md(path, P, verdict, cells, methods, h3j, h4j, warp, h1) -> None:
c1 = P["grid"]["realistic_drift"]
L = [f"# P2 summary (protocol {P['sha256'][:12]})", ""]
L += [f"## Gate G-B: {'PASS' if verdict['pass'] else 'FAIL'}" + ("" if verdict["complete"] else " (incomplete grid)"), "",
f"- c = {c1:g}: {verdict['realistic_cells_pass']} cells pass (required ≥ 3/4) → realistic_pass = {verdict['realistic_pass']}",
f"- c = 0: macro ratio {verdict['zero_drift_macro_ratio']:.4f}, per N "
f"{ {k: round(v, 4) for k, v in verdict['zero_drift_ratio_per_N'].items()} } → guard = {verdict['zero_drift_guard']}", ""]
t = cells.set_index(["c", "n_train"])[["best", "runner_up", "ratio", "ratio_lo", "ratio_hi", "dpcc", "dpcc_lo", "dpcc_hi",
"seeds_improve", "rids_improve", "cell_pass", "ratio_vs_B3b"]]
L += [md(t), ""]
for k, lab in (("band_rmse", "band RMSE (p.u.)"), ("band_pcc", "band PCC"), ("rmse", "total RMSE (p.u.)")):
piv = methods.pivot_table(index="method", columns=["c", "n_train"], values=k)
piv.columns = [f"c{c:g}/N{n}" for c, n in piv.columns]
L += [f"### {lab} by method (mean over realizations × seeds)", "", md(piv), ""]
if h3j:
rows = {"pooled": h3j["pooled"]} | {f"N = {n}": v for n, v in h3j["per_N"].items()}
L += [f"## H3: {'rejected' if h3j['pooled']['reject_H3'] else 'not rejected'} (pooled over all N at c = {c1:g})", "",
md(pd.DataFrame(rows).T.drop(columns="dce_ci95", errors="ignore")), "",
f"ΔCE (M2-ens − B5) = {h3j['pooled']['dce']:.4f}, 95% CI {np.round(h3j['pooled']['dce_ci95'], 4).tolist()}", "",
"Single model (mean over 5 individual seeds):", "", md(pd.DataFrame(h3j["single_model"]).T), ""]
if h4j.get("available"):
L += [f"## H4: {'rejected' if h4j['reject_H4'] else 'not rejected'} (c = 1, N = 4)", "",
md(pd.DataFrame({m: {k: (str(np.round(v, 3).tolist()) if isinstance(v, list) else v) for k, v in h4j[m].items()}
for m in ("M1", "M2")}).T, ".3f"), ""]
if h1 is not None:
L += [f"## H1: {'rejected' if h1['json']['reject_H1'] else 'not rejected'} (budget MSE0 = {h1['json']['budget']})", "",
md(h1["table"]), ""]
L += ["## Warp diagnostics (means over training wells; phase/λ/hyperparameters per registration run)", "",
md(warp.set_index(["variant", "c", "n_train"]).T, ".3f"), ""]
path.write_text("\n".join(L))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["main", "dev"], default="main")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
s11, s12 = load_script("11_run_d2.py"), load_script("12_h1_blur.py")
P = s11.load_protocol(check=args.mode == "main")
budgets = P["training"]["budgets"]
cell_dir = outputs_dir() / "p2" / args.mode / "cells"
out = outputs_dir() / "p2" / "summary" / args.mode
out.mkdir(parents=True, exist_ok=True)
figs = outputs_dir() / "figures" if args.mode == "main" else out
rng = np.random.default_rng(0)
run, diag = load_runs(cell_dir, budgets)
methods = run.groupby(["c", "n_train", "method"])[METRICS].mean().reset_index()
cells, verdict = gate_gb(run, P, args.n_boot, rng)
e = h3_table(cell_dir, P, budgets)
h3j = h3_verdict(e, run, P, args.n_boot, rng) if len(e) else None
h4j = h4(run, diag, args.n_boot, rng)
warp = warp_table(diag)
h1 = h1_summary(P, s12)
verdict |= {"protocol_sha256": P["sha256"][:12], "n_boot": args.n_boot}
(out / "gate_gb.json").write_text(json.dumps(verdict, indent=1, ensure_ascii=False))
cells.to_csv(out / "cells.csv", index=False)
methods.to_csv(out / "methods.csv", index=False)
e.to_csv(out / "h3.csv", index=False)
(out / "h3.json").write_text(json.dumps(h3j, indent=1, ensure_ascii=False, default=float))
(out / "h4.json").write_text(json.dumps(h4j, indent=1, ensure_ascii=False, default=float))
warp.to_csv(out / "warp.csv", index=False)
if h1 is not None:
h1["table"].to_csv(out / "h1.csv")
plot_h1(h1, figs / "p2_h1.png")
write_md(out / "summary.md", P, verdict, cells, methods, h3j, h4j, warp, h1)
plot_phase(cells, verdict, P, figs / "p2_phase.png")
plot_lines(run, cells, figs / "p2_band_lines.png", args.n_boot, rng)
if len(e):
plot_h3(e, figs / "p2_h3.png")
print(json.dumps(verdict, indent=1, ensure_ascii=False))
print(cells[["c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]]
.to_string(index=False, float_format="%.3f"))
if h3j:
print("H3:", {k: round(v, 4) if isinstance(v, float) else v for k, v in h3j["pooled"].items() if k != "dce_ci95"})
if h4j.get("available"):
print("H4 rejected:", h4j["reject_H4"], {m: (round(h4j[m]["warp_ratio"], 3), round(h4j[m]["band_ratio"], 3)) for m in ("M1", "M2")})
if h1 is not None:
print("H1:", h1["table"][["r", "r_lo", "r_hi", "n_freq"]].round(3).to_dict("index"))
print("->", out)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,202 @@
"""Post-G-B diagnostics, steps 1–2 (plan §9): seismic-conditioned warp posterior via SMC tempering.
python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --workers 4 --device cuda:1
Dev realizations only (realizations of the protocol_p2 main grid are refused). Each job (rid, c, N, seed): register
as in protocol_p2 (pipeline.register: MAP-II hyperparameters, statistical wavelet + constant phase, old M1/M2, B3b–d),
re-estimate the constant phase by SMC over the training wells (smc.smc_fit_phase), then run SMC per well from P
anchor-posterior samples through the γ milestones: γ of the old M2 (g_old), γ = 1/κ at the best anchor sample (g_acf)
and γ = 1 (g_one). Four wavelets: "est" (statistical spectrum, protocol_p2 phase), "estR" (statistical spectrum,
re-estimated phase — the proposed method), "est0" (statistical spectrum, zero phase = true D2 phase) and "true" (true
D2 wavelet); est0 and true serve only as upper bounds, not as methods. B3c is recomputed for each wavelet. Writes warp
errors (RMSE of τ(t) over the main window — for SMC, the error of the posterior-mean warp, i.e. B3d on the new
posterior — 90% coverage and width), the log-likelihood at the true warp, log Z_w over phase (smc_fit_phase) and the
SMC samples (est, estR) to outputs/p2/diag/posterior/. --device cpu runs smc.py (numpy); any other device runs
smc_torch.py (same algorithm and random streams; matches the numpy version up to rounding error).
Stress tests (dev only; defaults = protocol_p2): --snr and --anchor-density change the observed data; --sigma-a-reg
changes the σ_a used for registration (data are still generated with the σ_a of d2_synth.yaml); --smc-seeds k reruns
the anchor sampling, phase and SMC with random stream k (registration seed kept) to measure run-to-run stability;
--wavelets drops some of the upper-bound wavelets. Each setting should write to its own --out-dir.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
_spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
run_d2 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(run_d2)
OLD = ["B3b", "B3c", "B3d", "M1", "M2"]
SAVE = {("est", "g_acf"), ("estR", "g_acf"), ("estR", "g_one")}
WAVELETS = ("est", "estR", "est0", "true")
def job_tag(rid, c, N, seed, smc_seed=None) -> str:
return f"r{rid}_c{c:g}_n{N}_s{seed}" + ("" if smc_seed is None else f"_k{smc_seed}")
def run_job(job) -> pd.DataFrame:
rid, c, N, seed, n_part, P, out_dir, device, mem_gb, st = job
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.registration.pipeline import register
from ml_porosity.registration.sampler import sample_warps
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
from ml_porosity.registration.tie_likelihood import synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors
from ml_porosity.registration.warp_prior import WarpHyper
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
obs = [R.observe(w, c, st["snr_db"], cfg["anchors"]["sigma_a_ms"], st["anchor_density"]) for w in R.pool[:N]]
reg = run_d2.reg_settings(P)
if st["sigma_a_reg"] is not None:
reg["sigma_a_ms"] = st["sigma_a_reg"]
k = seed if st["smc_seed"] is None else st["smc_seed"] # random stream for anchor samples, phase and SMC
mm = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
if device == "cpu":
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
wrap = lambda T: T
else:
import torch
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
dev = torch.device(device)
if dev.type == "cuda": # shared GPU: exceeding the cap makes this job OOM rather than encroach on other processes
total = torch.cuda.get_device_properties(dev).total_memory
torch.cuda.set_per_process_memory_fraction(min(1.0, mem_gb * 2**30 / total), dev)
wrap = lambda T: TiePosteriorTorch(T, device)
out = register(R, obs, reg, seed)
h = WarpHyper(**out["hyper"])
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
B = phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), int(round(R.dt / cfg["fine_dt_ms"])))
Ts, Z0s = [], []
for i, o in enumerate(obs):
smp = sample_warps(R.grid, h, o["tau_k"], o["t_k"], n_part, reg["g_max"], np.random.default_rng([k, i, 13]))
Ts.append(wrap(TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine,
R.t_ext, phase_wavelet(B, out["phase"]), seis[i], (R.t_main[0], R.t_main[-1]))))
Z0s.append(Ts[-1].z(smp["u"]))
t0 = time.time()
phase_r, ph = smc_fit_phase(Ts, Z0s, B, out["phase"], [k, 19])
key = dict(rid=rid, c=c, n_train=N, seed=seed, smc_seed=k, particles=n_part, snr_db=st["snr_db"],
anchor_density=st["anchor_density"], sigma_a_reg=reg["sigma_a_ms"], phase=out["phase"], phase_R=phase_r,
phase_n=len(ph["phases"]), phase_edge=ph["edge"], phase_time_s=time.time() - t0)
wavelets = {"est": phase_wavelet(B, out["phase"]), "estR": phase_wavelet(B, phase_r),
"est0": phase_wavelet(B, 0.0), "true": R.w_fine}
wavelets = {wn: wf for wn, wf in wavelets.items() if wn in st["wavelets"]}
rows, saved = [], {}
for i, o in enumerate(obs):
d = out["diag"][i]
for m in OLD:
e = {k.removeprefix(f"{m}_"): v for k, v in d.items() if k.startswith(f"{m}_warp")}
rows.append(key | {"well": o["name"], "method": m, "wavelet": "est",
"gamma": d["gamma"] if m == "M2" else np.nan} | e)
ut = np.concatenate([[o["b"]], o["g"]])[None]
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
for wn, wf in wavelets.items():
if wn != "est":
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wf)[0]
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
rows.append(key | {"well": o["name"], "method": "B3c", "wavelet": wn}
| warp_errors(t3c[None], R.tau_fine, o["t_of_tau_true"], R.t_main))
T = Ts[i].with_wavelet(wf)
_, l0 = T.parts(Z0s[i])
cks = {"g_old": d["gamma"], "g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
t0, T.n_eval = time.time(), 0
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
sg = pd.DataFrame(res["stages"])
info = {"well": o["name"], "wavelet": wn, "kappa0": 1.0 / cks["g_acf"], "ll_true": float(T.loglik(ut)[0]),
"ll_anchor_max": float(l0.max()), "n_stages": len(sg), "n_eval": T.n_eval,
"time_s": time.time() - t0, "shrink_mean": float(sg["shrink"].mean()),
"jump_z_min": float(sg["jump_z"].min()), "r_true": ncc(T.synth(ut)[0], seis[i])}
for name, gk in cks.items():
U = T.u(res["Z"][float(gk)])
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
e = warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)
syn_m = T.synth(U.mean(0)[None])[0]
rows.append(key | info | {"method": f"SMC_{name}", "gamma": gk, "logZ": res["logZ"][float(gk)],
"ll_max": float(res["ll"][float(gk)].max()),
"ll_mean": float(res["ll"][float(gk)].mean()),
"kappa_post": residual_kappa(syn_m, seis[i]), "r_post": ncc(syn_m, seis[i])} | e)
if (wn, name) in SAVE:
saved[f"{o['name']}/{wn}/{name}"] = U.astype(np.float32)
tag = job_tag(rid, c, N, seed, st["smc_seed"])
(out_dir / f"{tag}_phase.json").write_text(json.dumps({"phase0": out["phase"], "phase_R": phase_r} | ph))
np.savez_compressed(out_dir / f"{tag}_particles.npz", **saved)
df = pd.DataFrame(rows)
df.to_csv(out_dir / f"{tag}.csv", index=False)
return df
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--rids", type=int, nargs="+", default=[900, 901])
ap.add_argument("--c", type=float, nargs="+", default=[1.0])
ap.add_argument("--n", type=int, nargs="+", default=[16])
ap.add_argument("--seeds", type=int, nargs="+", default=[0])
ap.add_argument("--particles", type=int, default=256)
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--device", default="cuda:1", help="cpu: smc.py; cuda:k: smc_torch.py")
ap.add_argument("--gpu-mem-gb", type=float, default=2.0, help="per-worker GPU memory allocation cap (GiB)")
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/posterior")
ap.add_argument("--snr", type=float, default=None, help="seismic SNR (dB); default: grid.snr_db of protocol_p2")
ap.add_argument("--anchor-density", default=None, choices=["full", "half", "topbottom"])
ap.add_argument("--sigma-a-reg", type=float, default=None, help="σ_a (ms) used for registration; default as in protocol_p2")
ap.add_argument("--smc-seeds", type=int, nargs="+", default=None,
help="each k: an independent SMC run (random stream k); files get the suffix _k<k>")
ap.add_argument("--wavelets", nargs="+", default=list(WAVELETS), choices=WAVELETS)
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
bad = sorted(set(args.rids) & set(P["grid"]["realizations"]))
if bad:
raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid: diagnostics use dev realizations only")
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "posterior"
out_dir.mkdir(parents=True, exist_ok=True)
G = P["grid"]
st = {"snr_db": G["snr_db"] if args.snr is None else args.snr,
"anchor_density": args.anchor_density or G["anchor_density"], "sigma_a_reg": args.sigma_a_reg,
"wavelets": args.wavelets}
jobs = [(r, c, n, s, args.particles, P, out_dir, args.device, args.gpu_mem_gb, st | {"smc_seed": k})
for r in args.rids for c in args.c for n in args.n for s in args.seeds for k in (args.smc_seeds or [None])
if not (out_dir / f"{job_tag(r, c, n, s, k)}.csv").exists()]
jobs.sort(key=lambda j: -j[2])
print(f"{len(jobs)} jobs, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(run_job, j): j[:4] + (j[-1]["smc_seed"],) for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
f.result()
print(f"[{i}/{len(jobs)}] {futs[f]} done ({time.time() - t0:.0f} s)", flush=True)
df = pd.concat([pd.read_csv(f) for f in sorted(out_dir.glob("r*_s*.csv"))], ignore_index=True)
df.to_csv(out_dir / "warp.csv", index=False)
print(df.groupby(["rid", "c", "n_train"])[["phase", "phase_R", "phase_n", "phase_edge"]].first().to_string())
cols = ["warp_rmse_ms", "warp_cov90", "warp_width90_ms", "gamma"]
print(df.groupby(["c", "n_train", "wavelet", "method"])[cols].mean().round(3).to_string())
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

324
scripts/15_diag_train.py Normal file
View File

@@ -0,0 +1,324 @@
"""Post-G-B diagnostics, step 3 (plan §9): training on dev realizations with labels from the SMC posterior of scripts/14.
python scripts/15_diag_train.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 1 --workers 4
Dev realizations only. Each cell (rid, c, N): re-register as in protocol_p2 with a fixed registration seed (default 0,
the same seed as scripts/14, hence the same hyperparameters, old phase and old label bank), load the SMC samples and the
re-estimated phase from outputs/p2/diag/posterior/, then train with the same backbone, optimizer, windows and label
normalization as protocol_p2:
- existing methods (label banks from pipeline.register): Oracle, B3a–d, B4a–d, M2 at their locked budgets;
- M2@1, M2@3, M2@inf: the old M2 label bank with λ = 1, 3, ∞ (hard-min) instead of the cell's λ = 1/τ_c (λ diagnostic
of if_fail);
- B3c-R: B3c with the re-estimated-phase wavelet (smc_fit_phase);
- B3d-S·: mean warp over all SMC particles; M2-S·: label bank of S samples drawn at random from the SMC particles,
uniform π, the cell's λ. Suffixes: "e" old-phase wavelet, γ = 1/κ; "a" new-phase wavelet, γ = 1/κ; "1" new-phase
wavelet, γ = 1;
- M2-Sa@1, M2-Sa@3, M2-Sa@inf: as M2-Sa with λ = 1, 3, ∞.
Methods without a locked budget are run at every candidate budget of protocol_p2 and selected by the protocol's rule
(lowest total RMSE at c = 1, averaged over rid × N × seed; band metrics are not used). The training seed controls only
the network initialization. A G-B-style gate is recomputed for each candidate against two competitor sets: that of
protocol_p2 ("p2"), and that set plus B3c-R and B3d-S from the same posterior ("full"); over 2 realizations × 2 seeds,
cell_pass requires both.
→ outputs/p2/diag/train/: cells/r{rid}_c{c}_n{N}.csv (+ _diag.csv), results.csv, runs.csv, budgets.json, gate.csv,
gate.json
Stress tests (preparation of protocol_p3, dev only): --snr, --anchor-density and --sigma-a-reg must match the
scripts/14 run in --post-dir (checked via the register phase). The SNR also changes the seismic of the test wells.
--variants selects variants with particles in --post-dir (the scripts/14 stress grid stores only estR: "a" and "1");
--methods restricts the methods; --budgets-from reuses budgets selected in a previous run (budgets.json) instead of
running all candidates and reselecting; --save-preds stores per-seed μ, σ (cells/*.npz) to build seed ensembles as in
H3: B5 (B3b) versus the ensemble of each method, with the same rejection rule as protocol_p2 (→ h3.csv, h3.json).
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
def load_script(name: str):
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
run_d2 = load_script("11_run_d2.py")
OLD = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M2"]
VARIANTS = {"e": ("est", "g_acf"), "a": ("estR", "g_acf"), "1": ("estR", "g_one")}
LAMS = {"1": 1.0, "3": 3.0, "inf": None}
CANDIDATES = ["M2", *[f"M2@{k}" for k in LAMS], *[f"M2-S{v}" for v in VARIANTS], *[f"M2-Sa@{k}" for k in LAMS]]
def run_cell(job) -> tuple[list[dict], float]:
rid, c, N, seeds, reg_seed, P, device, post_dir, out_dir, st = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.models.bank_train import train_predict, zscore_patch
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.pipeline import register
from ml_porosity.registration.smc import phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors, warp_mean
from ml_porosity.registration.warp_prior import WarpHyper
t0 = time.time()
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, c, st["snr_db"], sa, st["anchor_density"]) for w in R.pool[:N]]
test = [R.observe(w, c, st["snr_db"], sa) for w in R.test]
X = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test])
yt = 100 * np.stack([o["y_true"] for o in test])
reg = run_d2.reg_settings(P)
if st["sigma_a_reg"] is not None:
reg["sigma_a_ms"] = st["sigma_a_reg"]
tcfg = P["training"]["model"] | P["training"]["optimizer"]
variants = {v: VARIANTS[v] for v in st["variants"]}
out = register(R, obs, reg, reg_seed)
tag = f"r{rid}_c{c:g}_n{N}_s{reg_seed}"
ph = json.loads((post_dir / f"{tag}_phase.json").read_text())
if ph["phase0"] != out["phase"]:
raise RuntimeError(f"{tag}: register phase ({out['phase']}) differs from scripts/14 ({ph['phase0']})")
smc = np.load(post_dir / f"{tag}_particles.npz")
f, fac = cfg["fine_dt_ms"], int(round(R.dt / cfg["fine_dt_ms"]))
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
banks = {m: [] for m in ["B3c-R", *[f"{p}-S{v}" for v in variants for p in ("B3d", "M2")]]}
logpi = {v: [] for v in variants}
key = dict(rid=rid, c=c, n_train=N)
diag = []
for i, o in enumerate(obs):
y_aa = antialias(o["phi_log"], f, R.dt)
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wR)[0]
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
banks["B3c-R"].append(lab(y_aa, t3c))
d = key | {"reg_seed": reg_seed, "phase": out["phase"], "phase_R": ph["phase_R"], "lam": out["lam"],
"well": o["name"], "B3c-R_warp_rmse_ms": err(t3c, o)}
for v, (wn, gn) in variants.items():
U = smc[f"{o['name']}/{wn}/{gn}"].astype(float)
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
tm = warp_mean(Tf, np.zeros(len(Tf)))
banks[f"B3d-S{v}"].append(lab(y_aa, tm))
sub = np.random.default_rng([reg_seed, i, 29]).choice(len(Tf), reg["S"], replace=False)
Y = lab(y_aa, Tf[sub])
ok = np.all(np.isfinite(Y), 1)
Y[~ok] = Y[ok][0]
banks[f"M2-S{v}"].append(Y)
logpi[v].append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
d |= {f"B3d-S{v}_warp_rmse_ms": err(tm, o), f"M2-S{v}_n_valid": int(ok.sum())}
diag.append(d)
m0, s0 = out["norm"]
cand, locked = P["training"]["budget_candidates"], P["training"]["budgets"]
specs = {m: (sp, [locked[m]]) for m, sp in run_d2.method_specs(out, P, OLD).items()}
nbank = {m: ((np.stack(v) - m0) / s0).astype(np.float32) for m, v in banks.items()}
single = lambda Y: {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1)), "lam": out["lam"]}
specs |= {f"M2@{k}": (specs["M2"][0] | {"lam": lam}, cand) for k, lam in LAMS.items()}
specs |= {m: (single(nbank[m]), cand) for m in ["B3c-R", *[f"B3d-S{v}" for v in variants]]}
for v in variants:
sp = {"kind": "bank", "Y": nbank[f"M2-S{v}"], "logpi": np.stack(logpi[v]).astype(np.float32), "lam": out["lam"]}
specs[f"M2-S{v}"] = (sp, cand)
if v == "a":
specs |= {f"M2-Sa@{k}": (sp | {"lam": lam}, cand) for k, lam in LAMS.items()}
if st["methods"]:
specs = {m: s for m, s in specs.items() if m in st["methods"]}
if st["budgets"]:
specs = {m: (sp, [st["budgets"][m]] if m in st["budgets"] else bud) for m, (sp, bud) in specs.items()}
rows, preds = [], {}
for seed in seeds:
for m, (sp, bud) in specs.items():
for b, (mu, sg) in train_predict(X, Xte, sp, tcfg, seed, bud, device).items():
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
for w, r in zip(R.test, run_d2.evaluate(yt, mu_p, sg_p, P["metrics"]["bands"]["f_c_hz"])):
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": w.name} | r)
if st["save_preds"]:
preds[f"{m}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32)
preds[f"{m}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32)
stem = f"r{rid}_c{c:g}_n{N}"
if preds:
np.savez_compressed(out_dir / f"{stem}.npz", y_true=yt.astype(np.float32),
test_wells=np.array([w.name for w in R.test]), **preds)
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the cell as complete
return rows, time.time() - t0
def summarize(cell_dir: Path, out_dir: Path, P: dict, args) -> None:
sp13 = load_script("13_summarize_p2.py")
files = sorted(f for f in cell_dir.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv"))
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
dg = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True)
G = P["grid"]
locked = P["training"]["budgets"]
free = sorted(set(df.method) - set(OLD))
if args.budgets_from:
fixed = json.loads(args.budgets_from.read_text())
budgets = {m: int(locked[m] if m in OLD else fixed[m]) for m in sorted(set(df.method))}
else:
budgets = {m: int(locked[m]) for m in OLD} | run_d2.select_budgets(df[(df.c == G["realistic_drift"]) & df.method.isin(free)])
(out_dir / "budgets.json").write_text(json.dumps(budgets, indent=1))
df.to_csv(out_dir / "results.csv", index=False)
dg.to_csv(out_dir / "diag.csv", index=False)
df = df[df["budget"] == df["method"].map(budgets)]
run = df.groupby(["rid", "c", "n_train", "method", "seed"], as_index=False)[sp13.METRICS].mean()
run.to_csv(out_dir / "runs.csv", index=False)
tab = run.groupby(["c", "n_train", "method"])[["band_rmse", "band_pcc", "rmse"]].mean().unstack("method")
pd.set_option("display.width", 250)
print("budgets:", budgets)
print(tab["band_rmse"].round(3).to_string())
print(tab["band_pcc"].round(3).to_string())
print(dg.groupby(["c", "n_train"])[[k for k in dg.columns if k.endswith("warp_rmse_ms")]].mean().round(2).to_string())
grid = G | {"realizations": sorted(run.rid.unique().tolist()), "seeds": sorted(run.seed.unique().tolist()),
"n_train": sorted(run.n_train.unique().tolist()), "drift_factors": sorted(run.c.unique().tolist())}
comp_p2 = P["gates"]["G-B"]["competitors"]
rng = np.random.default_rng(0)
rows, verdicts = [], {}
for cand in CANDIDATES:
if cand not in set(run.method):
continue
v = cand.split("@")[0].removeprefix("M2-S") if cand.startswith("M2-S") else None
sets = {"p2": comp_p2}
if v is not None:
sets["full"] = comp_p2 + ["B3c-R", f"B3d-S{v}"]
for sname, comp in sets.items():
r = run[run.method.isin(comp) | (run.method == cand)]
if cand != "M2":
r = r[r.method != "M2"].replace({"method": {cand: "M2"}})
Pg = P | {"grid": grid, "gates": {"G-B": P["gates"]["G-B"] | {"competitors": comp}}}
cells, verdict = sp13.gate_gb(r, Pg, args.n_boot, rng)
rows.append(cells.assign(candidate=cand, competitors=sname))
verdicts[f"{cand}/{sname}"] = verdict
if not rows: # e.g. --methods B3d alone: no gate candidate trained
print("no gate candidate among the trained methods; gate skipped")
return
gate = pd.concat(rows, ignore_index=True)
gate.to_csv(out_dir / "gate.csv", index=False)
(out_dir / "gate.json").write_text(json.dumps(verdicts, indent=1, default=float))
cols = ["candidate", "competitors", "c", "n_train", "best", "m2_band_rmse", "best_band_rmse", "ratio", "dpcc",
"seeds_improve", "rids_improve", "cell_pass"]
print(gate[cols].round(3).to_string())
print(pd.DataFrame(verdicts).T[["realistic_cells_pass", "zero_drift_macro_ratio", "zero_drift_guard", "pass"]].to_string())
if any(cell_dir.glob("r*_c*_n*.npz")):
h3_ensembles(cell_dir, out_dir, P, budgets, sp13, args.n_boot, rng)
def h3_ensembles(cell_dir: Path, out_dir: Path, P: dict, budgets: dict, sp13, n_boot: int, rng) -> None:
"""As H3 of protocol_p2, but for every method with saved predictions: seed ensemble (μ = mean of μ_s,
σ² = mean of σ_s² + variance of μ_s) versus B5 in each cell (c, N), with the same rejection rule."""
pairs = [("B5", "B3b")] + [(f"{m}-ens", m) for m in budgets if m != "B3b"]
e = sp13.h3_table(cell_dir, P, budgets, pairs=pairs, pattern="r*_c*_n*.npz")
e.to_csv(out_dir / "h3.csv", index=False)
res = {}
for cand in sorted(set(e.method) - {"B5"}):
for (c, N), d in e.groupby(["c", "n_train"]):
m = d.groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean()
if cand not in m.index or "B5" not in m.index:
continue
a, b = m.loc[cand], m.loc["B5"]
width = a.mean_sigma / b.mean_sigma
per_rid = d.groupby(["method", "rid"])["ce"].mean()
diff = (per_rid.loc[cand] - per_rid.loc["B5"]).to_numpy()
res[f"{cand}/c{c:g}/n{N}"] = {
"ce": a.ce, "ce_b5": b.ce, "dce": float(diff.mean()), "dce_ci95": sp13.boot(diff, None, n_boot, rng),
"width_ratio": width, "nll": a.nll, "nll_b5": b.nll, "crps": a.crps, "crps_b5": b.crps,
"members": int(d.loc[d.method == cand, "members"].min()),
"reject_H3": bool(a.ce >= b.ce or (width > sp13.H3_WIDTH and a.nll >= b.nll and a.crps >= b.crps))}
(out_dir / "h3.json").write_text(json.dumps(res, indent=1, default=float))
print(pd.DataFrame(res).T[["ce", "ce_b5", "dce", "width_ratio", "nll", "nll_b5", "crps", "crps_b5", "members",
"reject_H3"]].to_string())
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--rids", type=int, nargs="+", default=[900, 901])
ap.add_argument("--c", type=float, nargs="+", default=[0.0, 1.0, 2.0])
ap.add_argument("--n", type=int, nargs="+", default=[4, 16])
ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1])
ap.add_argument("--reg-seed", type=int, default=0)
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--n-boot", type=int, default=2000)
ap.add_argument("--post-dir", type=Path, default=None, help="default: outputs/p2/diag/posterior")
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/train")
ap.add_argument("--summary-only", action="store_true")
ap.add_argument("--snr", type=float, default=None, help="seismic SNR (dB) for all wells; default as in protocol_p2")
ap.add_argument("--anchor-density", default=None, choices=["full", "half", "topbottom"])
ap.add_argument("--sigma-a-reg", type=float, default=None, help="σ_a (ms) used for registration; default as in protocol_p2")
ap.add_argument("--variants", nargs="+", default=list(VARIANTS), choices=list(VARIANTS))
ap.add_argument("--methods", nargs="+", default=None, help="train only these methods (default: all)")
ap.add_argument("--budgets-from", type=Path, default=None,
help="budgets.json from a previous run: each method listed there is run only at that budget")
ap.add_argument("--save-preds", action="store_true", help="save per-seed μ, σ (cells/*.npz) for H3-style ensembles")
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
bad = sorted(set(args.rids) & set(P["grid"]["realizations"]))
if bad:
raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid: diagnostics use dev realizations only")
post_dir = args.post_dir or outputs_dir() / "p2" / "diag" / "posterior"
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "train"
cell_dir = out_dir / "cells"
cell_dir.mkdir(parents=True, exist_ok=True)
G = P["grid"]
st = {"snr_db": G["snr_db"] if args.snr is None else args.snr,
"anchor_density": args.anchor_density or G["anchor_density"], "sigma_a_reg": args.sigma_a_reg,
"variants": args.variants, "methods": args.methods, "save_preds": args.save_preds,
"budgets": json.loads(args.budgets_from.read_text()) if args.budgets_from else None}
jobs = []
for rid in args.rids:
for c in args.c:
for N in args.n:
if (cell_dir / f"r{rid}_c{c:g}_n{N}.csv").exists() or args.summary_only:
continue
if not (post_dir / f"r{rid}_c{c:g}_n{N}_s{args.reg_seed}_particles.npz").exists():
print(f"skipping r{rid} c={c:g} N={N}: no SMC samples yet", flush=True)
continue
jobs.append((rid, c, N, args.seeds, args.reg_seed, P, args.device, post_dir, cell_dir, st))
jobs.sort(key=lambda j: -j[2])
print(f"{len(jobs)} cells, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(run_cell, j): j[:3] for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
_, dt = f.result()
print(f"[{i}/{len(jobs)}] cell {futs[f]} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
summarize(cell_dir, out_dir, P, args)
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

208
scripts/16_f3_posterior.py Normal file
View File

@@ -0,0 +1,208 @@
"""Placing F3 on the σ_post axis (preparation of protocol_p3, descriptive only): SMC warp posterior on the 4 real F3 wells.
python scripts/16_f3_posterior.py --device cuda:1
τ is sonic time (DT integrated from the first TD marker, as in scripts/09). Anchors are the TD markers within the
extended window 400–1300 ms; TD markers are not independent checkshots (plan §10). AI in τ is taken from the LAS AI log,
anti-alias filtered onto a 0.5 ms grid. The seismic is the central trace of the 3×3 patch at each well
(outputs/f3_wells.npz).
Registration as for D2 under protocol_p2:
- MAP-II hyperparameters on the anchors of the 4 wells (σ_a = 7 ms, σ_b = 50 ms fixed, hyperprior as in the protocol);
- 128 ms statistical wavelet from the 4 traces;
- initial phase from the old fit_phase, then re-estimated by SMC (log Z);
- SMC up to γ = 1/κ (g_acf) and γ = 1.
The "f3ml" variant uses the type-II ML hyperparameters of scripts/09 (σ_a ≈ 0.4 ms), i.e. treats the TD markers as
nearly exact relative to the seismic.
There is no true warp, hence no warp error. The script reports:
- σ_post: mean over the main window of (q95 − q05)/3.29 of τ(t);
- the particle standard deviation and κ;
- r between the synthetic at the posterior-mean warp and the seismic over the main window (same definition as the
r_post column of script 14);
- r of B3c and the RMS shift of the posterior-mean warp relative to B3b.
K independent SMC runs (--smc-seeds) measure the Monte Carlo error. The results only describe where F3 lies on the
σ_post and r axes of D2; they are not used to select γ, P or λ.
Outputs: outputs/p2/diag/f3_posterior/{wells.csv, phase.json, particles.npz}.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import time
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
_spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
run_d2 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(run_d2)
TAU_RANGE = (200.0, 1500.0) # wider than scripts/09 so that τ(t) covers the seismic window ± half a wavelet at every well
PHASES = np.arange(-180, 180, 15)
def f3_wells(cfg: dict, tau_fine: np.ndarray) -> list[dict]:
from ml_porosity.data.las_io import load_well
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import sonic_tdr
D = np.load(outputs_dir() / "f3_wells.npz")
e0, e1 = cfg["ext_window_ms"]
out = []
for name in cfg["wells"]:
w = load_well(name)
cs = w.checkshot
base = sonic_tdr(w.md, w.curve("DT"), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
tk = cs.twt_ms.to_numpy()
tau_k = base.time_at(cs.md.to_numpy())
m = (tk >= e0) & (tk <= e1)
ai = log_to_time(w.md, w.curve("AI"), base, tau_fine, **cfg["resample"])
ok = np.isfinite(ai)
out.append({"name": name, "tau_k": tau_k[m], "t_k": tk[m],
"ai_log": np.interp(tau_fine, tau_fine[ok], ai[ok]), # outside the logged interval: constant (zero reflectivity)
"seis": D[f"{name}/seismic_patch"][4].astype(float), "t": D[f"{name}/times_ms"].astype(float),
"main": D[f"{name}/main_mask"].astype(bool)})
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--particles", type=int, default=256)
ap.add_argument("--smc-seeds", type=int, nargs="+", default=[0, 1, 2, 3])
ap.add_argument("--settings", nargs="+", default=["proto", "f3ml"], choices=["proto", "f3ml"])
ap.add_argument("--device", default="cuda:1", help="cpu: smc.py; cuda:k: smc_torch.py")
ap.add_argument("--gpu-mem-gb", type=float, default=2.0)
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/f3_posterior")
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "4", "MKL_NUM_THREADS": "4", "OPENBLAS_NUM_THREADS": "4"}.items():
os.environ.setdefault(k, v)
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.registration.labels import invert_warps
from ml_porosity.registration.pipeline import fit_cell_hyper
from ml_porosity.registration.sampler import sample_warps
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, phase_loglik, synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper
if args.device == "cpu":
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
wrap = lambda T: T
else:
import torch
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
dev = torch.device(args.device)
if dev.type == "cuda":
total = torch.cuda.get_device_properties(dev).total_memory
torch.cuda.set_per_process_memory_fraction(min(1.0, args.gpu_mem_gb * 2**30 / total), dev)
wrap = lambda T: TiePosteriorTorch(T, args.device)
P = run_d2.load_protocol(check=True)
reg = run_d2.reg_settings(P)
cfg_d2 = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d1_f3.yaml").read_text())
f, dt = cfg_d2["fine_dt_ms"], cfg_d2["dt_ms"]
fac = int(round(dt / f))
grid = WarpGrid(*TAU_RANGE, cfg_d2["warp_dtau_ms"])
tau_fine = np.arange(TAU_RANGE[0], TAU_RANGE[1] + f / 2, f)
wells = f3_wells(cfg, tau_fine)
t_out, mm = wells[0]["t"], wells[0]["main"]
if not all(np.array_equal(w["t"], t_out) and np.array_equal(w["main"], mm) for w in wells):
raise SystemExit("seismic time axes differ between wells")
t_main = t_out[mm]
t_fine = np.arange(t_out[0] - 300.0, t_out[-1] + 300.0 + f / 2, f)
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
w0 = statistical_wavelet(np.stack([w["seis"] for w in wells]), dt, reg["wavelet_ms"])
B = phase_basis(w0, fac)
qc = pd.read_csv(outputs_dir() / "tie_qc.csv").set_index(["well", "tdr"])["r_best_tie"]
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "f3_posterior"
out_dir.mkdir(parents=True, exist_ok=True)
rows, phases, saved = [], {}, {}
for setting in args.settings:
if setting == "proto":
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=grid), wells, reg, seed=0)
hinfo = {k: hinfo[k] for k in ("log_marginal", "at_bound")}
else:
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())
h, hinfo = WarpHyper(**prior["fits"][P["inputs"]["warp_prior"]["fit"]]["hyper"]), {}
# initial phase as in pipeline.register: old fit_phase on S anchor-posterior samples at γ = 1
LL = []
for i, w in enumerate(wells):
smp = sample_warps(grid, h, w["tau_k"], w["t_k"], reg["S"], reg["g_max"], np.random.default_rng([0, i, 11]))
T = grid.t_of_tau(smp["b"], smp["g"], tau=tau_fine)
LL.append(phase_loglik(synth_for_warps(tau_fine, w["ai_log"], T, t_fine, t_out, fine_wavelet(w0, fac)),
w["seis"], PHASES))
phase0 = float(PHASES[fit_phase(LL, [np.ones(L.shape[1], bool) for L in LL], PHASES)])
for k in args.smc_seeds:
t0 = time.time()
Ts, Z0s = [], []
for i, w in enumerate(wells):
smp = sample_warps(grid, h, w["tau_k"], w["t_k"], args.particles, reg["g_max"],
np.random.default_rng([k, i, 13]))
Ts.append(wrap(TiePosterior(grid, h, w["tau_k"], w["t_k"], reg["g_max"], tau_fine, w["ai_log"], t_fine,
t_out, phase_wavelet(B, phase0), w["seis"], (t_main[0], t_main[-1]))))
Z0s.append(Ts[-1].z(smp["u"]))
phase_r, ph = smc_fit_phase(Ts, Z0s, B, phase0, [k, 19])
phases[f"{setting}/k{k}"] = {"phase0": phase0, "phase_R": phase_r} | ph
wf = phase_wavelet(B, phase_r)
key = {"setting": setting, "smc_seed": k, "particles": args.particles, "phase0": phase0, "phase_R": phase_r,
"phase_edge": ph["edge"]} | {f"hyper_{a}": b for a, b in h.as_dict().items() if a != "kernel"} | hinfo
for i, w in enumerate(wells):
T = Ts[i].with_wavelet(wf)
_, l0 = T.parts(Z0s[i])
cks = {"g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
t1 = time.time()
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
t_b3b = tie_b3b(w["tau_k"], w["t_k"], tau_fine)
syn_b = synth_for_warps(tau_fine, w["ai_log"], t_b3b, t_fine, t_out, wf)[0]
t_b3c = tie_b3c(t_b3b, tau_fine, syn_b, w["seis"], t_out, dt)
syn_c = synth_for_warps(tau_fine, w["ai_log"], t_b3c[None], t_fine, t_out, wf)[0]
tau_b3b = invert_warps(t_b3b[None], tau_fine, t_main)[0]
info = {"well": w["name"], "n_anchor": len(w["tau_k"]), "kappa0": 1.0 / cks["g_acf"],
"n_stages": len(res["stages"]), "time_s": time.time() - t1, "r_b3b": ncc(syn_b, w["seis"]),
"r_b3c": ncc(syn_c, w["seis"]),
"b3c_vs_b3b_rms_ms": float(np.sqrt(np.nanmean((invert_warps(t_b3c[None], tau_fine, t_main)[0]
- tau_b3b) ** 2))),
"r_best_tie_calibrated": float(qc.get((w["name"], "calibrated"), np.nan))}
post = [("anchor", np.nan, Z0s[i])] + [(nm, g, res["Z"][float(g)]) for nm, g in cks.items()]
for nm, g, Z in post:
U = T.u(Z)
tau_t = invert_warps(grid.t_of_tau(U[:, 0], U[:, 1:], tau=tau_fine), tau_fine, t_main)
q05, q95 = np.nanquantile(tau_t, [0.05, 0.95], axis=0)
mean_tau = np.nanmean(tau_t, 0)
syn_m = T.synth(U.mean(0)[None])[0]
rows.append(key | info | {"posterior": nm, "gamma": g,
"logZ": res["logZ"].get(float(g), np.nan) if nm != "anchor" else np.nan,
"sigma_post_ms": float(np.mean(q95 - q05)) / 3.29,
"sd_post_ms": float(np.mean(np.nanstd(tau_t, 0))),
"shift_vs_b3b_rms_ms": float(np.sqrt(np.nanmean((mean_tau - tau_b3b) ** 2))),
"r_post": ncc(syn_m, w["seis"]), "kappa_post": residual_kappa(syn_m, w["seis"])})
saved[f"{setting}/k{k}/{w['name']}/{nm}/mean_tau"] = mean_tau.astype(np.float32)
if nm == "g_acf":
saved[f"{setting}/k{k}/{w['name']}/{nm}/U"] = U.astype(np.float32)
print(f"{setting} k={k}: φ0 {phase0:+.0f}°, φ_R {phase_r:+.1f}° ({time.time() - t0:.0f} s)", flush=True)
saved["t_main"] = t_main
np.savez_compressed(out_dir / "particles.npz", **saved)
(out_dir / "phase.json").write_text(json.dumps(phases, indent=1, default=float))
df = pd.DataFrame(rows)
df.to_csv(out_dir / "wells.csv", index=False)
cols = ["sigma_post_ms", "sd_post_ms", "r_post", "kappa_post", "kappa0", "shift_vs_b3b_rms_ms", "r_b3c",
"r_best_tie_calibrated"]
print(df.groupby(["setting", "posterior", "well"])[cols].mean().round(3).to_string())
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

View File

@@ -0,0 +1,391 @@
"""Summary of the dev experiments preparing protocol_p3 (scripts/run_p3_dev.sh). Uses dev realizations 900/901 only.
python scripts/17_summarize_p3_dev.py # every section with available data
python scripts/17_summarize_p3_dev.py --only screen
Sections:
screen posterior stress grid (outputs/p2/diag/stress/snr*_{full,half,topbottom}/). Each cell (SNR, anchor
density, c) is averaged over rid × N × well:
- σ_post = width90/3.29 of τ(t);
- warp error, 90% coverage;
- r at the posterior-mean warp and at the true warp; κ; γ.
A cell is "wide" if σ_post (estR wavelet, γ = 1/κ) ≥ 1.5 ms. Threshold from Proposition 1: the transfer
coefficient at 50 Hz is exp(−2π²σ²f²) ≤ 0.90. Wide cells are written to wide_cells.txt, which the train
stage of run_p3_dev.sh reads.
stability independent SMC runs (stability/p256, p1024; same registration seed):
- |Δτ̄(t)| between each pair of runs over the main window;
- p95 against the 0.5 ms criterion;
- spread of σ_post and of the re-estimated phase.
sigma_a registration with σ_a = 3.5 or 14 ms versus 7 ms; data are always generated with σ_a = 7 ms.
f3 F3 (f3_posterior/), descriptive only: σ_post, r, κ per well; |Δτ̄| between runs.
blur B(σ): band-RMSE penalty when dev Oracle predictions are blurred by σ (Proposition 1); a bound on the
attainable gain for H2b.
train training in the wide cells (train_stress/*) and H3 with the SMC posterior (h3_smc):
- band RMSE of M2-Sa / B3d-Sa / B3c-R / Oracle per cell;
- M2-Sa/B3d-Sa ratio per seed and per realization, joined with the cell's σ_post;
- H3 results written by scripts/15 (h3.json).
→ outputs/p2/diag/p3dev/: screen.csv, wide_cells.txt, stability.csv, sigma_a.csv, f3.csv, train.csv, blur.csv, summary.md
"""
from __future__ import annotations
import argparse
import itertools
import json
import re
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
Z90 = 3.29 # width of the Gaussian 90% interval = 3.29 σ
WIDE_MS = 1.5
STAB_MS = 0.5
SMC = ["SMC_g_acf", "SMC_g_one"]
DIAG = outputs_dir() / "p2" / "diag"
def load_dir(d: Path, k_files: bool = False) -> pd.DataFrame | None:
files = [f for f in sorted(d.glob("r*_s*.csv")) if bool(re.search(r"_k\d+\.csv$", f.name)) == k_files]
return pd.concat([pd.read_csv(f) for f in files], ignore_index=True) if files else None
def cell_stats(df: pd.DataFrame, by: list[str]) -> pd.DataFrame:
s = df[df.method.isin(SMC)].assign(sigma_post_ms=lambda d: d.warp_width90_ms / Z90)
tab = s.groupby(by + ["wavelet", "method"]).agg(
sigma_post_ms=("sigma_post_ms", "mean"), sigma_post_min=("sigma_post_ms", "min"),
warp_rmse_ms=("warp_rmse_ms", "mean"), warp_cov90=("warp_cov90", "mean"), r_post=("r_post", "mean"),
r_true=("r_true", "mean"), kappa_post=("kappa_post", "mean"), gamma=("gamma", "mean"), n=("well", "size"))
b3c = (df[df.method == "B3c"].groupby(by + ["wavelet"])["warp_rmse_ms"].mean().rename("b3c_warp_rmse_ms"))
return tab.join(b3c, on=by + ["wavelet"]).reset_index()
# ---------------------------------------------------------------- screen
def screen(out: Path) -> pd.DataFrame | None:
parts = [load_dir(d) for d in sorted((DIAG / "stress").glob("snr*_*")) if re.fullmatch(r"snr-?\d+_[a-z]+", d.name)]
parts = [p for p in parts if p is not None]
if not parts:
return None
df = pd.concat(parts, ignore_index=True)
by = ["snr_db", "anchor_density", "c"]
tab = cell_stats(df, by)
per_n = cell_stats(df, by + ["n_train"])
tab.to_csv(out / "screen.csv", index=False)
per_n.to_csv(out / "screen_per_n.csv", index=False)
key = tab[(tab.wavelet == "estR") & (tab.method == "SMC_g_acf")]
wide = key[key.sigma_post_ms >= WIDE_MS]
with open(out / "wide_cells.txt", "w") as fh:
for (snr, dens), d in wide.groupby(["snr_db", "anchor_density"]):
fh.write(f"{snr:g} {dens} {' '.join(f'{c:g}' for c in sorted(d.c))}\n")
return tab
# ---------------------------------------------------------------- stability
def d2_axes() -> tuple:
from ml_porosity.registration.warp_prior import WarpGrid
P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text())
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
f, dt = cfg["fine_dt_ms"], cfg["dt_ms"]
grid = WarpGrid(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1], cfg["warp_dtau_ms"])
tau_fine = np.arange(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1] + f / 2, f)
t_ext = np.arange(cfg["ext_window_ms"][0], cfg["ext_window_ms"][1] + dt / 2, dt)
m0, m1 = cfg["main_window_ms"]
return grid, tau_fine, t_ext[(t_ext >= m0) & (t_ext <= m1)]
def tau_of_t(U: np.ndarray, grid, tau_fine, t_main) -> np.ndarray:
from ml_porosity.registration.labels import invert_warps
return invert_warps(grid.t_of_tau(U[:, 0], U[:, 1:], tau=tau_fine), tau_fine, t_main)
def pair_diffs(means: dict) -> tuple[np.ndarray, list[float]]:
"""means: {k: τ̄_k(t)} → |Δ| concatenated over all pairs, and max |Δ| of each pair."""
d = [np.abs(means[a] - means[b]) for a, b in itertools.combinations(sorted(means), 2)]
return (np.concatenate(d) if d else np.array([])), [float(np.nanmax(x)) for x in d]
def stability(out: Path) -> pd.DataFrame | None:
dirs = sorted(d for d in (DIAG / "stability").glob("p*") if d.is_dir()) if (DIAG / "stability").exists() else []
if not dirs:
return None
grid, tau_fine, t_main = d2_axes()
rows = []
for d in dirs:
runs = {}
for f in sorted(d.glob("r*_s*_k*_particles.npz")):
rid, c, N, s, k = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)_s(\d+)_k(\d+)_particles", f.stem).groups()
runs.setdefault((int(rid), float(c), int(N)), {})[int(k)] = f
for (rid, c, N), ks in runs.items():
if len(ks) < 2:
continue
zs = {k: np.load(f) for k, f in ks.items()}
ph = {k: json.loads(f.with_name(f.name.replace("_particles.npz", "_phase.json")).read_text())["phase_R"]
for k, f in ks.items()}
wells = sorted({key.split("/")[0] for key in zs[min(zs)].files})
for variant in ("estR/g_acf", "estR/g_one"):
for w in wells:
means, sig = {}, {}
for k, z in zs.items():
T = tau_of_t(z[f"{w}/{variant}"].astype(float), grid, tau_fine, t_main)
means[k] = np.nanmean(T, 0)
q05, q95 = np.nanquantile(T, [0.05, 0.95], axis=0)
sig[k] = float(np.mean(q95 - q05)) / Z90
dd, mx = pair_diffs(means)
rows.append({"particles": d.name, "rid": rid, "c": c, "n_train": N, "variant": variant, "well": w,
"runs": len(ks), "d_p50": float(np.nanmedian(dd)), "d_p95": float(np.nanquantile(dd, 0.95)),
"d_max": float(np.nanmax(dd)), "pairs_max_gt1": int(sum(m > 1 for m in mx)),
"pairs": len(mx), "sigma_post_mean": float(np.mean(list(sig.values()))),
"sigma_post_sd": float(np.std(list(sig.values()))),
"phase_R_range": float(np.ptp(list(ph.values())))})
df = pd.DataFrame(rows)
df.to_csv(out / "stability.csv", index=False)
return df
def stability_table(df: pd.DataFrame) -> pd.DataFrame:
"""The pooled p95 of |Δ| over all wells × t × pairs is not a weighted mean of the per-well p95, so both the
median per-well p95 and the maximum p95 are reported; the criterion applies to the p95 of each cell (rid, c, N)
averaged over wells."""
g = df.groupby(["particles", "variant", "c"])
return g.agg(runs=("runs", "max"), wells=("well", "size"), d_p50=("d_p50", "median"), d_p95_median=("d_p95", "median"),
d_p95_mean=("d_p95", "mean"), d_p95_max=("d_p95", "max"), d_max=("d_max", "max"),
pairs_max_gt1=("pairs_max_gt1", "sum"), pairs=("pairs", "sum"), sigma_post=("sigma_post_mean", "mean"),
sigma_post_sd=("sigma_post_sd", "mean"), phase_R_range=("phase_R_range", "max")).reset_index()
# ---------------------------------------------------------------- σ_a, F3
def sigma_a(out: Path) -> pd.DataFrame | None:
parts = []
for d in [DIAG / "stress" / "snr10_full", *sorted((DIAG / "stress").glob("snr10_full_sa*"))]:
df = load_dir(d) if d.exists() else None
if df is not None:
parts.append(df)
if len(parts) < 2:
return None
df = pd.concat(parts, ignore_index=True)
old = df[df.method.isin(["M1", "M2"])].groupby(["sigma_a_reg", "c", "method"])[["warp_rmse_ms", "warp_cov90", "warp_width90_ms"]].mean()
tab = cell_stats(df, ["sigma_a_reg", "c"])
tab.to_csv(out / "sigma_a.csv", index=False)
old.reset_index().to_csv(out / "sigma_a_anchor.csv", index=False)
return tab
def f3(out: Path) -> tuple[pd.DataFrame, pd.DataFrame] | None:
d = DIAG / "f3_posterior"
if not (d / "wells.csv").exists():
return None
df = pd.read_csv(d / "wells.csv")
cols = ["sigma_post_ms", "sd_post_ms", "r_post", "kappa_post", "kappa0", "shift_vs_b3b_rms_ms", "r_b3b", "r_b3c",
"r_best_tie_calibrated", "n_anchor"]
tab = df.groupby(["setting", "posterior", "well"])[cols].mean()
tab["sigma_post_sd_runs"] = df.groupby(["setting", "posterior", "well"])["sigma_post_ms"].std()
tab = tab.reset_index()
z = np.load(d / "particles.npz")
rows = []
for setting, post, w in tab[["setting", "posterior", "well"]].itertuples(index=False):
means = {int(re.search(r"/k(\d+)/", k).group(1)): z[k] for k in z.files
if k.startswith(f"{setting}/k") and k.endswith(f"/{w}/{post}/mean_tau")}
dd, mx = pair_diffs(means)
if len(dd):
rows.append({"setting": setting, "posterior": post, "well": w, "d_p95": float(np.nanquantile(dd, 0.95)),
"d_max": float(np.nanmax(dd))})
stab = pd.DataFrame(rows)
tab = tab.merge(stab, on=["setting", "posterior", "well"], how="left") if len(stab) else tab
tab.to_csv(out / "f3.csv", index=False)
ph = json.loads((d / "phase.json").read_text())
return tab, pd.DataFrame([{"run": k, "phase0": v["phase0"], "phase_R": v["phase_R"], "edge": v.get("edge")}
for k, v in ph.items()])
# ---------------------------------------------------------------- train
TRAIN_METHODS = ["Oracle", "B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa", "B3d-S1", "M2-S1", "M2"]
def train(out: Path, screen_tab: pd.DataFrame | None) -> pd.DataFrame | None:
dirs = [(re.fullmatch(r"snr(-?\d+)_([a-z]+)", d.name), d) for d in sorted((DIAG / "train_stress").glob("snr*_*"))] \
if (DIAG / "train_stress").exists() else []
srcs = [(float(m.group(1)), m.group(2), d) for m, d in dirs if m and (d / "runs.csv").exists()]
if (DIAG / "h3_smc" / "runs.csv").exists():
srcs.append((10.0, "full", DIAG / "h3_smc"))
if not srcs:
return None
rows = []
for snr, dens, d in srcs:
run = pd.read_csv(d / "runs.csv")
for (c, N), g in run.groupby(["c", "n_train"]):
mean = g.groupby("method")["band_rmse"].mean()
pcc = g.groupby("method")["band_pcc"].mean()
r = {"source": d.name, "snr_db": snr, "anchor_density": dens, "c": c, "n_train": N,
**{f"band_rmse_{m}": mean.get(m, np.nan) for m in TRAIN_METHODS},
**{f"band_pcc_{m}": pcc.get(m, np.nan) for m in TRAIN_METHODS}}
for a, b in (("M2-Sa", "B3d-Sa"), ("M2-S1", "B3d-S1"), ("M2-Sa", "B3c-R"), ("B3d-Sa", "B3c-R")):
if a in mean and b in mean:
x = g[g.method == a].set_index(["rid", "seed"])["band_rmse"]
y = g[g.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
r |= {f"ratio_{a}/{b}": mean[a] / mean[b],
f"seeds_better_{a}/{b}": int(((x - y).groupby("seed").mean() < 0).sum()),
f"rids_better_{a}/{b}": int(((x - y).groupby("rid").mean() < 0).sum()),
"n_seed": int(x.index.get_level_values("seed").nunique()),
"n_rid": int(x.index.get_level_values("rid").nunique())}
rows.append(r)
df = pd.DataFrame(rows)
if screen_tab is not None:
key = screen_tab[(screen_tab.wavelet == "estR") & (screen_tab.method == "SMC_g_acf")]
df = df.merge(key[["snr_db", "anchor_density", "c", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]],
on=["snr_db", "anchor_density", "c"], how="left")
df.to_csv(out / "train.csv", index=False)
return df
# ---------------------------------------------------------------- blur
BLUR_SIGMAS = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0]
def blur(P: np.ndarray, sigma_ms: float, dt_ms: float = 4.0, L: int = 512) -> np.ndarray:
"""Gaussian filter of Proposition 1, exp(−2π²σ²f²), along the time axis (reflect padding)."""
n = P.shape[1]
a = L // 2 - n // 2
m = P.mean(1, keepdims=True)
Pp = np.pad(P - m, ((0, 0), (a, L - n - a)), mode="reflect")
f = np.fft.rfftfreq(L, dt_ms / 1000)
out = np.fft.irfft(np.fft.rfft(Pp) * np.exp(-2 * np.pi ** 2 * (sigma_ms / 1000) ** 2 * f ** 2), L)
return out[:, a:a + n] + m
def blur_sources() -> list[tuple[str, Path]]:
"""(source, cells directory) pairs with saved predictions: h3_smc (SNR 10, full) and train_stress/snr*_* (same source names as train())."""
srcs = [("h3_smc", DIAG / "h3_smc" / "cells")]
if (DIAG / "train_stress").exists():
srcs += [(d.name, d / "cells") for d in sorted((DIAG / "train_stress").glob("snr*_*"))]
return [(s, d) for s, d in srcs if d.exists() and any(d.glob("r*_c*_n*.npz"))]
def blur_curve(out: Path) -> pd.DataFrame | None:
"""Band-RMSE penalty when (dev) Oracle predictions are blurred by σ: B(σ) = band_rmse(blur_σ(μ)) / band_rmse(μ).
This bounds the gain from removing label blur: if B3d labels have errors ~ N(0, σ²) and RML removes them fully,
the best attainable M2/B3d ratio is ≈ 1/B(σ). Computed per source (regime), since noisy inputs already make
predictions smoother. Dev realizations only (cells/*.npz of h3_smc and train_stress)."""
from ml_porosity.eval.metrics import band_metrics
rows = []
for src, cells in blur_sources():
for f in sorted(cells.glob("r*_c*_n*.npz")):
rid, c, N = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)", f.stem).groups()
z = np.load(f)
Y = z["y_true"].astype(float)
for k in (k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")):
P0 = z[k].astype(float)
b0 = np.mean([band_metrics(Y[i], P0[i], 6)["band_rmse"] for i in range(len(Y))])
for s in BLUR_SIGMAS:
Pb = blur(P0, s)
rows.append({"source": src, "rid": int(rid), "c": float(c), "n_train": int(N), "seed": k.split("/")[1],
"sigma_ms": s,
"ratio": np.mean([band_metrics(Y[i], Pb[i], 6)["band_rmse"] for i in range(len(Y))]) / b0})
if not rows:
return None
df = pd.DataFrame(rows).groupby(["source", "n_train", "sigma_ms"])["ratio"].agg(["mean", "min", "max", "size"]).reset_index()
df.to_csv(out / "blur.csv", index=False)
return df
def dose_response(tr: pd.DataFrame, bl: pd.DataFrame | None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""H2b on dev: M2-Sa/B3d-Sa ratio versus σ_post (c > 0), with the bound 1/B(σ_post) of the same source and N
(linear interpolation on the BLUR_SIGMAS grid; σ outside the grid is clamped to the edge). Spearman per N over
all cells."""
from scipy.stats import spearmanr
t = tr[(tr.c > 0) & tr["ratio_M2-Sa/B3d-Sa"].notna() & tr.sigma_post_ms.notna()].copy()
if bl is not None:
def bound(r):
b = bl[(bl.source == r.source) & (bl.n_train == r.n_train)]
return 1.0 / np.interp(r.sigma_post_ms, b.sigma_ms, b["mean"]) if len(b) else np.nan
t["bound_1/B"] = t.apply(bound, axis=1)
rows = []
for N, g in t.groupby("n_train"):
rho, p = spearmanr(g.sigma_post_ms, g["ratio_M2-Sa/B3d-Sa"]) if len(g) > 2 else (np.nan, np.nan)
wide, narrow = g[g.sigma_post_ms >= WIDE_MS], g[g.sigma_post_ms < WIDE_MS]
rows.append({"n_train": N, "cells": len(g), "spearman_rho": rho, "spearman_p": p,
"wide_cells": len(wide), "wide_ratio_mean": wide["ratio_M2-Sa/B3d-Sa"].mean(),
"wide_cells_ratio_lt1": int((wide["ratio_M2-Sa/B3d-Sa"] < 1).sum()),
"narrow_cells": len(narrow), "narrow_ratio_max": narrow["ratio_M2-Sa/B3d-Sa"].max()})
return t, pd.DataFrame(rows)
# ---------------------------------------------------------------- report
def md(df: pd.DataFrame, fmt: str = ".3f") -> str:
return df.to_markdown(index=False, floatfmt=fmt)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--only", nargs="+", default=None, choices=["screen", "stability", "sigma_a", "f3", "train", "blur"])
args = ap.parse_args()
want = lambda s: args.only is None or s in args.only
out = DIAG / "p3dev"
out.mkdir(parents=True, exist_ok=True)
pd.set_option("display.width", 250)
lines = ["# Dev experiments for protocol_p3 (realizations 900/901)", ""]
tab = screen(out) if want("screen") or want("train") else None
if tab is not None:
key = tab[(tab.wavelet == "estR") & (tab.method == "SMC_g_acf")]
show = key[["snr_db", "anchor_density", "c", "sigma_post_ms", "sigma_post_min", "warp_rmse_ms", "warp_cov90",
"r_post", "r_true", "kappa_post", "gamma", "b3c_warp_rmse_ms"]].sort_values(["c", "anchor_density", "snr_db"])
lines += ["## Stress grid: SMC posterior (estR, γ = 1/κ)", "", md(show), "",
f"Wide cells (σ_post ≥ {WIDE_MS} ms): {len(key[key.sigma_post_ms >= WIDE_MS])}/{len(key)}", ""]
print(show.round(3).to_string(index=False))
if want("stability") and (st := stability(out)) is not None:
t = stability_table(st)
t["pass"] = t.d_p95_max <= STAB_MS
lines += ["## Run-to-run stability of SMC", "", md(t), "",
f"Criterion: p95 of |Δτ̄(t)| ≤ {STAB_MS} ms in every cell (column d_p95_max).", ""]
print(t.round(3).to_string(index=False))
if want("sigma_a") and (sa := sigma_a(out)) is not None:
show = sa[sa.method == "SMC_g_acf"][["sigma_a_reg", "c", "wavelet", "sigma_post_ms", "warp_rmse_ms", "warp_cov90",
"r_post", "gamma"]]
lines += ["## Registration σ_a (data generated with σ_a = 7 ms)", "", md(show), ""]
print(show.round(3).to_string(index=False))
if want("f3") and (r := f3(out)) is not None:
ft, ph = r
lines += ["## F3 (descriptive only)", "", md(ft), "", md(ph), ""]
print(ft.round(3).to_string(index=False))
print(ph.to_string(index=False))
tr = train(out, tab) if want("train") else None
if tr is not None:
cols = [c for c in tr.columns if c.startswith(("source", "snr", "anchor", "c", "n_train", "sigma_post", "ratio_",
"seeds_better", "rids_better"))
or c in {f"band_rmse_{m}" for m in ("Oracle", "B3c-R", "B3d-Sa", "M2-Sa")}]
lines += ["## Training in the wide cells and H3", "", md(tr[cols]), ""]
print(tr[cols].round(3).to_string(index=False))
for src in sorted(set(tr.source)):
for d in (DIAG / "train_stress" / src, DIAG / src):
if (d / "h3.json").exists():
h3 = pd.DataFrame(json.loads((d / "h3.json").read_text())).T
lines += [f"### H3 — {src}", "", md(h3.reset_index(names="ensemble/cell")), ""]
break
bl = blur_curve(out) if want("blur") else None
if bl is not None:
lines += ["## Band-RMSE penalty from blur (Proposition 1) on dev Oracle predictions", "", md(bl), "",
"B(σ) = band_rmse(blurred by σ) / band_rmse(original); 1/B(σ) is the best attainable M2/B3d ratio "
"if RML removes all blur.", ""]
print(bl.round(4).to_string(index=False))
if want("train") and tr is not None:
cells, dr = dose_response(tr, bl)
cols = ["source", "c", "n_train", "sigma_post_ms", "ratio_M2-Sa/B3d-Sa", "seeds_better_M2-Sa/B3d-Sa",
"rids_better_M2-Sa/B3d-Sa", *(["bound_1/B"] if "bound_1/B" in cells else [])]
cells = cells[cols].sort_values(["n_train", "sigma_post_ms"])
cells.to_csv(out / "dose_response.csv", index=False)
lines += ["## H2b on dev: M2-Sa/B3d-Sa versus σ_post", "", md(cells), "", md(dr), ""]
print(cells.round(3).to_string(index=False))
print(dr.round(3).to_string(index=False))
(out / "summary.md").write_text("\n".join(lines))
print(f"→ {out}")
if __name__ == "__main__":
main()

View File

@@ -1,10 +1,14 @@
#!/usr/bin/env bash
# Chạy toàn bộ pipeline P0: kiểm hash dữ liệu → dựng giếng → QC TD → train thử B2 → unit test.
# Run the full P0 pipeline: data hash check → build wells → TD QC → B2 smoke training → unit tests.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
"$PY" scripts/00_data_manifest.py --check
"$PY" scripts/01_build_wells.py
"$PY" scripts/02_td_qc.py
"$PY" scripts/03_train.py --config configs/b2_smoke.yaml
"$PY" -m pytest -q
# Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p0/, one subdirectory per step, one row per step in
# logs/index.csv (ml_porosity/runlog.py).
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p0 -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog -- "$@"; }
step "$PY" scripts/00_data_manifest.py --check
step "$PY" scripts/01_build_wells.py
step "$PY" scripts/02_td_qc.py
step "$PY" scripts/03_train.py --config configs/b2_smoke.yaml
step "$PY" -m pytest -q

View File

@@ -1,10 +1,14 @@
#!/usr/bin/env bash
# Chạy P1: dựng giếng → wavelet/tie QC → LOWO (cần protocol.yaml khớp hash) → tổng hợp.
# Run P1: build wells → wavelet/tie QC → LOWO (requires protocol.yaml to match its hash) → summary.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
"$PY" scripts/01_build_wells.py
"$PY" scripts/04_wavelet_tie.py
"$PY" scripts/05_lowo.py --only B0a,B0b,B1
"$PY" scripts/05_lowo.py --only B2,B3a,B3b --workers "${WORKERS:-12}"
"$PY" scripts/06_summarize_p1.py
# Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p1/, one subdirectory per step, one row per step in
# logs/index.csv (ml_porosity/runlog.py).
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p1 -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog -- "$@"; }
step "$PY" scripts/01_build_wells.py
step "$PY" scripts/04_wavelet_tie.py
step "$PY" scripts/05_lowo.py --only B0a,B0b,B1
step "$PY" scripts/05_lowo.py --only B2,B3a,B3b --workers "${WORKERS:-12}"
step "$PY" scripts/06_summarize_p1.py

26
scripts/run_p2.sh Executable file
View File

@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Run P2: fit F3 warp prior → D2 QC → unit tests → dev round (budget selection) → [lock protocol_p2] → main grid
# → H1 → summary. GPU jobs run on cuda:1 (shared machine; override with DEVICE=...).
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
# Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p2/, one subdirectory per step, one row per step in
# logs/index.csv (ml_porosity/runlog.py). Re-running after an interruption: 11_run_d2 skips cells that already have a CSV.
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p2 -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog -- "$@"; }
DEVICE="${DEVICE:-cuda:1}"
WORKERS="${WORKERS:-6}"
# warp_prior_f3.json is an input whose hash is recorded in protocol_p2: do not regenerate if present (changing it ⇒ new protocol lock)
[[ -f outputs/p2/warp_prior_f3.json ]] || step "$PY" scripts/09_fit_warp_prior_f3.py
step "$PY" scripts/10_build_d2.py
step "$PY" -m pytest -q tests/test_losses.py tests/test_registration.py tests/test_d2.py
if ! sha256sum --status -c configs/protocol_p2.sha256 2>/dev/null; then
step "$PY" scripts/11_run_d2.py --dev --workers "$WORKERS" --device "$DEVICE"
step "$PY" scripts/13_summarize_p2.py --mode dev
echo "Dev round finished. Copy training.budgets from outputs/p2/dev/budgets.json into configs/protocol_p2.yaml, lock it with" >&2
echo " sha256sum configs/protocol_p2.yaml > configs/protocol_p2.sha256 (and a git tag), then re-run this script." >&2
exit 1
fi
step "$PY" scripts/11_run_d2.py --main --workers "$WORKERS" --device "$DEVICE"
step "$PY" scripts/12_h1_blur.py --workers "$WORKERS" --device "$DEVICE"
step "$PY" scripts/13_summarize_p2.py --mode main

83
scripts/run_p3_dev.sh Executable file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env bash
# Dev experiments in preparation for protocol_p3 (plan §10): dev realizations 900/901 only; main grid 0–7 is not used.
# scripts/run_p3_dev.sh # all stages in order
# scripts/run_p3_dev.sh stability sigma_a # only the named stages
# screen SMC posterior over SNR {10, 5, 0, −5} dB × anchor density {full, half, topbottom} × c {1, 2} × N {4, 16}
# train training (scripts/15) in the screen cells with σ_post ≥ 1.5 ms (outputs/p2/diag/p3dev/wide_cells.txt,
# written by scripts/17): M2-Sa, B3d-Sa, B3c-R, Oracle… 5 seeds, fixed budgets
# stability 4 independent SMC runs with P = 256 and 2 with P = 1024 (SNR 10, full): warp difference between runs
# stability_m5 as stability at SNR −5 dB, full (the F3-like regime): 2 runs with P = 1024 (the chosen setting)
# b3d_old supplementary: old protocol_p2 B3d (point-tie competitor for H2a) at SNR 10/0/−5, full, same seeds and budgets
# sigma_a registration with σ_a = 3.5 and 14 ms when the data are generated with σ_a = 7 ms (plan §5.5)
# train_sa training on the sigma_a posteriors (c 1 2; every method registered with the misspecified σ_a): does H2a hold?
# f3 SMC posterior on the 4 F3 wells (descriptive only, scripts/16)
# h3 H3 with the SMC posterior: 5-seed ensembles of M2-Sa, B3d-Sa… vs B5 in the protocol_p2 setting (c 1, 2)
# GPU jobs run on cuda:1 (override with DEVICE=...). Re-running after an interruption: scripts 14, 15 skip jobs that already have a CSV.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p3dev -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog "$@" || echo "step failed: $*" >&2; }
DEVICE="${DEVICE:-cuda:1}"
WORKERS="${WORKERS:-6}"
# The machine environment presets OMP_NUM_THREADS=40 (also MKL, OpenBLAS): unless overridden, each worker opens a 40-thread pool.
THREADS="${THREADS:-2}"
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
NUMBA_NUM_THREADS=$THREADS
OUT=outputs/p2/diag
POST=(scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device "$DEVICE")
TRAIN=(scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device "$DEVICE" --variants a 1
--methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from "$OUT/train/budgets.json" --save-preds)
for stage in ${@:-screen train stability sigma_a f3 h3}; do
case "$stage" in
screen)
for snr in 10 5 0 -5; do
for dens in full half topbottom; do
step -n "stress_snr${snr}_${dens}" -- "$PY" "${POST[@]}" --snr "$snr" --anchor-density "$dens" \
--wavelets estR true --workers "$WORKERS" --out-dir "$OUT/stress/snr${snr}_${dens}"
done
done ;;
train)
CUDA_VISIBLE_DEVICES= "$PY" scripts/17_summarize_p3_dev.py --only screen > /dev/null
while read -r snr dens cs <&3; do
# shellcheck disable=SC2086 # cs is a list of c values and must be word-split
step -n "train_snr${snr}_${dens}" -- "$PY" "${TRAIN[@]}" --snr "$snr" --anchor-density "$dens" --c $cs \
--workers 4 --post-dir "$OUT/stress/snr${snr}_${dens}" --out-dir "$OUT/train_stress/snr${snr}_${dens}"
done 3< "$OUT/p3dev/wide_cells.txt" ;;
stability)
step -n stab_p256 -- "$PY" "${POST[@]}" --smc-seeds 0 1 2 3 --wavelets estR --workers "$WORKERS" \
--out-dir "$OUT/stability/p256"
step -n stab_p1024 -- "$PY" "${POST[@]}" --particles 1024 --smc-seeds 0 1 --wavelets estR --workers 4 \
--gpu-mem-gb 6 --out-dir "$OUT/stability/p1024" ;;
stability_m5)
step -n stab_p1024_snr-5 -- "$PY" "${POST[@]}" --snr -5 --anchor-density full --particles 1024 --smc-seeds 0 1 \
--wavelets estR --workers 4 --gpu-mem-gb 6 --out-dir "$OUT/stability/p1024_snr-5" ;;
b3d_old)
B3D=(scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device "$DEVICE" --variants a
--methods B3d --budgets-from "$OUT/train/budgets.json" --workers 4)
step -n b3d_snr10_full -- "$PY" "${B3D[@]}" --post-dir "$OUT/posterior_gpu" --out-dir "$OUT/train_b3d/snr10_full"
for snr in 0 -5; do
step -n "b3d_snr${snr}_full" -- "$PY" "${B3D[@]}" --snr "$snr" --anchor-density full \
--post-dir "$OUT/stress/snr${snr}_full" --out-dir "$OUT/train_b3d/snr${snr}_full"
done ;;
sigma_a)
for sa in 3.5 14; do
step -n "stress_sa${sa}" -- "$PY" "${POST[@]}" --sigma-a-reg "$sa" --wavelets estR true --workers "$WORKERS" \
--out-dir "$OUT/stress/snr10_full_sa${sa}"
done ;;
train_sa)
for sa in 3.5 14; do
step -n "train_sa${sa}" -- "$PY" scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 \
--device "$DEVICE" --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --sigma-a-reg "$sa" \
--budgets-from "$OUT/train/budgets.json" --workers 4 --post-dir "$OUT/stress/snr10_full_sa${sa}" \
--out-dir "$OUT/train_sa/sa${sa}"
done ;;
f3)
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 step -n f3_posterior -- "$PY" scripts/16_f3_posterior.py \
--device "$DEVICE" ;;
h3)
step -n h3_smc -- "$PY" "${TRAIN[@]}" --c 1 2 --workers 4 --post-dir "$OUT/posterior_gpu" --out-dir "$OUT/h3_smc" ;;
*) echo "unknown stage: $stage" >&2; exit 2 ;;
esac
done

8
scripts/runlog.sh Executable file
View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Run a command, saving log + runtime to logs/runs/<timestamp>_<name>/ and appending one row to logs/index.csv
# (details: ml_porosity/runlog.py). Examples:
# scripts/runlog.sh scripts/15_diag_train.py --rids 900 901 --device cuda:1 # .py files are run with $PY
# scripts/runlog.sh -n h1_rerun --note "re-run after fixing X" -- scripts/12_h1_blur.py --device cuda:1
# scripts/runlog.sh ls # most recent runs
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec "${PY:-$ROOT/.venv/bin/python}" -m ml_porosity.runlog "$@"