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:
2026-10-26 08:41:11 +00:00
parent d11b7b1bb5
commit a76e61398a
163 changed files with 120177 additions and 2742 deletions

70
tests/test_geometry.py Normal file
View File

@@ -0,0 +1,70 @@
import numpy as np
import pytest
from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.paths import f3_root
SURVEY = f3_root() / ".survey"
pytestmark = pytest.mark.skipif(not SURVEY.exists(), reason="thiếu F3 .survey")
@pytest.fixture(scope="module")
def geom():
return SurveyGeometry.from_survey(SURVEY)
def test_parses_survey(geom):
assert geom.il_range == (100, 750, 1)
assert geom.xl_range == (300, 1250, 1)
assert geom.epsg == 23031
assert len(geom.set_points) == 3
def test_set_points_forward_and_inverse(geom):
for il, xl, x, y in geom.set_points:
xp, yp = geom.bin_to_xy(il, xl)
assert xp == pytest.approx(x, abs=0.01)
assert yp == pytest.approx(y, abs=0.01)
ilp, xlp = geom.xy_to_bin(x, y)
assert ilp == pytest.approx(il, abs=1e-3)
assert xlp == pytest.approx(xl, abs=1e-3)
def test_bin_spacing_25m(geom):
assert geom.bin_spacing() == pytest.approx((25.0, 25.0), abs=0.01)
def test_round_trip_vectorised(geom):
rng = np.random.default_rng(0)
il = rng.uniform(100, 750, 100)
xl = rng.uniform(300, 1250, 100)
il2, xl2 = geom.xy_to_bin(*geom.bin_to_xy(il, xl))
np.testing.assert_allclose(il2, il, atol=1e-6)
np.testing.assert_allclose(xl2, xl, atol=1e-6)
@pytest.mark.parametrize(
"name,xy,expected",
[ # bảng IL/XL thật ở plan mục 1.2a
("F02-1", (606554, 6080126), (362, 336)),
("F03-2", (619101, 6089491), (722, 848)),
("F03-4", (623256, 6082586), (442, 1007)),
("F06-1", (607903, 6077213), (244, 387)),
],
)
def test_well_bins_match_plan(geom, name, xy, expected):
assert geom.nearest_bin(*xy) == expected
assert geom.in_survey(*expected)
@pytest.mark.parametrize(
"legacy,xy,km",
[ # vị trí luận văn dùng và độ lệch ở plan mục 1.2a
((418, 608), (606554, 6080126), 6.94),
((362, 821), (623256, 6082586), 5.05),
((283, 842), (607903, 6077213), 11.42),
],
)
def test_legacy_offsets(geom, legacy, xy, km):
x, y = geom.bin_to_xy(*legacy)
assert np.hypot(x - xy[0], y - xy[1]) / 1000 == pytest.approx(km, abs=0.01)

24
tests/test_models.py Normal file
View File

@@ -0,0 +1,24 @@
import torch
from ml_porosity.losses.legacy_v2 import LegacyV2Loss, pcc_loss, shape_loss
from ml_porosity.models.cnn_gru import CNNGRU
def test_cnn_gru_shape():
m = CNNGRU(in_ch=9, d=16)
assert m(torch.randn(2, 9, 126)).shape == (2, 1, 126)
def test_shape_loss_redundant_with_pcc():
# plan mục 1.1 #7: L_shape = 2·L_PCC − 2/L (z-score dùng std không chệch, Σx² = L − 1)
torch.manual_seed(0)
p, t = torch.randn(4, 1, 126), torch.randn(4, 1, 126)
assert torch.allclose(shape_loss(p, t), 2 * pcc_loss(p, t) - 2 / 126, atol=1e-5)
def test_legacy_loss_finite_and_differentiable():
m = CNNGRU(in_ch=9, d=8)
x, y = torch.randn(2, 9, 64), torch.randn(2, 1, 64)
loss = LegacyV2Loss()(m(x), y)
loss.backward()
assert torch.isfinite(loss)

61
tests/test_p1_modules.py Normal file
View File

