P2 diagnosis on dev, P3 dev experiments, lock protocol_p3

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

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

View File

@@ -1,12 +1,13 @@
"""Quan hệ thời gian–độ sâu (TDR): MD (m, từ KB) ↔ TWT (ms, từ datum seismic).
"""Time–depth relationship (TDR): MD (m, from KB) ↔ TWT (ms, from the seismic datum).
Ba cách dựng TDR:
* `legacy_sonic_tdr` – tái hiện cách của luận văn (prepare_data.py:110): tích phân DT
với t = 0 tại mẫu LAS đầu tiên, không hiệu chỉnh drift. Chỉ dùng để audit.
* `sonic_tdr` – tích phân DT bắt đầu từ một điểm neo (md0, t0).
* `calibrate_to_anchors` – hiệu chỉnh drift: co giãn thời gian sonic trong từng khoảng
giữa hai anchor để đi qua đúng mọi anchor. Vì hệ số co giãn
của mỗi khoảng dương, TDR kết quả luôn đơn điệu tăng.
Three ways of constructing a TDR:
* `legacy_sonic_tdr` – reproduces the thesis approach (prepare_data.py:110): integrates DT
with t = 0 at the first LAS sample, without drift correction. For auditing only.
* `sonic_tdr` – integrates DT starting from an anchor point (md0, t0).
* `calibrate_to_anchors` – drift correction: stretches/squeezes the sonic time within each
interval between consecutive anchors so that every anchor is honoured
exactly. Since each interval's stretch factor is positive, the resulting
TDR is always monotonically increasing.
"""
from __future__ import annotations
@@ -21,26 +22,26 @@ US_PER_M_TO_S_PER_M = 1e-6
@dataclass(frozen=True)
class TDR:
md: np.ndarray # (N,) tăng nghiêm ngặt
twt_ms: np.ndarray # (N,) tăng nghiêm ngặt
md: np.ndarray # (N,) strictly increasing
twt_ms: np.ndarray # (N,) strictly increasing
name: str = ""
def __post_init__(self):
md = np.asarray(self.md, dtype=float)
t = np.asarray(self.twt_ms, dtype=float)
if md.shape != t.shape or md.ndim != 1 or md.size < 2:
raise ValueError("md và twt_ms phải là mảng 1D cùng độ dài ≥ 2")
raise ValueError("md and twt_ms must be 1-D arrays of equal length ≥ 2")
if np.any(np.diff(md) <= 0):
raise ValueError(f"TDR {self.name!r}: MD không tăng nghiêm ngặt")
raise ValueError(f"TDR {self.name!r}: MD is not strictly increasing")
if np.any(np.diff(t) <= 0):
raise ValueError(f"TDR {self.name!r}: TWT không tăng nghiêm ngặt")
raise ValueError(f"TDR {self.name!r}: TWT is not strictly increasing")
object.__setattr__(self, "md", md)
object.__setattr__(self, "twt_ms", t)
@classmethod
def from_pairs(cls, pairs: np.ndarray, name: str = "", drop_flat: bool = False) -> TDR:
"""`drop_flat=True` bỏ các điểm không tăng thời gian so với điểm giữ lại trước đó
(ví dụ F02-1.wlt có hai cặp MD khác nhau cùng TWT 700 và 800 ms)."""
"""`drop_flat=True` drops points whose time does not increase relative to the previously kept point
(e.g. F02-1.wlt contains two pairs with different MD but the same TWT of 700 and 800 ms)."""
pairs = np.asarray(pairs, dtype=float)
pairs = pairs[np.argsort(pairs[:, 0], kind="stable")]
if drop_flat:
@@ -52,14 +53,14 @@ class TDR:
return cls(pairs[:, 0], pairs[:, 1], name)
def time_at(self, md) -> np.ndarray:
"""TWT (ms) tại MD; ngoài phạm vi thì ngoại suy tuyến tính theo khoảng đầu/cuối."""
"""TWT (ms) at MD; outside the range, linearly extrapolated from the first/last interval."""
return _interp_extrap(md, self.md, self.twt_ms)
def depth_at(self, twt_ms) -> np.ndarray:
return _interp_extrap(twt_ms, self.twt_ms, self.md)
def interval_velocity(self) -> np.ndarray:
"""Vận tốc khoảng (m/s) giữa các nút liên tiếp."""
"""Interval velocity (m/s) between consecutive nodes."""
return 2000.0 * np.diff(self.md) / np.diff(self.twt_ms)
@@ -75,26 +76,26 @@ def _interp_extrap(x, xp, fp) -> np.ndarray:
def fill_nan(a: np.ndarray) -> np.ndarray:
"""Nội suy tuyến tính chỗ NaN theo chỉ số, giữ giá trị biên ở hai đầu (như luận văn)."""
"""Linearly interpolate NaNs by index, holding the edge values at both ends (as in the thesis)."""
a = np.asarray(a, dtype=float).copy()
ok = np.isfinite(a)
if not ok.any():
raise ValueError("toàn bộ giá trị là NaN")
raise ValueError("all values are NaN")
a[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), a[ok])
return a
def legacy_sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray) -> TDR:
"""TWT = 2·∫DT dz với t = 0 tại mẫu LAS đầu tiên (prepare_data.py:110)."""
"""TWT = 2·∫DT dz with t = 0 at the first LAS sample (prepare_data.py:110)."""
dt = fill_nan(np.where(np.asarray(dt_us_per_m) < 0, np.nan, dt_us_per_m))
owt_s = integrate.cumulative_trapezoid(dt * US_PER_M_TO_S_PER_M, md, initial=0.0)
return TDR(md, 2000.0 * owt_s, "legacy_sonic")
def sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray, md0: float, t0_ms: float) -> TDR:
"""Tích phân DT đi qua điểm neo (md0, t0_ms). Chỉ dùng mẫu DT hợp lệ, nên khoảng thiếu
được tích phân như DT tuyến tính giữa hai đầu; nếu md0 nằm trên mẫu DT đầu tiên thì
đoạn md0 → mẫu đầu dùng DT của mẫu đầu."""
"""Integrated DT passing through the anchor point (md0, t0_ms). Only valid DT samples are used, so
gaps are integrated as DT varying linearly between their ends; if md0 lies above the first DT
sample, the segment from md0 to the first sample uses the DT of the first sample."""
md = np.asarray(md, dtype=float)
dt = np.asarray(dt_us_per_m, dtype=float)
ok = np.isfinite(dt) & (dt > 0)
@@ -108,19 +109,19 @@ def sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray, md0: float, t0_ms: float)
def calibrate_to_anchors(base: TDR, anchor_md, anchor_twt_ms, name: str = "calibrated") -> TDR:
"""Hiệu chỉnh drift theo khoảng: giữa hai anchor liên tiếp (z_i, t_i), (z_{i+1}, t_{i+1})
"""Interval-wise drift correction: between consecutive anchors (z_i, t_i), (z_{i+1}, t_{i+1})
t(z) = t_i + (t_b(z) − t_b(z_i)) · (t_{i+1} − t_i) / (t_b(z_{i+1}) − t_b(z_i))
với t_b là TDR gốc (sonic). Ngoài phạm vi anchor: dịch đều (bulk) theo anchor gần nhất.
Kết quả đi qua đúng mọi anchor và đơn điệu nếu anchor tăng nghiêm ngặt theo cả z và t.
where t_b is the base (sonic) TDR. Outside the anchor range: bulk shift to the nearest anchor.
The result honours every anchor exactly and is monotonic if the anchors are strictly increasing in both z and t.
"""
za = np.asarray(anchor_md, dtype=float)
ta = np.asarray(anchor_twt_ms, dtype=float)
order = np.argsort(za)
za, ta = za[order], ta[order]
if np.any(np.diff(za) <= 0) or np.any(np.diff(ta) <= 0):
raise ValueError("anchor phải tăng nghiêm ngặt theo MD và TWT")
raise ValueError("anchors must be strictly increasing in MD and TWT")
z = np.union1d(base.md, za)
tb = base.time_at(z)
@@ -138,5 +139,5 @@ def calibrate_to_anchors(base: TDR, anchor_md, anchor_twt_ms, name: str = "calib
def misfit_at_anchors(tdr: TDR, anchor_md, anchor_twt_ms) -> np.ndarray:
"""TWT theo TDR trừ TWT của anchor (ms). Âm nghĩa là TDR sớm hơn anchor."""
"""TDR-predicted TWT minus anchor TWT (ms). Negative means the TDR is earlier than the anchor."""
return tdr.time_at(anchor_md) - np.asarray(anchor_twt_ms, dtype=float)