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:
85
tests/test_d2.py
Normal file
85
tests/test_d2.py
Normal file
@@ -0,0 +1,85 @@
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.paths import REPO_ROOT, f3_root
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2.yaml"))
|
||||
INP = P["inputs"]
|
||||
CFG = yaml.safe_load(open(REPO_ROOT / INP["d2_config"]["path"]))
|
||||
NEEDED = [f3_root() / ".survey", REPO_ROOT / CFG["horizon_cache"], REPO_ROOT / INP["warp_prior"]["path"],
|
||||
REPO_ROOT / INP["wavelet"]["path"]]
|
||||
pytestmark = pytest.mark.skipif(not all(p.exists() for p in NEEDED), reason="missing D2 inputs (run scripts/09, 10)")
|
||||
|
||||
RID = P["grid"]["dev_realizations"][0]
|
||||
SIGMA_A = CFG["anchors"]["sigma_a_ms"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def make():
|
||||
hg = load_horizon_grid(CFG["horizons"], REPO_ROOT / CFG["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / INP["warp_prior"]["path"]).read_text())["fits"][INP["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / INP["wavelet"]["path"])[INP["wavelet"]["key"]]
|
||||
return lambda rid: D2Realization(CFG, rid, hg, WarpHyper(**prior["hyper"]), wav)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def R(make):
|
||||
return make(RID)
|
||||
|
||||
|
||||
def test_realization_is_deterministic(make, R):
|
||||
R2 = make(RID)
|
||||
for a, b in zip(R.wells, R2.wells):
|
||||
assert (a.name, a.il, a.xl) == (b.name, b.il, b.xl)
|
||||
for k in ("seis_clean", "noise_unit", "phi_t", "z_g", "boundaries_t", "eps_a"):
|
||||
np.testing.assert_array_equal(getattr(a, k), getattr(b, k))
|
||||
assert a.z_b == b.z_b
|
||||
assert not np.allclose(make(RID + 1).wells[0].phi_t, R.wells[0].phi_t)
|
||||
|
||||
|
||||
def test_wells_are_spatially_separated(R):
|
||||
xy = np.array([[w.x, w.y] for w in R.wells])
|
||||
d = np.hypot(*(xy[:, None] - xy[None]).transpose(2, 0, 1))
|
||||
np.fill_diagonal(d, np.inf)
|
||||
nt = CFG["wells"]["n_test"]
|
||||
assert len(R.test) == nt and len(R.pool) == CFG["wells"]["n_train_pool"]
|
||||
assert d[:nt].min() >= CFG["wells"]["min_dist_test_m"]
|
||||
assert d[nt:, nt:].min() >= CFG["wells"]["min_dist_train_m"]
|
||||
|
||||
|
||||
def test_common_random_numbers_across_drift(R):
|
||||
w = R.pool[0]
|
||||
obs = {c: R.observe(w, c, P["grid"]["snr_db"], SIGMA_A) for c in P["grid"]["drift_factors"]}
|
||||
ref = obs[1.0]
|
||||
for c, o in obs.items():
|
||||
for k in ("seis", "y_true", "t_k"):
|
||||
np.testing.assert_array_equal(o[k], ref[k])
|
||||
np.testing.assert_allclose(o["g"], c * ref["g"], atol=1e-12)
|
||||
assert o["b"] == pytest.approx(c * ref["b"])
|
||||
np.testing.assert_allclose(obs[0.0]["t_of_tau_true"], R.tau_fine, atol=1e-9)
|
||||
np.testing.assert_allclose(obs[0.0]["tau_k"], w.boundaries_t, atol=1e-9)
|
||||
|
||||
|
||||
def test_anchors_and_density_subsets(R):
|
||||
for w in R.wells:
|
||||
bt = w.boundaries_t
|
||||
assert np.all(np.diff(bt) > 0) and R.t_ext[0] <= bt[0] and bt[-1] <= R.t_ext[-1]
|
||||
assert len(w.eps_a) == len(bt) and 10 <= len(bt) <= 20 # F3: 14–17 markers per well
|
||||
w = R.pool[0]
|
||||
n = len(w.boundaries_t)
|
||||
sizes = {d: len(R.observe(w, 1.0, None, SIGMA_A, d)["tau_k"]) for d in ("full", "half", "topbottom", "none")}
|
||||
assert sizes == {"full": n, "half": (n + 1) // 2, "topbottom": 2, "none": 0}
|
||||
|
||||
|
||||
def test_max_drift_stays_in_domain(R):
|
||||
c = max(P["grid"]["drift_factors"])
|
||||
for w in R.wells:
|
||||
o = R.observe(w, c, None, SIGMA_A)
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
assert R.tau_fine[0] <= o["tau_k"].min() and o["tau_k"].max() <= R.tau_fine[-1]
|
||||
assert np.isfinite(R.true_tau_at(o, R.t_ext)).all()
|
||||
@@ -5,7 +5,7 @@ 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")
|
||||
pytestmark = pytest.mark.skipif(not SURVEY.exists(), reason="missing F3 .survey")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -45,7 +45,7 @@ def test_round_trip_vectorised(geom):
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name,xy,expected",
|
||||
[ # bảng IL/XL thật ở plan mục 1.2a
|
||||
[ # true IL/XL table in plan §1.2a
|
||||
("F02-1", (606554, 6080126), (362, 336)),
|
||||
("F03-2", (619101, 6089491), (722, 848)),
|
||||
("F03-4", (623256, 6082586), (442, 1007)),
|
||||
@@ -59,7 +59,7 @@ def test_well_bins_match_plan(geom, name, xy, expected):
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"legacy,xy,km",
|
||||
[ # vị trí luận văn dùng và độ lệch ở plan mục 1.2a
|
||||
[ # locations used in the thesis and their offsets, plan §1.2a
|
||||
((418, 608), (606554, 6080126), 6.94),
|
||||
((362, 821), (623256, 6082586), 5.05),
|
||||
((283, 842), (607903, 6077213), 11.42),
|
||||
|
||||
143
tests/test_losses.py
Normal file
143
tests/test_losses.py
Normal file
@@ -0,0 +1,143 @@
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from scipy import signal
|
||||
|
||||
from ml_porosity.losses.rml import bank_loss, effective_lambda, gather_windows, shift_bank, window_loglik
|
||||
from ml_porosity.losses.softdtw import dilate_loss, dilate_loss_fast, nll_cost, softdtw_loss, softdtw_loss_fast
|
||||
|
||||
WIN = 16
|
||||
F64 = torch.float64
|
||||
|
||||
|
||||
def bank_data(B=3, L=40, S=5, seed=0):
|
||||
g = torch.Generator().manual_seed(seed)
|
||||
mu = torch.randn(B, L, generator=g, dtype=F64)
|
||||
sigma = 0.5 + torch.rand(B, L, generator=g, dtype=F64)
|
||||
Y = mu[:, None, :] + torch.randn(B, S, L, generator=g, dtype=F64)
|
||||
starts = torch.tensor([[0, 6, 24]] * B)
|
||||
return mu, sigma, Y, starts
|
||||
|
||||
|
||||
def random_logpi(B, S, seed=1):
|
||||
return torch.log_softmax(torch.randn(B, S, generator=torch.Generator().manual_seed(seed), dtype=F64), -1)
|
||||
|
||||
|
||||
def gauss_nll(mu, sigma, y, starts):
|
||||
m, s, v = (gather_windows(a, starts, WIN) for a in (mu, sigma, y))
|
||||
return (torch.log(s) + 0.5 * ((v - m) / s) ** 2 + 0.5 * math.log(2 * math.pi)).mean()
|
||||
|
||||
|
||||
def test_gather_windows_matches_slices():
|
||||
_, _, Y, starts = bank_data()
|
||||
w = gather_windows(Y, starts, WIN)
|
||||
assert w.shape == (3, 3, 5, WIN)
|
||||
torch.testing.assert_close(w[1, 2], Y[1, :, 24: 24 + WIN])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lam", [None, 1e-3, 1.0, 50.0])
|
||||
def test_single_or_identical_members_give_gaussian_nll(lam):
|
||||
mu, sigma, Y, starts = bank_data()
|
||||
ref = gauss_nll(mu, sigma, Y[:, 0], starts)
|
||||
one = bank_loss(mu, sigma, Y[:, :1], torch.zeros(3, 1, dtype=F64), starts, WIN, lam)
|
||||
same = bank_loss(mu, sigma, Y[:, :1].expand(3, 4, -1), torch.full((3, 4), -math.log(4), dtype=F64),
|
||||
starts, WIN, lam)
|
||||
torch.testing.assert_close(one, ref)
|
||||
torch.testing.assert_close(same, ref)
|
||||
|
||||
|
||||
def test_rml_between_hard_min_and_mixture_mean():
|
||||
# uniform π: −max ℓ/n ≤ RML_λ ≤ hard-min + log S/(λn), non-increasing in λ; λ → 0 gives −mean ℓ/n
|
||||
mu, sigma, Y, starts = bank_data()
|
||||
S = Y.shape[1]
|
||||
logpi = torch.full((3, S), -math.log(S), dtype=F64)
|
||||
hard = bank_loss(mu, sigma, Y, logpi, starts, WIN, None)
|
||||
mean = -(window_loglik(mu, sigma, Y, starts, WIN).mean(-1) / WIN).mean()
|
||||
lams = [1e-8, 0.01, 0.1, 1.0, 10.0, 1e4]
|
||||
v = [bank_loss(mu, sigma, Y, logpi, starts, WIN, lam) for lam in lams]
|
||||
assert all(a >= b - 1e-12 for a, b in zip(v, v[1:]))
|
||||
for lam, x in zip(lams, v):
|
||||
assert hard - 1e-12 <= x <= hard + math.log(S) / (lam * WIN) + 1e-12
|
||||
torch.testing.assert_close(v[0], mean, rtol=0, atol=1e-6)
|
||||
|
||||
|
||||
def test_rml_small_lambda_is_pi_weighted_nll():
|
||||
mu, sigma, Y, starts = bank_data()
|
||||
logpi = random_logpi(3, Y.shape[1])
|
||||
ll = window_loglik(mu, sigma, Y, starts, WIN)
|
||||
ref = -((ll * logpi.exp()[:, None, :]).sum(-1) / WIN).mean()
|
||||
torch.testing.assert_close(bank_loss(mu, sigma, Y, logpi, starts, WIN, 1e-7), ref, rtol=0, atol=1e-6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lam", [0.05, 1.0])
|
||||
def test_rml_gradient_is_responsibility_weighted(lam):
|
||||
# ∇ RML = −(1/n) Σ_s r_s ∇ℓ_s with r = softmax(log π + λℓ)
|
||||
mu, sigma, Y, starts = bank_data()
|
||||
logpi = random_logpi(3, Y.shape[1])
|
||||
mu.requires_grad_(True)
|
||||
sigma.requires_grad_(True)
|
||||
g = torch.autograd.grad(bank_loss(mu, sigma, Y, logpi, starts, WIN, lam), (mu, sigma))
|
||||
ll = window_loglik(mu, sigma, Y, starts, WIN)
|
||||
r = torch.softmax(logpi[:, None, :] + lam * ll, -1).detach()
|
||||
g_ref = torch.autograd.grad(-((r * ll).sum(-1) / WIN).mean(), (mu, sigma))
|
||||
for a, b in zip(g, g_ref):
|
||||
torch.testing.assert_close(a, b)
|
||||
|
||||
|
||||
def test_shift_bank_rows_are_label_shifts():
|
||||
y = np.arange(10.0)
|
||||
bank = shift_bank(y, 2)
|
||||
assert bank.shape == (5, 10)
|
||||
np.testing.assert_array_equal(bank[2], y)
|
||||
np.testing.assert_array_equal(bank[3, :9], y[1:]) # k = +1: y_{i+1}
|
||||
np.testing.assert_array_equal(bank[0, 2:], y[:8]) # k = −2: y_{i−2}
|
||||
assert np.isnan(bank[3, 9]) and np.isnan(bank[0, :2]).all()
|
||||
|
||||
|
||||
def dtw_data(B=3, n=12, seed=0):
|
||||
g = torch.Generator().manual_seed(seed)
|
||||
mu = torch.randn(B, n, generator=g, dtype=F64)
|
||||
sigma = 0.3 + torch.rand(B, n, generator=g, dtype=F64)
|
||||
y = torch.roll(mu, 1, -1) + 0.3 * torch.randn(B, n, generator=g, dtype=F64)
|
||||
return mu, sigma, y
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fast", [False, True])
|
||||
def test_band0_reduces_to_nll(fast):
|
||||
# band 0 leaves only the diagonal: soft-DTW/(2n) = mean NLL, TDI = 0
|
||||
mu, sigma, y = dtw_data()
|
||||
nll = torch.diagonal(nll_cost(mu, sigma, y), dim1=1, dim2=2).mean()
|
||||
sd, dl = (softdtw_loss_fast, dilate_loss_fast) if fast else (softdtw_loss, dilate_loss)
|
||||
torch.testing.assert_close(sd(mu, sigma, y, gamma=0.1, band=0), nll)
|
||||
torch.testing.assert_close(dl(mu, sigma, y, alpha=0.3, gamma=0.1, band=0), 0.3 * nll)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["softdtw", "dilate"])
|
||||
@pytest.mark.parametrize("band", [4, None])
|
||||
@pytest.mark.parametrize("gamma", [0.1, 1.0])
|
||||
def test_fast_matches_autograd(kind, band, gamma):
|
||||
mu, sigma, y = dtw_data(seed=2)
|
||||
if kind == "softdtw":
|
||||
fns = [lambda m, s: f(m, s, y, gamma=gamma, band=band) for f in (softdtw_loss, softdtw_loss_fast)]
|
||||
else:
|
||||
fns = [lambda m, s: f(m, s, y, alpha=0.5, gamma=gamma, band=band) for f in (dilate_loss, dilate_loss_fast)]
|
||||
out = []
|
||||
for fn in fns:
|
||||
m, s = mu.clone().requires_grad_(True), sigma.clone().requires_grad_(True)
|
||||
v = fn(m, s)
|
||||
out.append((v.detach(), *torch.autograd.grad(v, (m, s))))
|
||||
for a, b in zip(*out):
|
||||
torch.testing.assert_close(b, a, rtol=1e-7, atol=1e-10)
|
||||
|
||||
|
||||
def test_effective_lambda_grows_with_correlation():
|
||||
rng = np.random.default_rng(0)
|
||||
white = [rng.standard_normal(400) for _ in range(4)]
|
||||
sos = signal.butter(4, 20, fs=250, output="sos")
|
||||
smooth = [signal.sosfiltfilt(sos, w) for w in white]
|
||||
lam_w, tau_w = effective_lambda(white)
|
||||
lam_s, tau_s = effective_lambda(smooth)
|
||||
assert tau_w < 1.3 and tau_s > 2.0
|
||||
assert lam_w == pytest.approx(1 / tau_w) and lam_s == pytest.approx(1 / tau_s)
|
||||
@@ -10,7 +10,7 @@ def test_cnn_gru_shape():
|
||||
|
||||
|
||||
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)
|
||||
# plan §1.1 #7: L_shape = 2·L_PCC − 2/L (z-score uses the unbiased std, Σ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)
|
||||
|
||||
@@ -38,7 +38,7 @@ def test_strat_map_identity_and_shift():
|
||||
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
|
||||
# linear stretch between two horizons
|
||||
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)
|
||||
|
||||
@@ -58,4 +58,4 @@ def test_gaussian_metrics_calibrated():
|
||||
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)
|
||||
assert g["crps"] == pytest.approx(1 / np.sqrt(np.pi), abs=0.01) # E[CRPS] for a correct N(0, 1) forecast
|
||||
|
||||
43
tests/test_protocol.py
Normal file
43
tests/test_protocol.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
|
||||
CONFIGS = REPO_ROOT / "configs"
|
||||
|
||||
|
||||
def test_d2_p3_generator_matches_p2():
|
||||
"""protocol_p3 uses the protocol_p2 D2 generator: only the regimes block may be added."""
|
||||
p2 = yaml.safe_load((CONFIGS / "d2_synth.yaml").read_text())
|
||||
p3 = yaml.safe_load((CONFIGS / "d2_synth_p3.yaml").read_text())
|
||||
regimes = p3.pop("regimes")
|
||||
assert p3 == p2
|
||||
assert all(set(r) == {"snr_db", "anchor_density"} for r in regimes.values())
|
||||
|
||||
|
||||
def test_p3_regimes_and_realizations():
|
||||
P = yaml.safe_load((CONFIGS / "protocol_p3.yaml").read_text())
|
||||
regimes = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())["regimes"]
|
||||
assert set(P["grid"]["regimes"]) <= set(regimes)
|
||||
p2 = yaml.safe_load((CONFIGS / "protocol_p2.yaml").read_text())["grid"]
|
||||
used = set(p2["realizations"]) | set(p2["dev_realizations"])
|
||||
assert not used & set(P["grid"]["realizations"])
|
||||
|
||||
|
||||
def test_locked_protocols_match_sha256():
|
||||
"""Locked protocols must not change after locking (a change needs a new version)."""
|
||||
import hashlib
|
||||
|
||||
for name in ["protocol_p2", "protocol_p3"]:
|
||||
sha, path = (CONFIGS / f"{name}.sha256").read_text().split()
|
||||
assert hashlib.sha256((REPO_ROOT / path).read_bytes()).hexdigest() == sha
|
||||
|
||||
|
||||
def test_p3_inputs_match_sha256():
|
||||
import hashlib
|
||||
|
||||
P = yaml.safe_load((CONFIGS / "protocol_p3.yaml").read_text())
|
||||
for key in ["d2_config", "budgets", "warp_prior", "wavelet"]:
|
||||
f = REPO_ROOT / P["inputs"][key]["path"]
|
||||
if not f.exists(): # outputs/ is not versioned
|
||||
continue
|
||||
assert hashlib.sha256(f.read_bytes()).hexdigest() == P["inputs"][key]["sha256"], key
|
||||
262
tests/test_registration.py
Normal file
262
tests/test_registration.py
Normal file
@@ -0,0 +1,262 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from ml_porosity.data.wavelet import convolve_same, ricker, rotate_phase
|
||||
from ml_porosity.registration.labels import invert_warps, labels_for_warps
|
||||
from ml_porosity.registration.sampler import ess, sample_warps, temper
|
||||
from ml_porosity.registration.smc import (TiePosterior, ess_moves, next_gamma, phase_basis, phase_wavelet,
|
||||
residual_kappa, smc_fit_phase, smc_tie_posterior)
|
||||
from ml_porosity.registration.tie_likelihood import (fine_wavelet, fit_phase, phase_loglik, profile_loglik,
|
||||
synth_for_warps)
|
||||
from ml_porosity.registration.ties import clean_monotone, tie_b3a, tie_b3b, warp_errors
|
||||
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, kernel_matrix
|
||||
|
||||
PHASES = np.arange(-180, 180, 15)
|
||||
|
||||
|
||||
def test_invert_warps_linear_map():
|
||||
tau = np.arange(400.0, 1300.1, 4.0)
|
||||
t_out = np.array([350.0, 600.0, 1000.0, 1500.0])
|
||||
T = invert_warps(np.stack([1.1 * tau + 5, tau - 20]), tau, t_out)
|
||||
np.testing.assert_allclose(T[0, 1:3], (t_out[1:3] - 5) / 1.1)
|
||||
np.testing.assert_allclose(T[1, 1:3], t_out[1:3] + 20)
|
||||
assert np.isnan(T[:, [0, 3]]).all()
|
||||
|
||||
|
||||
def test_labels_for_shifted_warps():
|
||||
tau = np.arange(400.0, 1300.1, 0.5)
|
||||
t_out = np.arange(600.0, 1100.1, 4.0)
|
||||
lab = labels_for_warps(tau, np.sin(tau / 30.0), np.stack([tau, tau + 8.0]), t_out)
|
||||
np.testing.assert_allclose(lab[0], np.sin(t_out / 30.0), atol=1e-12)
|
||||
np.testing.assert_allclose(lab[1], np.sin((t_out - 8.0) / 30.0), atol=1e-12)
|
||||
|
||||
|
||||
def test_sample_warps_honour_tight_anchors():
|
||||
grid = WarpGrid(400.0, 1300.0, 4.0)
|
||||
h = WarpHyper(m_g=0.0, sigma_g=0.1, ell_ms=70.0, sigma_b_ms=20.0, sigma_a_ms=0.5)
|
||||
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
|
||||
g = np.linalg.cholesky(K + 1e-8 * np.eye(grid.n)) @ np.random.default_rng(3).standard_normal(grid.n)
|
||||
b = 15.0
|
||||
tau_k = np.array([450.0, 610.0, 800.0, 950.0, 1200.0])
|
||||
t_k = grid.t_of_tau(b, g, tau_k)[0]
|
||||
out = sample_warps(grid, h, tau_k, t_k, n_samples=32, g_max=1.0, rng=np.random.default_rng(0))
|
||||
T = grid.t_of_tau(out["b"], out["g"], tau_k)
|
||||
assert np.sqrt(np.mean((T - t_k) ** 2)) < 2 * h.sigma_a_ms # posterior ≈ σ_a; prior ≥ σ_b = 20 ms
|
||||
mid = np.array([530.0, 875.0, 1075.0])
|
||||
err = np.abs(grid.t_of_tau(out["b"], out["g"], mid).mean(0) - grid.t_of_tau(b, g, mid)[0])
|
||||
assert err.max() < 0.5 * h.sigma_b_ms
|
||||
|
||||
|
||||
def test_temper_equal_loglik_keeps_gamma_one():
|
||||
lw, g, e = temper(np.full(64, -3.0))
|
||||
assert g == 1.0 and e == pytest.approx(64)
|
||||
np.testing.assert_allclose(lw, -np.log(64))
|
||||
|
||||
|
||||
def test_temper_largest_gamma_with_target_ess():
|
||||
ll = 50 * np.random.default_rng(0).standard_normal(64)
|
||||
lw, g, e = temper(ll, min_frac=0.25, tol=1e-3)
|
||||
assert 0.0 < g < 1.0 and e >= 16 - 1e-9
|
||||
assert ess((g + 1e-3) * ll) < 16
|
||||
np.testing.assert_allclose(lw, g * ll - np.logaddexp.reduce(g * ll))
|
||||
|
||||
|
||||
def test_clean_monotone_and_point_ties():
|
||||
tau_k = np.array([800.0, 500.0, 600.0, 700.0, 1000.0])
|
||||
t_k = np.array([820.0, 510.0, 620.0, 615.0, 1030.0])
|
||||
tk, ttk = clean_monotone(tau_k, t_k)
|
||||
assert len(tk) == 4 and np.all(np.diff(tk) > 0) and np.all(np.diff(ttk) > 0)
|
||||
tau = np.arange(400.0, 1300.1, 0.5)
|
||||
np.testing.assert_allclose(tie_b3a(tau_k, t_k, tau), tau + 10.0)
|
||||
t = tie_b3b(tau_k, t_k, tau)
|
||||
assert np.all(np.diff(t) > 0)
|
||||
np.testing.assert_allclose(np.interp(tk, tau, t), ttk, atol=1e-6)
|
||||
|
||||
|
||||
def test_warp_errors_perfect_and_bracketing():
|
||||
tau = np.arange(400.0, 1300.1, 1.0)
|
||||
t_true = tau + 10.0
|
||||
t_eval = np.arange(600.0, 1100.1, 4.0)
|
||||
assert warp_errors(t_true[None], tau, t_true, t_eval)["warp_rmse_ms"] == pytest.approx(0.0, abs=1e-9)
|
||||
e = warp_errors(t_true[None] + np.linspace(-5, 5, 21)[:, None], tau, t_true, t_eval)
|
||||
assert e["warp_rmse_ms"] == pytest.approx(0.0, abs=1e-9) and e["warp_cov90"] == 1.0
|
||||
assert e["warp_width90_ms"] == pytest.approx(9.0)
|
||||
|
||||
|
||||
def synth(seed, n=300):
|
||||
rng = np.random.default_rng(seed)
|
||||
return convolve_same(rng.standard_normal(n) * (rng.random(n) < 0.3), ricker(30))
|
||||
|
||||
|
||||
def test_profile_loglik_respects_polarity():
|
||||
s = synth(0)
|
||||
seis = s + 0.05 * s.std() * np.random.default_rng(1).standard_normal(len(s))
|
||||
ll = profile_loglik(np.stack([s, -s, 2.0 * s]), seis)
|
||||
assert ll[0] > ll[1]
|
||||
assert ll[2] == pytest.approx(ll[0])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", [0, 45, -90])
|
||||
def test_fit_phase_recovers_constant_rotation(phase):
|
||||
rng = np.random.default_rng(2)
|
||||
ll, ok = [], []
|
||||
for w in range(2):
|
||||
s = synth(10 + w)
|
||||
seis = rotate_phase(s, phase) + 0.1 * s.std() * rng.standard_normal(len(s))
|
||||
bank = np.stack([np.roll(s, k) for k in (-1, 0, 1)]) # warp samples around the true warp
|
||||
ll.append(phase_loglik(bank, seis, PHASES))
|
||||
ok.append(np.ones(3, bool))
|
||||
assert PHASES[fit_phase(ll, ok, PHASES)] == phase
|
||||
|
||||
|
||||
def tie_toy(seed: int = 0, phase: float = 0.0) -> dict:
|
||||
"""A toy well: true warp drawn from the prior, blocky AI, seismic = synthetic (30 Hz Ricker rotated by `phase`)
|
||||
+ 10% white noise, 4 anchors with σ_a = 3 ms."""
|
||||
rng = np.random.default_rng(seed)
|
||||
grid = WarpGrid(400.0, 1000.0, 4.0)
|
||||
h = WarpHyper(m_g=0.0, sigma_g=0.05, ell_ms=80.0, sigma_b_ms=20.0, sigma_a_ms=3.0)
|
||||
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
|
||||
g = np.linalg.cholesky(K + 1e-8 * np.eye(grid.n)) @ rng.standard_normal(grid.n)
|
||||
tau_fine = np.arange(grid.tau[0], grid.tau[-1] + 0.25, 0.5)
|
||||
ai = np.exp(np.cumsum(0.1 * rng.standard_normal(len(tau_fine)) * (rng.random(len(tau_fine)) < 0.04)))
|
||||
t_fine, t_out = np.arange(300.0, 1100.0, 0.5), np.arange(500.0, 900.1, 4.0)
|
||||
w_fine = fine_wavelet(rotate_phase(ricker(30), phase), 8)
|
||||
tau_k = np.linspace(450.0, 950.0, 4)
|
||||
t_k = grid.t_of_tau(5.0, g, tau_k)[0] + h.sigma_a_ms * rng.standard_normal(4)
|
||||
t_true = grid.t_of_tau(5.0, g, tau=tau_fine)[0]
|
||||
s = synth_for_warps(tau_fine, ai, t_true, t_fine, t_out, w_fine)[0]
|
||||
seis = s + 0.1 * s.std() * rng.standard_normal(len(s))
|
||||
T = TiePosterior(grid, h, tau_k, t_k, 1.0, tau_fine, ai, t_fine, t_out, w_fine, seis, (t_out[0], t_out[-1]))
|
||||
return dict(grid=grid, h=h, T=T, tau_fine=tau_fine, ai=ai, t_fine=t_fine, t_out=t_out, w_fine=w_fine,
|
||||
tau_k=tau_k, t_k=t_k, t_true=t_true)
|
||||
|
||||
|
||||
def anchor_samples(d: dict, n: int, seed: int) -> np.ndarray:
|
||||
return sample_warps(d["grid"], d["h"], d["tau_k"], d["t_k"], n, 1.0, np.random.default_rng(seed))["u"]
|
||||
|
||||
|
||||
def test_tie_posterior_synth_matches_synth_for_warps():
|
||||
d = tie_toy()
|
||||
T, U = d["T"], anchor_samples(d, 8, 1)
|
||||
np.testing.assert_allclose(T.u(T.z(U)), U, atol=1e-8)
|
||||
Tf = d["grid"].t_of_tau(U[:, 0], U[:, 1:], tau=d["tau_fine"])
|
||||
for w in (d["w_fine"], fine_wavelet(rotate_phase(ricker(25, length_ms=200.0), 40.0), 8)): # also a longer wavelet
|
||||
ref = synth_for_warps(d["tau_fine"], d["ai"], Tf, d["t_fine"], d["t_out"], w)
|
||||
np.testing.assert_allclose(T.with_wavelet(w).synth(U), ref, rtol=1e-9, atol=1e-12)
|
||||
np.testing.assert_array_equal(T.w_fine, d["w_fine"])
|
||||
|
||||
|
||||
def test_residual_kappa_white_vs_band_limited_noise():
|
||||
rng = np.random.default_rng(4)
|
||||
s = synth(20, n=2000)
|
||||
nb = convolve_same(rng.standard_normal(len(s)), ricker(30))
|
||||
assert residual_kappa(s, s + 0.5 * s.std() * rng.standard_normal(len(s))) < 1.2
|
||||
assert residual_kappa(s, s + 0.5 * s.std() * nb / nb.std()) > 1.5
|
||||
|
||||
|
||||
def test_next_gamma_largest_step_with_target_ess():
|
||||
ll = 30 * np.random.default_rng(5).standard_normal(128)
|
||||
g = next_gamma(ll, 0.2, 1.0, 0.5)
|
||||
assert 0.2 < g < 1.0 and ess((g - 0.2) * ll) >= 64 - 1e-6
|
||||
assert ess((g - 0.2 + 1e-3) * ll) < 64
|
||||
assert next_gamma(np.zeros(128), 0.2, 0.7) == 0.7
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", [-45, 0, 30, 90])
|
||||
def test_phase_basis_is_exact_rotation(phase):
|
||||
w0 = ricker(30)
|
||||
np.testing.assert_allclose(phase_wavelet(phase_basis(w0, 8), phase), fine_wavelet(rotate_phase(w0, phase), 8),
|
||||
atol=1e-12)
|
||||
|
||||
|
||||
def test_smc_concentrates_on_true_warp():
|
||||
d = tie_toy(seed=2)
|
||||
T, U0 = d["T"], anchor_samples(d, 64, 3)
|
||||
res = smc_tie_posterior(T, T.z(U0), [0.3, 1.0], np.random.default_rng(4))
|
||||
err = lambda U: warp_errors(d["grid"].t_of_tau(U[:, 0], U[:, 1:], tau=d["tau_fine"]), d["tau_fine"],
|
||||
d["t_true"], d["t_out"])["warp_rmse_ms"]
|
||||
assert err(T.u(res["Z"][1.0])) < 0.5 * err(U0)
|
||||
assert np.all(np.isfinite(T.parts(res["Z"][1.0])[0]))
|
||||
assert res["stages"][-1]["gamma"] == 1.0 and all(s["ess"] >= 32 - 1e-6 for s in res["stages"])
|
||||
assert np.isfinite(res["logZ"][0.3]) and np.isfinite(res["logZ"][1.0])
|
||||
|
||||
|
||||
def test_smc_fit_phase_recovers_rotation():
|
||||
wells = [tie_toy(seed=s, phase=30.0) for s in (5, 6)]
|
||||
Z0s = [d["T"].z(anchor_samples(d, 32, i)) for i, d in enumerate(wells)]
|
||||
phi, info = smc_fit_phase([d["T"] for d in wells], Z0s, phase_basis(ricker(30), 8), 0.0, [0])
|
||||
assert abs(phi - 30.0) < 10.0 and not info["edge"]
|
||||
|
||||
|
||||
def torch_tie(T):
|
||||
torch = pytest.importorskip("torch")
|
||||
from ml_porosity.registration.smc_torch import TiePosteriorTorch
|
||||
return TiePosteriorTorch(T, "cuda:1" if torch.cuda.device_count() > 1 else "cpu")
|
||||
|
||||
|
||||
def test_torch_tie_posterior_matches_cpu():
|
||||
d = tie_toy()
|
||||
T = d["T"]
|
||||
G = torch_tie(T)
|
||||
Z = T.z(anchor_samples(d, 8, 1))
|
||||
Z = np.vstack([Z, 40.0 * Z[:2]]) # two particles violate |g| ≤ g_max
|
||||
for w in (d["w_fine"], fine_wavelet(rotate_phase(ricker(25, length_ms=200.0), 40.0), 8)):
|
||||
Tw, Gw = T.with_wavelet(w), G.with_wavelet(w)
|
||||
np.testing.assert_allclose(Gw.synth(T.u(Z)), Tw.synth(T.u(Z)), rtol=1e-9, atol=1e-12)
|
||||
(bc, lc), (bg, lg) = Tw.parts(Z), Gw.parts(Z)
|
||||
assert not np.isfinite(bc[-2:]).any()
|
||||
np.testing.assert_array_equal(np.isfinite(bg), np.isfinite(bc))
|
||||
np.testing.assert_array_equal(np.isfinite(lg), np.isfinite(lc))
|
||||
ok = np.isfinite(bc)
|
||||
np.testing.assert_allclose(bg[ok], bc[ok], rtol=1e-10)
|
||||
np.testing.assert_allclose(lg[ok], lc[ok], rtol=1e-10)
|
||||
assert Gw.n_eval == Tw.n_eval
|
||||
np.testing.assert_allclose(Gw.reference(Z[:8].mean(0), 0.5)[1], Tw.reference(Z[:8].mean(0), 0.5)[1],
|
||||
rtol=1e-9, atol=1e-12)
|
||||
|
||||
|
||||
def test_torch_ess_moves_match_cpu():
|
||||
from ml_porosity.registration import smc_torch
|
||||
d = tie_toy(seed=2)
|
||||
T = d["T"]
|
||||
G = torch_tie(T)
|
||||
Z = T.z(anchor_samples(d, 32, 3))
|
||||
base, ll = T.parts(Z)
|
||||
ref = T.reference(Z.mean(0), 0.3)
|
||||
oc = ess_moves(T, Z, base, ll, 0.3, ref, 3, np.random.default_rng(7))
|
||||
og = smc_torch.ess_moves(G, *map(G.tensor, (Z, base, ll)), 0.3, tuple(map(G.tensor, ref)), 3,
|
||||
np.random.default_rng(7))
|
||||
for a, b in zip(oc[:3], og[:3]):
|
||||
np.testing.assert_allclose(b.cpu().numpy(), a, rtol=1e-8, atol=1e-10)
|
||||
assert og[3] == oc[3]
|
||||
|
||||
|
||||
def test_torch_ess_moves_memory_bounded():
|
||||
"""Each call captures a new CUDA graph; retained memory must not grow with the number of calls."""
|
||||
torch = pytest.importorskip("torch")
|
||||
from ml_porosity.registration import smc_torch
|
||||
d = tie_toy(seed=2)
|
||||
G = torch_tie(d["T"])
|
||||
if G.device.type != "cuda":
|
||||
pytest.skip("requires CUDA")
|
||||
Z = G.tensor(d["T"].z(anchor_samples(d, 32, 3)))
|
||||
base, ll = G.parts_t(Z)
|
||||
ref = G.reference_t(Z.mean(0), 0.3)
|
||||
run = lambda: smc_torch.ess_moves(G, Z, base, ll, 0.3, ref, 1, np.random.default_rng(0))
|
||||
run()
|
||||
r0 = torch.cuda.memory_reserved(G.device)
|
||||
for _ in range(5):
|
||||
run()
|
||||
assert torch.cuda.memory_reserved(G.device) == r0
|
||||
|
||||
|
||||
def test_torch_smc_matches_cpu():
|
||||
from ml_porosity.registration import smc_torch
|
||||
d = tie_toy(seed=2)
|
||||
T, U0 = d["T"], anchor_samples(d, 64, 3)
|
||||
rc = smc_tie_posterior(T, T.z(U0), [0.3, 1.0], np.random.default_rng(4))
|
||||
rg = smc_torch.smc_tie_posterior(torch_tie(T), T.z(U0), [0.3, 1.0], np.random.default_rng(4))
|
||||
np.testing.assert_allclose([s["gamma"] for s in rg["stages"]], [s["gamma"] for s in rc["stages"]], rtol=1e-9)
|
||||
for g in (0.3, 1.0):
|
||||
assert rg["logZ"][g] == pytest.approx(rc["logZ"][g], rel=1e-9)
|
||||
np.testing.assert_allclose(rg["Z"][g], rc["Z"][g], atol=1e-7)
|
||||
70
tests/test_runlog.py
Normal file
70
tests/test_runlog.py
Normal file
@@ -0,0 +1,70 @@
|
||||
"""ml_porosity.runlog: the log captures child workers, meta/index record the correct status, nested runs, signal forwarding."""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
|
||||
CHILD = ("import subprocess, sys; print('out-parent'); print('err-parent', file=sys.stderr); "
|
||||
"subprocess.run([sys.executable, '-c', 'print(\"out-child\")']); sys.exit(int(sys.argv[1]))")
|
||||
|
||||
|
||||
def launch(tmp: Path, *args: str, env: dict | None = None, **kw) -> subprocess.Popen:
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("RUNLOG_")} | {"ML_POROSITY_LOGS": str(tmp)} | (env or {})
|
||||
return subprocess.Popen([sys.executable, "-m", "ml_porosity.runlog", *args], cwd=REPO_ROOT, env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kw)
|
||||
|
||||
|
||||
def runs(tmp: Path) -> list[Path]:
|
||||
return sorted((tmp / "runs").iterdir())
|
||||
|
||||
|
||||
def test_log_meta_index(tmp_path):
|
||||
p = launch(tmp_path, "-n", "demo", "--", sys.executable, "-c", CHILD, "0")
|
||||
out, _ = p.communicate(timeout=60)
|
||||
assert p.returncode == 0 and "out-child" in out # still echoed to the terminal
|
||||
(d,) = runs(tmp_path)
|
||||
log = (d / "log.txt").read_text()
|
||||
assert all(s in log for s in ("out-parent", "err-parent", "out-child")) and "[0:00:00] out-parent" in log
|
||||
meta = json.loads((d / "meta.json").read_text())
|
||||
assert meta["status"] == "ok" and meta["exit_code"] == 0 and meta["wall_s"] >= 0 and meta["git"]["code_sha256"]
|
||||
(row,) = list(csv.DictReader(open(tmp_path / "index.csv")))
|
||||
assert row["name"] == "demo" and row["status"] == "ok" and row["parent"] == ""
|
||||
|
||||
|
||||
def test_failure_keeps_exit_code(tmp_path):
|
||||
p = launch(tmp_path, sys.executable, "-c", CHILD, "3")
|
||||
p.communicate(timeout=60)
|
||||
assert p.returncode == 3
|
||||
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
|
||||
assert meta["status"] == "failed" and meta["exit_code"] == 3
|
||||
|
||||
|
||||
def test_nested_steps_go_into_parent(tmp_path):
|
||||
inner = f"{sys.executable} -m ml_porosity.runlog -n step -- {sys.executable} -c 'print(1)'"
|
||||
p = launch(tmp_path, "-n", "parent", "--", "bash", "-c", f"{inner} && {inner}")
|
||||
p.communicate(timeout=60)
|
||||
assert p.returncode == 0
|
||||
(d,) = runs(tmp_path)
|
||||
assert sorted(x.name for x in d.iterdir() if x.is_dir()) == ["01_step", "02_step"]
|
||||
rows = list(csv.DictReader(open(tmp_path / "index.csv")))
|
||||
assert [r["parent"] for r in rows] == [d.name, d.name, ""]
|
||||
|
||||
|
||||
def test_sigterm_marks_interrupted(tmp_path):
|
||||
p = launch(tmp_path, sys.executable, "-c", "import time; print('started', flush=True); time.sleep(60)")
|
||||
t0 = time.time()
|
||||
while not (tmp_path / "runs").exists() or not any((d / "log.txt").exists() and "started" in (d / "log.txt").read_text()
|
||||
for d in runs(tmp_path)):
|
||||
assert time.time() - t0 < 30
|
||||
time.sleep(0.1)
|
||||
p.send_signal(signal.SIGTERM)
|
||||
p.communicate(timeout=30)
|
||||
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
|
||||
assert meta["status"] == "interrupted" and meta["signals"] == ["SIGTERM"] and p.returncode == 128 + signal.SIGTERM
|
||||
@@ -8,7 +8,7 @@ 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.mark.skipif(not f3_segy().exists(), reason="missing F3_entire.segy"),
|
||||
]
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ def cube():
|
||||
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
|
||||
# DelayRecordingTime = 4 ms: the first sample is at 4 ms, not 0
|
||||
assert cube.times_ms[0] == 4.0 and cube.dt_ms == 4.0 and len(cube.times_ms) == 462
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ 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
|
||||
# Header coordinates (scalar −100) match the .survey transform
|
||||
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)
|
||||
|
||||
@@ -11,7 +11,7 @@ from ml_porosity.data.tdr import (
|
||||
)
|
||||
from ml_porosity.paths import f3_wells_dir
|
||||
|
||||
# ---------- tổng hợp, không cần dữ liệu ----------
|
||||
# ---------- synthetic, no data required ----------
|
||||
|
||||
|
||||
def constant_velocity_log(v=2000.0, z0=0.0, z1=1000.0, dz=0.5):
|
||||
@@ -51,13 +51,13 @@ def test_legacy_starts_at_zero():
|
||||
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.
|
||||
# Anchors offset by up to ±40 ms from the sonic, an F06-1-style drift.
|
||||
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)
|
||||
ta = za + np.array([5.0, -20.0, 30.0, -40.0, 10.0]) # at 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
|
||||
# outside the anchor range: constant shift from the nearest anchor
|
||||
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)
|
||||
|
||||
@@ -78,7 +78,7 @@ def test_calibration_rejects_crossing_anchors():
|
||||
|
||||
|
||||
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.
|
||||
# A log linear in time is preserved; a 200 Hz sine (above the 125 Hz Nyquist of 4 ms) is filtered out.
|
||||
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)
|
||||
@@ -93,23 +93,23 @@ 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
|
||||
v[(md > 400) & (md < 450)] = np.nan # 50 ms gap
|
||||
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 ----------
|
||||
# ---------- on F3 data ----------
|
||||
|
||||
needs_f3 = pytest.mark.skipif(not (f3_wells_dir() / "Lasfiles").exists(), reason="thiếu dữ liệu giếng F3")
|
||||
needs_f3 = pytest.mark.skipif(not (f3_wells_dir() / "Lasfiles").exists(), reason="missing F3 well data")
|
||||
|
||||
|
||||
@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
|
||||
[ # plan §1.2b and §1.2e: integrated-DT TWT − TD marker within 600–1100 ms
|
||||
("F02-1", 11, -44, 2),
|
||||
("F03-2", 9, -14, -3),
|
||||
("F03-4", 9, -52, -42),
|
||||
@@ -147,7 +147,7 @@ def test_f3_calibrated_tdr(name):
|
||||
@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
|
||||
[("F02-1", 40.5), ("F03-2", 40.2), ("F03-4", 25.2), ("F06-1", -14.6)], # plan §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
|
||||
|
||||
@@ -13,7 +13,7 @@ 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")
|
||||
pytestmark = pytest.mark.skipif(not GI.exists(), reason="missing data/Volve/Geophysical_Interpretations")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -53,16 +53,16 @@ def test_well_picks(picks):
|
||||
assert deep.groupby("well").md.nunique().min() >= 6
|
||||
|
||||
|
||||
@pytest.mark.skipif(not VSP.exists(), reason="thiếu data/Volve/Well_logs_pr_WELL")
|
||||
@pytest.mark.skipif(not VSP.exists(), reason="missing 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."""
|
||||
"""F-15 A: the checkshot records MD from MSL and the picks take their TWT from this same checkshot, so they match to 0 ms once MD is referenced to 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")
|
||||
@pytest.mark.skipif(not VSP.exists(), reason="missing 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())]
|
||||
@@ -70,10 +70,10 @@ def test_f11t2_picks_vs_nivsp(picks):
|
||||
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")
|
||||
@pytest.mark.skipif(not CUBE.exists(), reason="missing ST10010 cube")
|
||||
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."""
|
||||
"""Byte 215 = 3 is not a valid time scalar; segyio still multiplies delrt by it, giving t0 = 12 ms instead of the correct
|
||||
4 ms (EBCDIC C11). The cube lacks 26 edge traces, so it must be read via the IL/XL table from the headers."""
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user