@@ -0,0 +1,61 @@
import numpy as np
import pytest
from ml_porosity.baselines.inversion import strat_map
from ml_porosity.data.synthetic import best_shift, local_shifts, reflectivity_from_ai, shift_signal
from ml_porosity.data.wavelet import convolve_same, estimate_wavelet_ls, ricker, rotate_phase
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, split_bands
def test_rotate_phase_180_flips_sign():
w = ricker(40)
np.testing.assert_allclose(rotate_phase(w, 180), -w, atol=1e-6)
def test_wavelet_ls_recovers_known_wavelet():
rng = np.random.default_rng(0)
w_true = rotate_phase(ricker(45), 30) * 3.0
refl = [rng.standard_normal(400) * 0.05 for _ in range(3)]
seis = [convolve_same(r, w_true) for r in refl]
w_est = estimate_wavelet_ls(refl, seis, damping=1e-6)
taper = np.hanning(len(w_true) + 2)[1:-1]
np.testing.assert_allclose(w_est, w_true * taper, atol=0.02 * np.abs(w_true).max())
def test_best_and_local_shift_find_known_shift():
rng = np.random.default_rng(1)
r = reflectivity_from_ai(np.exp(np.cumsum(rng.standard_normal(300) * 0.05)))
syn = convolve_same(r, ricker(50))
seis = shift_signal(syn, 6.0, 4.0)
sh, rr = best_shift(syn, seis, 4.0, 20.0)
assert sh == pytest.approx(6.0, abs=0.5) and rr > 0.99
_, ls, _ = local_shifts(syn, seis, 4.0, max_ms=16)
assert np.median(ls) == pytest.approx(6.0, abs=0.5)
def test_strat_map_identity_and_shift():
t = np.arange(500.0, 1200.0, 4.0)
h = np.array([600.0, 800.0, 1000.0])
np.testing.assert_allclose(strat_map(t, h, h), t)
np.testing.assert_allclose(strat_map(t, h, h + 20), t + 20)
# giãn tuyến tính giữa hai horizon
out = strat_map(np.array([700.0]), np.array([600.0, 800.0]), np.array([600.0, 1000.0]))
assert out[0] == pytest.approx(800.0)
def test_split_bands_sums_and_separates():
t = np.arange(126) * 0.004
y = np.sin(2 * np.pi * 2 * t) + 0.3 * np.sin(2 * np.pi * 40 * t)
lo, hi = split_bands(y, 6.0)
np.testing.assert_allclose(lo + hi, y, atol=1e-12)
assert np.corrcoef(hi[10:-10], 0.3 * np.sin(2 * np.pi * 40 * t)[10:-10])[0, 1] > 0.95
m = band_metrics(y, y)
assert m["band_pcc"] == pytest.approx(1.0) and m["low_rmse"] == pytest.approx(0.0)
def test_gaussian_metrics_calibrated():
rng = np.random.default_rng(0)
y = rng.standard_normal(20000)
g = gaussian_metrics(y, np.zeros_like(y), np.ones_like(y))
assert g["coverage_90"] == pytest.approx(0.90, abs=0.01)
assert g["crps"] == pytest.approx(1 / np.sqrt(np.pi), abs=0.01) # E[CRPS] khi dự báo đúng N(0, 1)

46
tests/test_seismic_io.py Normal file
View File

@@ -0,0 +1,46 @@
import numpy as np
import pytest
import segyio
from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.paths import f3_root, f3_segy
pytestmark = [
pytest.mark.data,
pytest.mark.skipif(not f3_segy().exists(), reason="thiếu F3_entire.segy"),
]
@pytest.fixture(scope="module")
def cube():
with SeismicCube() as c:
yield c
def test_axes(cube):
assert (cube.ilines[0], cube.ilines[-1], len(cube.ilines)) == (100, 750, 651)
assert (cube.xlines[0], cube.xlines[-1], len(cube.xlines)) == (300, 1250, 951)
# DelayRecordingTime = 4 ms: mẫu đầu ở 4 ms, không phải 0
assert cube.times_ms[0] == 4.0 and cube.dt_ms == 4.0 and len(cube.times_ms) == 462
@pytest.mark.parametrize("il,xl", [(100, 300), (244, 387), (722, 848), (750, 1250)])
def test_trace_index_matches_headers(cube, il, xl):
idx = cube._index(il, xl)
h = cube._f.header[idx]
assert (h[segyio.TraceField.INLINE_3D], h[segyio.TraceField.CROSSLINE_3D]) == (il, xl)
# Tọa độ trong header (scalar −100) khớp phép biến đổi của .survey
geom = SurveyGeometry.from_survey(f3_root())
x, y = geom.bin_to_xy(il, xl)
assert h[segyio.TraceField.CDP_X] / 100 == pytest.approx(x, abs=0.5)
assert h[segyio.TraceField.CDP_Y] / 100 == pytest.approx(y, abs=0.5)
def test_patch(cube):
p = cube.patch(244, 387, 1)
assert p.shape == (9, 462)
np.testing.assert_array_equal(p[4], cube.trace(244, 387))
np.testing.assert_array_equal(p[0], cube.trace(243, 386))
with pytest.raises(KeyError):
cube.patch(100, 300, 1)

