P0 + P1: ml_porosity package, audited F3 data, LOWO baselines, protocol v2
P0 - ml_porosity/: survey geometry, LAS/TDR/SEG-Y readers (4 ms delay fix, invalid time scalar, header LUT for incomplete cubes), anti-aliased log-to-time resampling, CNN-GRU v2 with the thesis loss, 41+ unit tests. - Full F3 Demo 2023 under data/ (text well/fault files tracked, bulk data ignored); the filtered copy and its cleanup notes are removed. - SHA-256 manifests for F3, Volve, NLOG and the thesis outputs. P1 - configs/protocol.yaml v2, locked by SHA-256 at 2026-10-26T04:28:09Z, before the first LOWO run (04:30:50Z); 05_lowo.py refuses to run on a hash mismatch. This commit postdates the runs. - Wavelet/synthetic tie QC, residual misregistration, LOWO 5 seeds for B0a, B0b, B1, B2, B3a, B3b (scripts 04-06); gate G-A: no pivot. - Volve D3: horizons, well picks, checkshots and the ST10010 cube read from data/Volve (scripts/07). - D-1 label check against measured NLOG density (scripts/08): PHIE_DT stays the primary label. - docs/plan.md, Volve and NLOG inventories, report.html. Full-text reference PDFs in refs/ stay local (ignored). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
83
scripts/00_data_manifest.py
Normal file
83
scripts/00_data_manifest.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Ghi manifest SHA-256 cho một bộ dữ liệu và đối chiếu với manifest đã commit.
|
||||
|
||||
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
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
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"),
|
||||
}
|
||||
|
||||
|
||||
def sha256(path: Path, chunk: int = 1 << 22) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
while block := f.read(chunk):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def scan(root: Path) -> dict[str, dict]:
|
||||
files = sorted(p for p in root.rglob("*") if p.is_file())
|
||||
with ThreadPoolExecutor(max_workers=8) as ex:
|
||||
digests = list(ex.map(sha256, files))
|
||||
return {
|
||||
p.relative_to(root).as_posix(): {"size_bytes": p.stat().st_size, "sha256": d}
|
||||
for p, d in zip(files, digests)
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--check", action="store_true")
|
||||
ap.add_argument("--dataset", choices=sorted(DATASETS), default="f3")
|
||||
args = ap.parse_args()
|
||||
|
||||
root_fn, manifest_name, description = DATASETS[args.dataset]
|
||||
manifest = REPO_ROOT / "data_manifest" / manifest_name
|
||||
root = root_fn()
|
||||
current = scan(root)
|
||||
|
||||
if args.check:
|
||||
ref = json.loads(manifest.read_text())["files"]
|
||||
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 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")
|
||||
return 1 if (missing or changed) else 0
|
||||
|
||||
out = {
|
||||
"dataset": description,
|
||||
"root": root.relative_to(REPO_ROOT).as_posix() if root.is_relative_to(REPO_ROOT) else str(root),
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"n_files": len(current),
|
||||
"total_bytes": sum(v["size_bytes"] for v in current.values()),
|
||||
"files": current,
|
||||
}
|
||||
manifest.parent.mkdir(parents=True, exist_ok=True)
|
||||
manifest.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n")
|
||||
print(f"{out['n_files']} file, {out['total_bytes'] / 1e9:.2f} GB -> {manifest.relative_to(REPO_ROOT)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
116
scripts/01_build_wells.py
Normal file
116
scripts/01_build_wells.py
Normal file
@@ -0,0 +1,116 @@
|
||||
"""Dựng bộ dữ liệu giếng F3 trong miền thời gian seismic.
|
||||
|
||||
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:
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import yaml
|
||||
|
||||
from ml_porosity.data.geometry import SurveyGeometry
|
||||
from ml_porosity.data.horizons import F3_HORIZONS, horizon_at
|
||||
from ml_porosity.data.las_io import LEGACY_IL_XL, Well, load_td_source, load_well
|
||||
from ml_porosity.data.resample import log_to_time
|
||||
from ml_porosity.data.seismic_io import SeismicCube
|
||||
from ml_porosity.data.tdr import TDR, calibrate_to_anchors, legacy_sonic_tdr, sonic_tdr
|
||||
from ml_porosity.paths import REPO_ROOT, f3_root, outputs_dir
|
||||
|
||||
|
||||
def build_tdrs(well: Well, names: list[str]) -> dict[str, TDR]:
|
||||
cs = well.checkshot
|
||||
dt = well.curve("DT")
|
||||
out = {}
|
||||
for name in names:
|
||||
if name == "legacy":
|
||||
out[name] = legacy_sonic_tdr(well.md, dt)
|
||||
elif name == "calibrated":
|
||||
base = sonic_tdr(well.md, dt, md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
|
||||
out[name] = calibrate_to_anchors(base, cs.md, cs.twt_ms)
|
||||
elif name == "anchors":
|
||||
out[name] = TDR.from_pairs(cs.to_numpy(), "anchors")
|
||||
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}")
|
||||
return out
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--config", default=str(REPO_ROOT / "configs" / "d1_f3.yaml"))
|
||||
cfg = yaml.safe_load(open(ap.parse_args().config))
|
||||
|
||||
geom = SurveyGeometry.from_survey(f3_root())
|
||||
t0, t1 = cfg["time_window_ms"]
|
||||
e0, e1 = cfg["ext_window_ms"]
|
||||
arrays: dict[str, np.ndarray] = {}
|
||||
summary = {"config": cfg, "wells": {}}
|
||||
|
||||
with SeismicCube() as cube:
|
||||
win = cube.window(e0, e1)
|
||||
t_win = cube.times_ms[win]
|
||||
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.
|
||||
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]
|
||||
tdrs = build_tdrs(w, cfg["tdrs"])
|
||||
|
||||
p = f"{name}/"
|
||||
arrays.update({
|
||||
p + "seismic_patch": patch,
|
||||
p + "times_ms": t_win,
|
||||
p + "main_mask": main,
|
||||
p + "il": np.int32(il), p + "xl": np.int32(xl),
|
||||
p + "x": np.float64(w.x), p + "y": np.float64(w.y),
|
||||
p + "anchors_md": w.checkshot.md.to_numpy(),
|
||||
p + "anchors_twt_ms": w.checkshot.twt_ms.to_numpy(),
|
||||
})
|
||||
coverage = {}
|
||||
for tname, tdr in tdrs.items():
|
||||
arrays[p + f"tdr/{tname}/md"] = tdr.md
|
||||
arrays[p + f"tdr/{tname}/twt_ms"] = tdr.twt_ms
|
||||
for c in cfg["curves"]:
|
||||
v = log_to_time(w.md, w.curve(c), tdr, t_win, **cfg["resample"])
|
||||
arrays[p + f"{tname}/{c}"] = v
|
||||
coverage[f"{tname}/{c}"] = round(float(np.isfinite(v[main]).mean()), 3)
|
||||
for h in F3_HORIZONS:
|
||||
arrays[p + f"horizon/{h}"] = np.float64(horizon_at(h, geom, [(il, xl)])[0])
|
||||
|
||||
info = {"x": w.x, "y": w.y, "kb": w.kb, "il": il, "xl": xl,
|
||||
"n_anchors_in_window": int(w.checkshot.twt_ms.between(t0, t1).sum()),
|
||||
"label_coverage": coverage}
|
||||
if name in LEGACY_IL_XL:
|
||||
lil, lxl = LEGACY_IL_XL[name]
|
||||
lx, ly = geom.bin_to_xy(lil, lxl)
|
||||
info["legacy_il_xl"] = [lil, lxl]
|
||||
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)"
|
||||
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%}")
|
||||
|
||||
out = outputs_dir()
|
||||
np.savez_compressed(out / "f3_wells.npz", **arrays)
|
||||
(out / "f3_wells_summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
|
||||
print(f"-> {out / 'f3_wells.npz'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
70
scripts/02_td_qc.py
Normal file
70
scripts/02_td_qc.py
Normal file
@@ -0,0 +1,70 @@
|
||||
"""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).
|
||||
|
||||
python scripts/02_td_qc.py
|
||||
|
||||
Đầu ra: outputs/figures/td_drift.png, outputs/td_qc.csv
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.data.las_io import F3_WELLS, load_td_source, load_well
|
||||
from ml_porosity.data.tdr import TDR, legacy_sonic_tdr, misfit_at_anchors
|
||||
from ml_porosity.paths import outputs_dir
|
||||
|
||||
WINDOW_MS = (600.0, 1100.0)
|
||||
SOURCES = {
|
||||
"legacy": "Tích phân DT (luận văn)",
|
||||
"wlt": "OpendTect .wlt",
|
||||
"dt_model": "DT_model",
|
||||
}
|
||||
COLORS = {"legacy": "#c0392b", "wlt": "#1f5fbf", "dt_model": "#7a7a7a"}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
rows = []
|
||||
fig, axes = plt.subplots(1, len(F3_WELLS), figsize=(13, 4.8), sharey=True, constrained_layout=True)
|
||||
for ax, name in zip(axes, F3_WELLS):
|
||||
w = load_well(name)
|
||||
cs = w.checkshot
|
||||
tdrs = {
|
||||
"legacy": legacy_sonic_tdr(w.md, w.curve("DT")),
|
||||
"wlt": TDR.from_pairs(load_td_source(name, "wlt"), drop_flat=True),
|
||||
"dt_model": TDR.from_pairs(load_td_source(name, "dt_model")),
|
||||
}
|
||||
inwin = cs.twt_ms.between(*WINDOW_MS).to_numpy()
|
||||
for key, tdr in tdrs.items():
|
||||
d = misfit_at_anchors(tdr, cs.md, cs.twt_ms)
|
||||
ax.plot(d, cs.twt_ms, "o-", ms=3.5, lw=1.2, color=COLORS[key], label=SOURCES[key])
|
||||
dw = d[inwin]
|
||||
rows.append({
|
||||
"well": name, "source": key, "n_anchors": int(inwin.sum()),
|
||||
"min_ms": dw.min(), "max_ms": dw.max(), "span_ms": dw.max() - dw.min(),
|
||||
"mean_ms": dw.mean(), "max_abs_ms": np.abs(dw).max(),
|
||||
})
|
||||
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.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)
|
||||
|
||||
out = outputs_dir()
|
||||
(out / "figures").mkdir(exist_ok=True)
|
||||
fig.savefig(out / "figures" / "td_drift.png", dpi=150)
|
||||
df = pd.DataFrame(rows).round(1)
|
||||
df.to_csv(out / "td_qc.csv", index=False)
|
||||
print(df.to_string(index=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
120
scripts/03_train.py
Normal file
120
scripts/03_train.py
Normal file
@@ -0,0 +1,120 @@
|
||||
"""Huấn luyện CNN–GRU v2 với loss gốc trên bộ dữ liệu từ 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>/.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import yaml
|
||||
|
||||
from ml_porosity.eval.metrics import point_metrics
|
||||
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
|
||||
from ml_porosity.models.cnn_gru import CNNGRU
|
||||
from ml_porosity.paths import outputs_dir
|
||||
|
||||
|
||||
def zscore_rows(X: np.ndarray) -> np.ndarray:
|
||||
mu = X.mean(axis=-1, keepdims=True)
|
||||
sd = X.std(axis=-1, keepdims=True) + 1e-8
|
||||
return (X - mu) / sd
|
||||
|
||||
|
||||
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")
|
||||
return X, Y
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--config", required=True)
|
||||
ap.add_argument("--epochs", type=int)
|
||||
ap.add_argument("--seed", type=int)
|
||||
args = ap.parse_args()
|
||||
cfg = yaml.safe_load(open(args.config))
|
||||
if args.epochs is not None:
|
||||
cfg["epochs"] = args.epochs
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
|
||||
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")
|
||||
|
||||
torch.manual_seed(cfg["seed"])
|
||||
np.random.seed(cfg["seed"])
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
D = np.load(outputs_dir() / cfg["dataset"])
|
||||
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
|
||||
|
||||
def T(a):
|
||||
return torch.tensor(a, dtype=torch.float32, device=device)
|
||||
|
||||
xtr, ytr = T(Xtr), T((Ytr - mu) / sd)[:, None]
|
||||
xva, yva = T(Xva), T((Yva - mu) / sd)[:, None]
|
||||
|
||||
model = CNNGRU(in_ch=Xtr.shape[1], d=cfg["d_channels"], pdrop=cfg["p_dropout"]).to(device)
|
||||
loss_fn = LegacyV2Loss()
|
||||
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
|
||||
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode="min", factor=0.5, patience=50)
|
||||
|
||||
run_dir = outputs_dir() / "runs" / f"{Path(args.config).stem}_s{cfg['seed']}"
|
||||
run_dir.mkdir(parents=True, exist_ok=True)
|
||||
best, best_ep, t_start = float("inf"), 0, time.time()
|
||||
for ep in range(1, cfg["epochs"] + 1):
|
||||
model.train()
|
||||
opt.zero_grad()
|
||||
pred = model(xtr)
|
||||
if ep <= 50: # nhiễu nhỏ những epoch đầu như luận văn
|
||||
pred = pred + 0.01 * torch.randn_like(pred)
|
||||
loss = loss_fn(pred, ytr)
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
|
||||
opt.step()
|
||||
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
vloss = float(loss_fn(model(xva), yva))
|
||||
sched.step(vloss)
|
||||
if vloss < best:
|
||||
best, best_ep = vloss, ep
|
||||
torch.save(model.state_dict(), run_dir / "best.pt")
|
||||
if ep == 1 or ep % 50 == 0:
|
||||
print(f"ep {ep:4d} train {loss.item():.4f} val {vloss:.4f} best {best:.4f} @ {best_ep}")
|
||||
|
||||
model.load_state_dict(torch.load(run_dir / "best.pt", map_location=device))
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
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
|
||||
|
||||
result = {"config": cfg, "device": device, "best_epoch": best_ep, "best_val_loss": best,
|
||||
"train_seconds": round(time.time() - t_start, 1),
|
||||
"test": m, "test_constant_train_mean": m_const}
|
||||
(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}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
162
scripts/04_wavelet_tie.py
Normal file
162
scripts/04_wavelet_tie.py
Normal file
@@ -0,0 +1,162 @@
|
||||
"""Wavelet, synthetic seismogram 4 giếng và misregistration còn lại sau tie (P1, cổng 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.
|
||||
|
||||
Đầu ra: outputs/tie_qc.csv, outputs/tie_local_shifts.csv, outputs/figures/ties.png,
|
||||
outputs/figures/wavelets.png, outputs/wavelets.npz
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.data.las_io import F3_WELLS
|
||||
from ml_porosity.data.synthetic import best_shift, local_shifts, ncc, reflectivity_from_ai, shift_signal
|
||||
from ml_porosity.data.wavelet import convolve_same, estimate_wavelet_ls, rotate_phase, statistical_wavelet
|
||||
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)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
D = np.load(outputs_dir() / "f3_wells.npz")
|
||||
seis = {w: D[f"{w}/seismic_patch"][4].astype(float) for w in F3_WELLS}
|
||||
t = D[f"{F3_WELLS[0]}/times_ms"]
|
||||
main_m = D[f"{F3_WELLS[0]}/main_mask"]
|
||||
|
||||
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.
|
||||
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).
|
||||
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}")
|
||||
|
||||
rows, lrows = [], []
|
||||
fig, axes = plt.subplots(1, 2 * len(F3_WELLS), figsize=(16, 8), sharey=True,
|
||||
gridspec_kw={"width_ratios": [2, 1] * len(F3_WELLS)}, constrained_layout=True)
|
||||
colors = {"calibrated": "#1f5fbf", "wlt": "#2a9d8f", "anchors": "#8a5cc2", "legacy": "#c0392b"}
|
||||
for k, w in enumerate(F3_WELLS):
|
||||
s = seis[w]
|
||||
ax_tr, ax_sh = axes[2 * k], axes[2 * k + 1]
|
||||
ax_tr.plot(s / np.std(s[main_m]), t, "k", lw=1.0, label="seismic")
|
||||
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 = (-np.inf, 0.0, 0.0)
|
||||
for p in range(-180, 180, 10):
|
||||
syn_p = convolve_same(r_w, rotate_phase(w_stat, p))
|
||||
for sh in np.arange(-40, 40.25, 0.5):
|
||||
rr = ncc(shift_signal(syn_p, sh, DT)[main_m], s[main_m])
|
||||
if rr > best[0]:
|
||||
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.
|
||||
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)
|
||||
good = inwin & (lr > 0.5)
|
||||
rows.append({"well": w, "tdr": tdr, "r_common_phase_shift0": round(r0, 3),
|
||||
"best_phase_deg": p_best, "best_bulk_shift_ms": sh_best, "r_best_tie": round(r_best, 3),
|
||||
"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.
|
||||
rng = np.random.default_rng(0)
|
||||
floor = []
|
||||
for _ in range(20):
|
||||
nz = convolve_same(rng.standard_normal(len(syn)), w_stat)
|
||||
nz *= np.std(syn[main_m]) / np.std(nz[main_m]) * np.sqrt(1 / max(r_best, 0.05) ** 2 - 1)
|
||||
_, ls0, lr0 = local_shifts(syn, syn + nz, DT, win_ms=120, hop_ms=20, max_ms=24)
|
||||
g0 = inwin & (lr0 > 0.5)
|
||||
if g0.any():
|
||||
floor.append(np.sqrt(np.mean(ls0[g0] ** 2)))
|
||||
rows[-1]["noise_floor_rms_ms"] = round(float(np.median(floor)), 1) if floor else np.nan
|
||||
for tci, lsi, lri in zip(tc[inwin], ls[inwin], lr[inwin]):
|
||||
lrows.append({"well": w, "tdr": tdr, "t_ms": tci, "shift_ms": lsi, "r": round(lri, 3)})
|
||||
if tdr in ("calibrated", "legacy"):
|
||||
ax_tr.plot(syn / np.std(syn[main_m]) + (3 if tdr == "calibrated" else 6), t,
|
||||
color=colors[tdr], lw=1.0, label=f"synthetic ({tdr})")
|
||||
ax_sh.plot(ls[inwin], tc[inwin], "o-", ms=3, color=colors[tdr], label=tdr,
|
||||
alpha=1.0 if tdr in ("calibrated", "legacy") else 0.6)
|
||||
ax_tr.set_title(f"{w}", fontsize=10)
|
||||
ax_tr.set_xticks([])
|
||||
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)
|
||||
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])
|
||||
axes[0].set_ylabel("TWT (ms)")
|
||||
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)
|
||||
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.set_xlabel("ms")
|
||||
ax.legend()
|
||||
ax.grid(alpha=0.3)
|
||||
fw.savefig(out / "figures" / "wavelets.png", dpi=130)
|
||||
np.savez(out / "wavelets.npz", statistical=w_stat, statistical_rotated=w_use, phase_deg=phase, ls_all_wells=w_ls)
|
||||
|
||||
df = pd.DataFrame(rows)
|
||||
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")
|
||||
|
||||
# Đố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).
|
||||
names = {"FS8": "FS8", "FS7": "FS7", "Truncation": "Truncation 1", "FS6": "FS6", "MFS4": "MFS4"}
|
||||
from ml_porosity.data.las_io import load_well
|
||||
hrows = []
|
||||
for w in F3_WELLS:
|
||||
mk = load_well(w).markers
|
||||
cs = load_well(w).checkshot
|
||||
for h, mname in names.items():
|
||||
th = float(D[f"{w}/horizon/{h}"])
|
||||
md = mk.loc[mk.name == mname, "md"]
|
||||
if md.empty or not np.isfinite(th):
|
||||
continue
|
||||
tm = float(np.interp(md.iloc[0], cs.md, cs.twt_ms))
|
||||
hrows.append({"well": w, "horizon": h, "horizon_ms": round(th, 1), "marker_ms": round(tm, 1),
|
||||
"diff_ms": round(th - tm, 1)})
|
||||
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")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
261
scripts/05_lowo.py
Normal file
261
scripts/05_lowo.py
Normal file
@@ -0,0 +1,261 @@
|
||||
"""LOWO cho các baseline P1 theo 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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import itertools
|
||||
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.yaml"
|
||||
|
||||
|
||||
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")
|
||||
return yaml.safe_load(PROTO.read_text()) | {"sha256": actual}
|
||||
|
||||
|
||||
class Data:
|
||||
def __init__(self, proto: dict):
|
||||
D = np.load(outputs_dir() / "f3_wells.npz")
|
||||
self.wells = proto["data"]["wells"]
|
||||
w0 = self.wells[0]
|
||||
self.t = D[f"{w0}/times_ms"]
|
||||
self.m = D[f"{w0}/main_mask"].astype(bool)
|
||||
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)."""
|
||||
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)
|
||||
|
||||
def y(self, w, tdr, label):
|
||||
return self.D[f"{w}/{tdr}/{label}"][self.m]
|
||||
|
||||
def ext(self, w, key):
|
||||
return self.D[f"{w}/{key}"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- metric
|
||||
|
||||
|
||||
def evaluate(d: Data, test: str, label: str, mu, sigma=None) -> list[dict]:
|
||||
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
|
||||
|
||||
rows = []
|
||||
for ref in ["calibrated"] + d.proto["registration"]["sensitivity_references"]:
|
||||
yt = 100 * d.y(test, ref, label)
|
||||
mp = 100 * np.asarray(mu)
|
||||
r = {"reference": ref} | point_metrics(yt, mp) | band_metrics(yt, mp, d.proto["metrics"]["bands"]["f_c_hz"])
|
||||
if sigma is not None:
|
||||
r |= gaussian_metrics(yt, mp, 100 * np.asarray(sigma))
|
||||
rows.append(r)
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- B0a, B0b, B1 (CPU, nhanh)
|
||||
|
||||
|
||||
def run_classical(d: Data, label: str, test: str, seeds: list[int]):
|
||||
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
|
||||
from sklearn.linear_model import LinearRegression, Ridge
|
||||
from sklearn.pipeline import make_pipeline
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
from ml_porosity.baselines.attributes import trace_attributes
|
||||
from ml_porosity.baselines import inversion as inv
|
||||
|
||||
P = d.proto["methods"]
|
||||
train = [w for w in d.wells if w != test]
|
||||
out, sel = [], []
|
||||
tt = d.t[d.m]
|
||||
|
||||
def ytrain(ws):
|
||||
return np.concatenate([d.y(w, "calibrated", label) for w in ws])
|
||||
|
||||
# B0a: trend tuyến tính theo 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
|
||||
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)
|
||||
return trace_attributes(p.mean(0), d.t)[d.m]
|
||||
|
||||
F = {w: feats(w) for w in d.wells}
|
||||
Ftr = np.vstack([F[w] for w in train])
|
||||
ytr = ytrain(train)
|
||||
|
||||
def inner_mse(make):
|
||||
errs = []
|
||||
for v in train:
|
||||
tr2 = [w for w in train if w != v]
|
||||
mdl = make().fit(np.vstack([F[w] for w in tr2]), ytrain(tr2))
|
||||
errs.append(np.mean((mdl.predict(F[v]) - d.y(v, "calibrated", label)) ** 2))
|
||||
return float(np.mean(errs))
|
||||
|
||||
grid = P["B0b"]["models"]["ridge"]["alpha_grid"]
|
||||
scores = [inner_mse(lambda a=a: make_pipeline(StandardScaler(), Ridge(alpha=a))) for a in grid]
|
||||
alpha = grid[int(np.argmin(scores))]
|
||||
sel.append({"label": label, "test_well": test, "method": "B0b-ridge", "param": "alpha", "value": alpha})
|
||||
ridge = make_pipeline(StandardScaler(), Ridge(alpha=alpha)).fit(Ftr, ytr)
|
||||
out.append(("B0b-ridge", -1, ridge.predict(F[test]), None))
|
||||
for s in seeds:
|
||||
rf = RandomForestRegressor(random_state=s, n_jobs=4, **P["B0b"]["models"]["rf"]).fit(Ftr, ytr)
|
||||
out.append(("B0b-rf", s, rf.predict(F[test]), None))
|
||||
gb = HistGradientBoostingRegressor(random_state=s, **P["B0b"]["models"]["gbm"]).fit(Ftr, ytr)
|
||||
out.append(("B0b-gbm", s, gb.predict(F[test]), None))
|
||||
|
||||
# B1: inversion
|
||||
hz = P["B1"]["lfm"].split("[")[1].split("]")[0].split(", ")
|
||||
|
||||
def wellinfo(w):
|
||||
return {"logai": np.log(inv.fill_edges(d.ext(w, "calibrated/AI"))),
|
||||
"h": np.array([float(d.ext(w, f"horizon/{h}")) for h in hz]),
|
||||
"xy": np.array([float(d.ext(w, "x")), float(d.ext(w, "y"))])}
|
||||
|
||||
info = {w: wellinfo(w) for w in d.wells}
|
||||
seis = {w: d.ext(w, "seismic_patch")[4].astype(float) for w in d.wells}
|
||||
|
||||
def b1_predict(tr_wells, target, e):
|
||||
wav = inv.estimate_wavelet([info[w]["logai"] for w in tr_wells], [seis[w] for w in tr_wells], d.m)
|
||||
lfm = inv.build_lfm(d.t, info[target]["h"], info[target]["xy"], {w: info[w] for w in tr_wells},
|
||||
f_c_hz=d.proto["metrics"]["bands"]["f_c_hz"])
|
||||
ai = np.exp(inv.invert(seis[target], wav, lfm, e))[d.m]
|
||||
ai_tr = np.concatenate([np.exp(info[w]["logai"])[d.m] for w in tr_wells])
|
||||
phi_fit = LinearRegression().fit(ai_tr[:, None], np.concatenate([d.y(w, "calibrated", label) for w in tr_wells]))
|
||||
return phi_fit.predict(ai[:, None])
|
||||
|
||||
egrid = [0.01, 0.03, 0.1, 0.3, 1.0]
|
||||
escores = [np.mean([np.mean((b1_predict([w for w in train if w != v], v, e) - d.y(v, "calibrated", label)) ** 2)
|
||||
for v in train]) for e in egrid]
|
||||
e_best = egrid[int(np.argmin(escores))]
|
||||
sel.append({"label": label, "test_well": test, "method": "B1", "param": "e", "value": e_best})
|
||||
out.append(("B1", -1, b1_predict(train, test, e_best), None))
|
||||
return out, sel
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- B2, B3 (GPU)
|
||||
|
||||
|
||||
def run_cnn(job):
|
||||
method, label, test, seed, device, proto = job
|
||||
import torch
|
||||
|
||||
torch.set_num_threads(2)
|
||||
from ml_porosity.models.train import predict, train_cnn
|
||||
|
||||
d = Data(proto)
|
||||
d.proto = proto
|
||||
P = proto["methods"]
|
||||
cfg = P["B2"]
|
||||
kind = "legacy" if method == "B2" else "nll"
|
||||
tdr_train = "legacy" if method == "B3a" else "calibrated"
|
||||
train = [w for w in d.wells if w != test]
|
||||
|
||||
def XY(ws):
|
||||
X = np.stack([d.X(w) for w in ws])
|
||||
Y = np.stack([d.y(w, tdr_train, label) for w in ws])
|
||||
return X, Y
|
||||
|
||||
# vòng inner: chọn epoch
|
||||
curves = []
|
||||
for v in train:
|
||||
tr2 = [w for w in train if w != v]
|
||||
Xa, Ya = XY(tr2)
|
||||
mu_, sd_ = Ya.mean(), Ya.std() + 1e-8
|
||||
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
|
||||
eps = [e for e, _ in c]
|
||||
best_ep = int(eps[int(np.argmin(np.mean(curves, axis=0)))])
|
||||
|
||||
Xtr, Ytr = XY(train)
|
||||
mu_, sd_ = Ytr.mean(), Ytr.std() + 1e-8
|
||||
model, _ = train_cnn(Xtr, (Ytr - mu_) / sd_, cfg, kind, seed, best_ep, device)
|
||||
m, s = predict(model, d.X(test)[None], device)
|
||||
mu = m[0] * sd_ + mu_
|
||||
sigma = None if s is None else s[0] * sd_
|
||||
return method, label, test, seed, mu, sigma, best_ep
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--workers", type=int, default=12)
|
||||
ap.add_argument("--device", default="cuda")
|
||||
ap.add_argument("--only", default="")
|
||||
args = ap.parse_args()
|
||||
|
||||
proto = check_protocol()
|
||||
d = Data(proto)
|
||||
d.proto = proto
|
||||
seeds = proto["split"]["seeds"]
|
||||
labels = [proto["data"]["labels"]["primary"], proto["data"]["labels"]["secondary"]]
|
||||
only = set(filter(None, args.only.split(",")))
|
||||
out_dir = outputs_dir() / "p1"
|
||||
out_dir.mkdir(exist_ok=True)
|
||||
|
||||
preds, rows, sel = {}, [], []
|
||||
|
||||
def record(method, label, test, seed, mu, sigma):
|
||||
preds[f"{label}/{test}/{method}/s{seed}/mu"] = np.asarray(mu)
|
||||
if sigma is not None:
|
||||
preds[f"{label}/{test}/{method}/s{seed}/sigma"] = np.asarray(sigma)
|
||||
for r in evaluate(d, test, label, mu, sigma):
|
||||
rows.append({"method": method, "label": label, "test_well": test, "seed": seed} | r)
|
||||
|
||||
t0 = time.time()
|
||||
if not only or only & {"B0a", "B0b", "B1"}:
|
||||
for label, test in itertools.product(labels, d.wells):
|
||||
out, s = run_classical(d, label, test, seeds)
|
||||
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")
|
||||
|
||||
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]
|
||||
if jobs:
|
||||
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
|
||||
futs = [ex.submit(run_cnn, j) for j in jobs]
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
method, label, test, seed, mu, sigma, best_ep = f.result()
|
||||
sel.append({"label": label, "test_well": test, "method": method, "param": f"epochs_s{seed}", "value": best_ep})
|
||||
record(method, label, test, seed, mu, sigma)
|
||||
if i % 10 == 0 or i == len(jobs):
|
||||
print(f"CNN {i}/{len(jobs)} sau {time.time() - t0:.0f} s")
|
||||
|
||||
tag = "_".join(sorted(only)) if only else "all"
|
||||
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)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||||
main()
|
||||
164
scripts/06_summarize_p1.py
Normal file
164
scripts/06_summarize_p1.py
Normal file
@@ -0,0 +1,164 @@
|
||||
"""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.
|
||||
|
||||
python scripts/06_summarize_p1.py
|
||||
|
||||
Đầu ra: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
ORDER = ["B0a", "B0b-ridge", "B0b-rf", "B0b-gbm", "B1", "B2", "B3a", "B3b"]
|
||||
|
||||
|
||||
def load():
|
||||
d = outputs_dir() / "p1"
|
||||
res = pd.concat([pd.read_csv(f) for f in sorted(d.glob("results_*.csv"))], ignore_index=True)
|
||||
preds = {}
|
||||
for f in sorted(d.glob("preds_*.npz")):
|
||||
z = np.load(f)
|
||||
preds.update({k: z[k] for k in z.files})
|
||||
return res, preds
|
||||
|
||||
|
||||
def per_well(res, label, ref):
|
||||
r = res[(res.label == label) & (res.reference == ref)].copy()
|
||||
b0a = r[r.method == "B0a"].set_index("test_well")["rmse"] ** 2
|
||||
r["skill"] = 1 - r.rmse**2 / r.test_well.map(b0a)
|
||||
cols = ["rmse", "pcc", "r2", "band_pcc", "band_std_ratio", "low_pcc", "skill"]
|
||||
g = r.groupby(["method", "test_well"])[cols]
|
||||
return g.mean(), g.std().fillna(0.0), r
|
||||
|
||||
|
||||
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)
|
||||
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)
|
||||
return out.reindex([m for m in ORDER if m in out.index])
|
||||
|
||||
|
||||
def fmt(m, s, nd=2):
|
||||
return f"{m:.{nd}f}" if s == 0 else f"{m:.{nd}f} ± {s:.{nd}f}"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
proto = yaml.safe_load((REPO_ROOT / "configs" / "protocol.yaml").read_text())
|
||||
res, preds = load()
|
||||
D = np.load(outputs_dir() / "f3_wells.npz")
|
||||
wells = proto["data"]["wells"]
|
||||
lab1, lab2 = proto["data"]["labels"]["primary"], proto["data"]["labels"]["secondary"]
|
||||
lines, summary = [], {"protocol_sha256": res.protocol_sha256.iloc[0]}
|
||||
|
||||
for label in (lab1, lab2):
|
||||
for ref in ("calibrated", "wlt"):
|
||||
mt = macro(res, label, ref)
|
||||
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("| --- | --- | --- | --- | --- | --- |")
|
||||
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("| --- |" + " --- |" * len(wells))
|
||||
summary["per_well"] = {}
|
||||
for m in ORDER:
|
||||
if m not in mean.index.get_level_values(0):
|
||||
continue
|
||||
cells = []
|
||||
for w in wells:
|
||||
a, s = mean.loc[(m, w)], sd.loc[(m, w)]
|
||||
cells.append(f"{fmt(a.rmse, s.rmse)} / {a.pcc:.2f} / {a.band_pcc:.2f}")
|
||||
summary["per_well"].setdefault(m, {})[w] = [round(a.rmse, 2), round(a.pcc, 2), round(a.band_pcc, 2)]
|
||||
lines.append(f"| {m} | " + " | ".join(cells) + " |")
|
||||
|
||||
# calibration B3
|
||||
cal = res[(res.label == lab1) & (res.reference == "calibrated") & res.method.isin(["B3a", "B3b"])]
|
||||
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("| | " + " | ".join(cc) + " |")
|
||||
lines.append("| --- |" + " --- |" * len(cc))
|
||||
summary["calibration"] = {}
|
||||
for m in cm.index:
|
||||
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
|
||||
mt = macro(res, lab1, "calibrated")
|
||||
if {"B3a", "B3b"} <= set(mt.index):
|
||||
ra, rb = mt.loc["B3a", ("rmse", "mean")], mt.loc["B3b", ("rmse", "mean")]
|
||||
pa, pb = mt.loc["B3a", ("pcc", "mean")], mt.loc["B3b", ("pcc", "mean")]
|
||||
d_rmse = (ra - rb) / rb * 100
|
||||
equal = abs(d_rmse) < 5 and abs(pa - pb) < 0.05
|
||||
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).")
|
||||
|
||||
# QC nhãn trong cửa sổ (D-1)
|
||||
m_ = D[f"{wells[0]}/main_mask"].astype(bool)
|
||||
lq = {}
|
||||
for w in wells:
|
||||
a, b = D[f"{w}/calibrated/PHIE"][m_], D[f"{w}/calibrated/PHIE_DT"][m_]
|
||||
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| --- | --- | --- | --- |")
|
||||
for w, v in lq.items():
|
||||
lines.append(f"| {w} | {v['r2']} | {v['max_abs_diff_pu']} | {v['std_pu']} |")
|
||||
|
||||
out = outputs_dir() / "p1"
|
||||
(out / "summary.md").write_text("\n".join(lines) + "\n")
|
||||
(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)
|
||||
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)")
|
||||
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 ""))
|
||||
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%")
|
||||
ax.set_title(f"test {w}", fontsize=10)
|
||||
ax.set_xlabel(f"{lab1} (p.u.)")
|
||||
ax.grid(alpha=0.3)
|
||||
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.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
143
scripts/07_volve_interp_qc.py
Normal file
143
scripts/07_volve_interp_qc.py
Normal file
@@ -0,0 +1,143 @@
|
||||
"""QC dữ liệu minh giải Volve (Geophysical_Interpretations) trước khi có cube.
|
||||
|
||||
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
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.data.seismic_io import SeismicCube
|
||||
from ml_porosity.data.volve_io import read_checkshot, read_horizon, read_well_picks
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
|
||||
|
||||
|
||||
def main() -> None:
|
||||
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d3_volve.yaml").read_text())
|
||||
root, out = volve_root(), outputs_dir() / "volve"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
hdir = root / cfg["horizons_twt"]
|
||||
summary = {}
|
||||
|
||||
# lưới horizon
|
||||
rows, hors = [], {}
|
||||
for f in sorted(hdir.parent.rglob("*.dat")):
|
||||
h = read_horizon(f)
|
||||
g = h.geometry()
|
||||
res = np.hypot(*(np.array(g.bin_to_xy(h.il, h.xl)) - np.array([h.x, h.y]))).max()
|
||||
key = f.relative_to(hdir.parent).as_posix()
|
||||
hors[key] = h
|
||||
rows.append(dict(file=key, survey=h.survey, domain=h.domain, n=len(h.z),
|
||||
il_min=g.il_range[0], il_max=g.il_range[1], xl_min=g.xl_range[0], xl_max=g.xl_range[1],
|
||||
z_min=h.z.min(), z_max=h.z.max(), bin_m=np.round(g.bin_spacing(), 3).tolist(),
|
||||
affine_res_m=round(float(res), 3)))
|
||||
H = pd.DataFrame(rows)
|
||||
H.to_csv(out / "horizons.csv", index=False)
|
||||
geom = hors[f"{hdir.name}/{cfg['grid_horizon']}"].geometry()
|
||||
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
|
||||
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"])
|
||||
& ~P.surface.isin(cfg["anchor_exclude_surfaces"]))
|
||||
A = P[ok & P.well.isin(cfg["wells"])].sort_values(["well", "md"])
|
||||
A.to_csv(out / "anchors.csv", index=False)
|
||||
per_well = {}
|
||||
for w in cfg["wells"]:
|
||||
a = A[A.well == w].drop_duplicates("md")
|
||||
per_well[w] = {"n_anchors": len(a), "md": [a.md.min(), a.md.max()], "twt_ms": [a.twt_ms.min(), a.twt_ms.max()],
|
||||
"n_faulted": int((a.qlf == "FP").sum())}
|
||||
summary["anchors"] = per_well
|
||||
|
||||
# TWT nông: cùng MD, khác nhánh khoan
|
||||
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
|
||||
C = []
|
||||
for s, f in cfg["pick_horizons"].items():
|
||||
h = hors[f"{hdir.name}/{f}"]
|
||||
for _, r in P[(P.surface == s) & P.twt_ms.notna() & P.x.notna() & (P.qlf != "NL")].iterrows():
|
||||
z = h.at(r.il, r.xl, radius=1)
|
||||
if np.isfinite(z):
|
||||
C.append(dict(well=r.well, surface=s, qlf=r.qlf, key=r.well in cfg["wells"], il=r.il, xl=r.xl,
|
||||
pick_ms=r.twt_ms, horizon_ms=z, d_ms=r.twt_ms - z))
|
||||
C = pd.DataFrame(C)
|
||||
C.to_csv(out / "pick_vs_horizon.csv", index=False)
|
||||
clean = C[C.key & (C.qlf == "")]
|
||||
summary["pick_minus_horizon_ms"] = {
|
||||
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)
|
||||
D = []
|
||||
for w, files in cfg["checkshots"].items():
|
||||
p = P[(P.well == w) & P.twt_ms.notna()]
|
||||
for kind, rel in files.items():
|
||||
cs = read_checkshot(root / cfg["well_logs_dir"] / rel)
|
||||
q = p[(-p.tvdss >= cs.tvdss.min()) & (-p.tvdss <= cs.tvdss.max())]
|
||||
for _, r in q.iterrows():
|
||||
D.append(dict(well=w, checkshot=kind, surface=r.surface, qlf=r.qlf, md=r.md, pick_ms=r.twt_ms,
|
||||
d_tvd_ms=r.twt_ms - np.interp(-r.tvdss, cs.tvdss, cs.twt_ms),
|
||||
d_md_ms=r.twt_ms - np.interp(r.md, cs.md, cs.twt_ms)))
|
||||
D = pd.DataFrame(D)
|
||||
D.to_csv(out / "pick_vs_checkshot.csv", index=False)
|
||||
deep = D[~D.surface.isin(cfg["anchor_exclude_surfaces"])]
|
||||
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
|
||||
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_path = root / cfg["cube"]
|
||||
if cube_path.exists():
|
||||
(i0, i1), (j0, j1) = summary["roi_ilxl"]["il"], summary["roi_ilxl"]["xl"]
|
||||
rng, lags, L = np.random.default_rng(0), np.arange(-24, 25, 1.0), []
|
||||
with SeismicCube(cube_path) as c:
|
||||
bins = [(int(i), int(j)) for i, j in zip(rng.integers(i0, i1 + 1, 200), rng.integers(j0, j1 + 1, 200))]
|
||||
xy = np.array([c.coords(i, j) for i, j in bins])
|
||||
gx, gy = geom.bin_to_xy(*np.array(bins).T)
|
||||
summary["cube"] = {"file": cube_path.name, "il": [int(c.ilines[0]), int(c.ilines[-1])],
|
||||
"xl": [int(c.xlines[0]), int(c.xlines[-1])], "t_ms": [c.times_ms[0], c.times_ms[-1]],
|
||||
"dt_ms": c.dt_ms, "max_header_vs_grid_m": float(np.hypot(xy[:, 0] - gx, xy[:, 1] - gy).max())}
|
||||
for s in ("Ty Fm. Top", "SHETLAND GP. Top", "Draupne Fm. Top", "Hugin Fm. VOLVE Top", "Hugin Fm. VOLVE Base"):
|
||||
h = hors[f"{hdir.name}/{cfg['pick_horizons'][s]}"]
|
||||
m = np.flatnonzero((h.il >= i0) & (h.il <= i1) & (h.xl >= j0) & (h.xl <= j1))
|
||||
amp = []
|
||||
for k in rng.choice(m, 1500, replace=False):
|
||||
try:
|
||||
amp.append(np.interp(h.z[k] + lags, c.times_ms, c.trace(int(h.il[k]), int(h.xl[k]))))
|
||||
except KeyError:
|
||||
pass
|
||||
mean = np.mean(amp, axis=0)
|
||||
sign = np.sign(mean[lags == 0][0])
|
||||
L.append(dict(surface=s, horizon=h.name, n=len(amp), polarity=int(sign),
|
||||
lag_ms=float(lags[np.argmax(sign * mean)]), amp_lag0=float(mean[lags == 0][0])))
|
||||
pd.DataFrame(L).to_csv(out / "horizon_lag.csv", index=False)
|
||||
summary["cube"]["horizon_extremum_lag_ms"] = {r["surface"]: r["lag_ms"] for r in L}
|
||||
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False, default=float))
|
||||
pd.set_option("display.width", 200)
|
||||
print(H[["file", "survey", "n", "il_min", "il_max", "xl_min", "xl_max", "z_min", "z_max"]].to_string(index=False))
|
||||
print(json.dumps(summary, indent=1, ensure_ascii=False, default=float))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
141
scripts/08_d1_label_check.py
Normal file
141
scripts/08_d1_label_check.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""Kiểm tra D-1 (định nghĩa nhãn F3) bằng density đo của NLOG.
|
||||
|
||||
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
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import lasio
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import signal
|
||||
|
||||
from ml_porosity.data.las_io import load_well
|
||||
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
|
||||
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),
|
||||
"F03-03": ("F03-03__7034_f0303_1974_comp.las", "F03-03__F033_Composite-TOTAL~LF1.las", "F03-03__F03-3_TZ_TM5.txt"),
|
||||
"F03-06": ("F03-06__7037_f0306_1978_comp.las", "F03-06__F036_Composite-TOTAL~LF1.las", "F03-06__F03-6_TZ_TM5.txt"),
|
||||
}
|
||||
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
|
||||
|
||||
|
||||
def phi_d(rhob):
|
||||
return (2650.0 - rhob) / 1600.0
|
||||
|
||||
|
||||
def phi_dt(dt):
|
||||
return -0.2018 + 0.0011 * 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)."""
|
||||
raw = nlog_root() / "raw"
|
||||
las = lasio.read(raw / comp)
|
||||
df = las.df().sort_index()
|
||||
df.index = df.index.astype(float)
|
||||
df["DT"] /= 0.3048
|
||||
df[["RHOB", "DRHO"]] *= 1000.0
|
||||
c = lasio.read(raw / composite).df()
|
||||
df["CALI"] = np.interp(df.index, c.index.to_numpy(float) * 0.3048, c["CALI"].to_numpy(float), left=np.nan, right=np.nan)
|
||||
return df, float(las.params["APD"].value)
|
||||
|
||||
|
||||
def read_tz(path: str, apd: float) -> TDR:
|
||||
rows = [s.split()[1:3] for s in (nlog_root() / "raw" / path).read_text().splitlines() if s.startswith("T/Z")]
|
||||
tz = np.asarray(rows, dtype=float)
|
||||
return TDR.from_pairs(np.column_stack([tz[:, 1] + apd, tz[:, 0]]), "nlog_tz", drop_flat=True)
|
||||
|
||||
|
||||
def corr(a: np.ndarray, b: np.ndarray) -> float:
|
||||
ok = np.isfinite(a) & np.isfinite(b)
|
||||
return float(np.corrcoef(a[ok], b[ok])[0, 1])
|
||||
|
||||
|
||||
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."""
|
||||
ok = np.isfinite(a) & np.isfinite(b)
|
||||
r = corr(a, b)
|
||||
i = np.flatnonzero(ok)
|
||||
seg = slice(i[0], i[-1] + 1)
|
||||
r_band = (float(np.corrcoef(signal.sosfiltfilt(SOS_BAND, a[seg]), signal.sosfiltfilt(SOS_BAND, b[seg]))[0, 1])
|
||||
if ok[seg].all() else np.nan)
|
||||
return dict(n=int(ok.sum()), r=round(r, 3), r2=round(r * r, 3), bias_pu=round(float(np.mean(a[ok] - b[ok])), 2),
|
||||
rms_pu=round(float(np.sqrt(np.mean((a[ok] - b[ok]) ** 2))), 2), r_band=round(r_band, 3),
|
||||
std_a_pu=round(float(np.std(a[ok])), 2), std_b_pu=round(float(np.std(b[ok])), 2))
|
||||
|
||||
|
||||
def quality(df: pd.DataFrame, d0: float, d1: float) -> dict:
|
||||
w = df.loc[d0:d1]
|
||||
drho, cal = w.DRHO.dropna().abs(), w.CALI.dropna()
|
||||
return dict(drho_gt50=round(float((drho > 50).mean()), 3), drho_gt100=round(float((drho > 100).mean()), 3),
|
||||
cali_median_in=round(float(cal.median()), 1), cali_p90_in=round(float(cal.quantile(0.9)), 1))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
out = outputs_dir() / "d1"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
Z = np.load(outputs_dir() / "f3_wells.npz")
|
||||
rows, summary = [], {"window_ms": WINDOW_MS, "wells": {}}
|
||||
|
||||
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
|
||||
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)
|
||||
g = np.arange(d0, d1, 0.1)
|
||||
dt_demo = np.interp(g, W.md, W.curve("DT"))
|
||||
shifts = np.round(np.arange(-8, 8.01, 0.1), 1)
|
||||
shift = float(max(shifts, key=lambda s: corr(np.interp(g + s, df.index, df.DT), dt_demo)))
|
||||
md = df.index.to_numpy() - shift
|
||||
info["depth_shift_nlog_to_demo_m"] = shift + 0.0
|
||||
for c in ("DT", "RHOB"):
|
||||
a, b = np.interp(g, md, df[c]), np.interp(g, W.md, W.curve(c))
|
||||
d = (a - b)[np.isfinite(a - b)]
|
||||
info[f"{c}_nlog_vs_demo"] = {"r": round(corr(a, b), 3), "bias": round(float(d.mean()), 1),
|
||||
"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
|
||||
tdr = read_tz(tz, apd)
|
||||
d0, d1 = tdr.depth_at(WINDOW_MS)
|
||||
md, shift = df.index.to_numpy(), 0.0
|
||||
labels = {"PHIE_DT": log_to_time(md, phi_dt(df.DT.to_numpy()), tdr, T)}
|
||||
info["window_md_m"] = [round(float(d0), 1), round(float(d1), 1)]
|
||||
info["quality"] = quality(df, d0 + shift, d1 + shift)
|
||||
phid = log_to_time(md, phi_d(df.RHOB.to_numpy()), tdr, T)
|
||||
for name, lab in labels.items():
|
||||
rows.append(dict(well=w, label=name, demo=tz is None, **compare(100 * phid, 100 * lab)))
|
||||
summary["wells"][w] = info
|
||||
|
||||
R = pd.DataFrame(rows)
|
||||
R.to_csv(out / "label_check.csv", index=False)
|
||||
summary["phi_d_vs_phie_dt"] = R[R.label == "PHIE_DT"].set_index("well")[["r2", "bias_pu", "rms_pu", "r_band"]].to_dict("index")
|
||||
(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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
10
scripts/run_p0.sh
Executable file
10
scripts/run_p0.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/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.
|
||||
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
|
||||
10
scripts/run_p1.sh
Executable file
10
scripts/run_p1.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/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.
|
||||
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
|
||||
Reference in New Issue
Block a user