159
tests/test_tdr.py Normal file
View File

@@ -0,0 +1,159 @@
import numpy as np
import pytest
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import (
TDR,
calibrate_to_anchors,
legacy_sonic_tdr,
misfit_at_anchors,
sonic_tdr,
)
from ml_porosity.paths import f3_wells_dir
# ---------- tổng hợp, không cần dữ liệu ----------
def constant_velocity_log(v=2000.0, z0=0.0, z1=1000.0, dz=0.5):
md = np.arange(z0, z1 + dz / 2, dz)
return md, np.full_like(md, 1e6 / v) # DT (µs/m)
def test_tdr_rejects_non_monotone():
with pytest.raises(ValueError):
TDR(np.array([0.0, 1.0, 1.0]), np.array([0.0, 1.0, 2.0]))
with pytest.raises(ValueError):
TDR(np.array([0.0, 1.0, 2.0]), np.array([0.0, 2.0, 1.0]))
def test_from_pairs_drop_flat():
pairs = np.array([[0, 0], [10, 5], [11, 5], [20, 10]], dtype=float)
with pytest.raises(ValueError):
TDR.from_pairs(pairs)
t = TDR.from_pairs(pairs, drop_flat=True)
np.testing.assert_array_equal(t.md, [0, 10, 20])
def test_sonic_constant_velocity():
md, dt = constant_velocity_log(v=2000.0)
t = sonic_tdr(md, dt, md0=100.0, t0_ms=50.0)
# TWT = t0 + 2·(z − z0)/v
np.testing.assert_allclose(t.time_at([100, 600]), [50.0, 550.0], atol=1e-9)
np.testing.assert_allclose(t.interval_velocity(), 2000.0)
def test_legacy_starts_at_zero():
md, dt = constant_velocity_log(z0=30.0)
t = legacy_sonic_tdr(md, dt)
assert t.twt_ms[0] == 0.0
def test_calibration_honors_anchors_and_is_monotone():
md, dt = constant_velocity_log(v=2000.0, z1=1500.0)
base = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
# Anchor lệch tới ±40 ms so với sonic, kiểu drift của F06-1.
za = np.array([100.0, 400.0, 700.0, 1000.0, 1300.0])
ta = za + np.array([5.0, -20.0, 30.0, -40.0, 10.0]) # ở 2000 m/s, TWT (ms) = MD (m)
cal = calibrate_to_anchors(base, za, ta)
np.testing.assert_allclose(misfit_at_anchors(cal, za, ta), 0.0, atol=1e-9)
assert np.all(np.diff(cal.twt_ms) > 0)
# ngoài phạm vi anchor: dịch đều theo anchor gần nhất
assert cal.time_at(50.0) == pytest.approx(base.time_at(50.0) + 5.0)
assert cal.time_at(1400.0) == pytest.approx(base.time_at(1400.0) + 10.0)
def test_calibration_noop_when_sonic_exact():
md, dt = constant_velocity_log(v=2500.0)
base = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
za = np.array([200.0, 500.0, 800.0])
cal = calibrate_to_anchors(base, za, base.time_at(za))
np.testing.assert_allclose(cal.time_at(md), base.time_at(md), atol=1e-9)
def test_calibration_rejects_crossing_anchors():
md, dt = constant_velocity_log()
base = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
with pytest.raises(ValueError):
calibrate_to_anchors(base, [100.0, 200.0], [300.0, 250.0])
def test_log_to_time_antialias():
# Log tuyến tính theo thời gian được giữ nguyên; sin 200 Hz (trên Nyquist 125 Hz của 4 ms) bị lọc.
md, dt = constant_velocity_log(v=2000.0, dz=0.15)
tdr = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
t_log = tdr.time_at(md)
t_out = np.arange(200.0, 800.0, 4.0)
ramp = log_to_time(md, 0.1 + 1e-4 * t_log, tdr, t_out)
np.testing.assert_allclose(ramp, 0.1 + 1e-4 * t_out, atol=1e-4)
hf = log_to_time(md, np.sin(2 * np.pi * 200.0 * t_log / 1000.0), tdr, t_out)
assert np.max(np.abs(hf)) < 0.02
def test_log_to_time_marks_gaps():
md, dt = constant_velocity_log(v=2000.0, dz=0.15)
tdr = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
v = np.ones_like(md)
v[(md > 400) & (md < 450)] = np.nan # khoảng trống 50 ms
out = log_to_time(md, v, tdr, np.arange(300.0, 600.0, 4.0))
t_out = np.arange(300.0, 600.0, 4.0)
assert np.all(np.isnan(out[(t_out > 402) & (t_out < 448)]))
assert np.all(np.isfinite(out[(t_out < 398) | (t_out > 452)]))
# ---------- trên dữ liệu F3 ----------
needs_f3 = pytest.mark.skipif(not (f3_wells_dir() / "Lasfiles").exists(), reason="thiếu dữ liệu giếng F3")
@needs_f3
@pytest.mark.data
@pytest.mark.parametrize(
"name,n_anchors,lo,hi",
[ # plan mục 1.2b và 1.2e: TWT tích phân DT − marker TD trong 600–1100 ms
("F02-1", 11, -44, 2),
("F03-2", 9, -14, -3),
("F03-4", 9, -52, -42),
("F06-1", 10, -66, -21),
],
)
def test_f3_legacy_drift_matches_plan(name, n_anchors, lo, hi):
from ml_porosity.data.las_io import load_well
w = load_well(name)
cs = w.checkshot[w.checkshot.twt_ms.between(600, 1100)]
assert len(cs) == n_anchors
d = misfit_at_anchors(legacy_sonic_tdr(w.md, w.curve("DT")), cs.md, cs.twt_ms)
assert d.min() == pytest.approx(lo, abs=1.0)
assert d.max() == pytest.approx(hi, abs=1.0)
@needs_f3
@pytest.mark.data
@pytest.mark.parametrize("name", ["F02-1", "F03-2", "F03-4", "F06-1"])
def test_f3_calibrated_tdr(name):
from ml_porosity.data.las_io import load_well
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])
cal = calibrate_to_anchors(base, cs.md, cs.twt_ms)
np.testing.assert_allclose(misfit_at_anchors(cal, cs.md, cs.twt_ms), 0.0, atol=1e-6)
assert np.all(np.diff(cal.twt_ms) > 0)
v = cal.interval_velocity()
assert 1000 < np.percentile(v, 1) and np.percentile(v, 99) < 6000
@needs_f3
@pytest.mark.data
@pytest.mark.parametrize(
"name,mean_ms",
[("F02-1", 40.5), ("F03-2", 40.2), ("F03-4", 25.2), ("F06-1", -14.6)], # plan mục 1.2c
)
def test_f3_dt_model_offset_matches_plan(name, mean_ms):
from ml_porosity.data.las_io import load_td_source, load_well
cs = load_well(name).checkshot
cs = cs[cs.md.between(500, 1300)]
dm = TDR.from_pairs(load_td_source(name, "dt_model"))
d = misfit_at_anchors(dm, cs.md, cs.twt_ms)
assert d.mean() == pytest.approx(mean_ms, abs=0.2)

85
tests/test_volve_io.py Normal file
View File

@@ -0,0 +1,85 @@
import numpy as np
import pytest
import yaml
from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.data.volve_io import VOLVE_KEY_WELLS, read_checkshot, read_horizon, read_well_picks
from ml_porosity.paths import REPO_ROOT, volve_root
GI = volve_root() / "Geophysical_Interpretations"
HUGIN = GI / "Horizons/Horizons_TWT/Official_Horizons/Hugin_Fm_Top+ST10010ZC11_Near_190314+STAT+TIME.dat"
PICKS = GI / "Wells/Well_picks_Volve_v1.dat"
CFG = yaml.safe_load((REPO_ROOT / "configs/d3_volve.yaml").read_text())
VSP = volve_root() / CFG["well_logs_dir"]
CUBE = volve_root() / CFG["cube"]
pytestmark = pytest.mark.skipif(not GI.exists(), reason="thiếu data/Volve/Geophysical_Interpretations")
@pytest.fixture(scope="module")
def hugin():
return read_horizon(HUGIN)
@pytest.fixture(scope="module")
def picks():
return read_well_picks(PICKS)
def test_from_points_recovers_affine():
g0 = SurveyGeometry((1000.0, 3.0, -12.0), (5000.0, 12.0, 3.0), (0, 0, 1), (0, 0, 1), (0, 0, 0))
il, xl = np.meshgrid(np.arange(10, 20), np.arange(100, 130, 2))
g = SurveyGeometry.from_points(il, xl, *g0.bin_to_xy(il, xl))
assert g.x_coef == pytest.approx(g0.x_coef) and g.y_coef == pytest.approx(g0.y_coef)
assert g.il_range == (10, 19, 1) and g.xl_range == (100, 128, 2)
def test_horizon_grid_is_st10010(hugin):
assert hugin.survey == "ST10010" and hugin.domain == "TIME"
g = hugin.geometry()
assert g.bin_spacing() == pytest.approx((12.5, 12.5), abs=1e-3)
x, y = g.bin_to_xy(hugin.il, hugin.xl)
assert np.hypot(x - hugin.x, y - hugin.y).max() < 0.05
i = len(hugin.z) // 2
assert hugin.at(hugin.il[i], hugin.xl[i], radius=0) == pytest.approx(hugin.z[i])
assert np.isnan(hugin.at(0, 0))
def test_well_picks(picks):
assert len(picks) == 409 and picks.well.nunique() == 35
assert set(VOLVE_KEY_WELLS) <= set(picks.well)
assert picks.twt_ms.notna().sum() > 300
deep = picks[picks.well.isin(VOLVE_KEY_WELLS) & picks.twt_ms.between(2280, 2900) & ~picks.qlf.isin(["NL", "NR"])]
assert deep.groupby("well").md.nunique().min() >= 6
@pytest.mark.skipif(not VSP.exists(), reason="thiếu data/Volve/Well_logs_pr_WELL")
def test_checkshot_md_reference(picks):
"""F-15 A: checkshot ghi MD từ MSL, picks lấy TWT từ chính checkshot này nên khớp 0 ms khi MD đã quy về RKB."""
cs = read_checkshot(VSP / "15_9-F-15 A/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC")
p = picks[(picks.well == "NO 15/9-F-15 A") & picks.twt_ms.notna() & picks.md.between(cs.md.min(), cs.md.max())]
assert len(p) >= 5
assert np.abs(p.twt_ms - np.interp(p.md, cs.md, cs.twt_ms)).max() < 0.5
@pytest.mark.skipif(not VSP.exists(), reason="thiếu data/Volve/Well_logs_pr_WELL")
def test_f11t2_picks_vs_nivsp(picks):
cs = read_checkshot(VSP / "15_9-F-11 T2/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC")
p = picks[(picks.well == "NO 15/9-F-11 T2") & picks.twt_ms.notna() & picks.md.between(cs.md.min(), cs.md.max())]
assert len(p) >= 5
assert np.abs(p.twt_ms - np.interp(p.md, cs.md, cs.twt_ms)).max() < 7
@pytest.mark.skipif(not CUBE.exists(), reason="thiếu cube ST10010")
def test_volve_cube(hugin):
"""Byte 215 = 3 không phải scalar thời gian hợp lệ; segyio vẫn nhân delrt với nó nên t0 = 12 ms, đúng là 4 ms
(EBCDIC C11). Cube thiếu 26 trace ở rìa nên phải đọc theo bảng IL/XL từ header."""
with SeismicCube(CUBE) as c:
assert (c.times_ms[0], c.times_ms[-1], c.dt_ms) == (4.0, 3400.0, 4.0)
assert (c.ilines[0], c.ilines[-1], c.xlines[0], c.xlines[-1]) == (9961, 10361, 1961, 2680)
with pytest.raises(KeyError):
c.trace(9961, 1961)
assert c.trace(10150, 2250).shape == (850,)
x, y = c.coords(10150, 2250)
gx, gy = hugin.geometry().bin_to_xy(10150, 2250)
assert np.hypot(x - gx, y - gy) < 0.5