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:
@@ -1,4 +1,4 @@
|
||||
"""Attribute seismic cho B0b, tính trên trace đầy đủ (cửa sổ mở rộng) rồi mới cắt cửa sổ chính."""
|
||||
"""Seismic attributes for B0b, computed on the full trace (extended window) before cropping to the main window."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -9,17 +9,17 @@ FEATURES = ("amplitude", "envelope", "cos_phase", "sin_phase", "inst_freq", "rel
|
||||
|
||||
|
||||
def trace_attributes(trace: np.ndarray, times_ms: np.ndarray, dt_ms: float = 4.0) -> np.ndarray:
|
||||
"""Ma trận (L, 7) theo thứ tự FEATURES."""
|
||||
"""(L, 7) matrix in the order of FEATURES."""
|
||||
s = np.asarray(trace, dtype=float)
|
||||
a = signal.hilbert(s)
|
||||
env = np.abs(a)
|
||||
ph = np.unwrap(np.angle(a))
|
||||
f_inst = np.gradient(ph) / (2 * np.pi * dt_ms / 1000.0)
|
||||
# tần số tức thời trọng số theo envelope rồi làm trơn 5 mẫu để bớt gai
|
||||
# envelope-weighted instantaneous frequency, smoothed over 5 samples to suppress spikes
|
||||
k = np.ones(5)
|
||||
f_inst = np.convolve(f_inst * env**2, k, "same") / (np.convolve(env**2, k, "same") + 1e-12)
|
||||
f_inst = np.clip(f_inst, 0.0, 500.0 / dt_ms)
|
||||
# relative AI: tích phân trace, bỏ xu hướng < 5 Hz
|
||||
# relative AI: integrated trace with the < 5 Hz trend removed
|
||||
rai = np.cumsum(s)
|
||||
sos = signal.butter(4, 5.0, btype="highpass", fs=1000.0 / dt_ms, output="sos")
|
||||
rai = signal.sosfiltfilt(sos, rai)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""B1: post-stack model-based AI inversion (PyLops) với LFM nội suy theo horizon, rồi φ = a + b·AI."""
|
||||
"""B1: post-stack model-based AI inversion (PyLops) with a horizon-guided interpolated LFM, followed by φ = a + b·AI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,7 +10,7 @@ from ml_porosity.data.wavelet import estimate_wavelet_ls
|
||||
|
||||
|
||||
def fill_edges(x: np.ndarray) -> np.ndarray:
|
||||
"""Thay NaN bằng nội suy tuyến tính, giữ hằng ở hai đầu."""
|
||||
"""Replace NaNs by linear interpolation, holding values constant at both ends."""
|
||||
x = np.asarray(x, dtype=float).copy()
|
||||
ok = np.isfinite(x)
|
||||
x[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), x[ok])
|
||||
@@ -23,8 +23,8 @@ def lowpass(x: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) ->
|
||||
|
||||
|
||||
def strat_map(t: np.ndarray, h_from: np.ndarray, h_to: np.ndarray) -> np.ndarray:
|
||||
"""Ánh xạ thời gian ở giếng đích sang thời gian tương đương địa tầng ở giếng nguồn: nội suy
|
||||
tuyến tính từng đoạn qua các cặp horizon (h_from → h_to), ngoài cùng thì dịch song song."""
|
||||
"""Map times at the target well to stratigraphically equivalent times at the source well: piecewise-linear
|
||||
interpolation through the horizon pairs (h_from → h_to), with a parallel shift beyond the outermost horizons."""
|
||||
ok = np.isfinite(h_from) & np.isfinite(h_to)
|
||||
a, b = h_from[ok], h_to[ok]
|
||||
order = np.argsort(a)
|
||||
@@ -38,7 +38,7 @@ def strat_map(t: np.ndarray, h_from: np.ndarray, h_to: np.ndarray) -> np.ndarray
|
||||
|
||||
|
||||
def build_lfm(t, target_h, target_xy, wells: dict, f_c_hz: float = 6.0, power: float = 2.0) -> np.ndarray:
|
||||
"""wells[name] = {"logai": (L,), "h": (H,), "xy": (2,)} trên cùng trục t. Trả về LFM của log(AI)."""
|
||||
"""wells[name] = {"logai": (L,), "h": (H,), "xy": (2,)} on a common t axis. Returns the LFM of log(AI)."""
|
||||
num = np.zeros_like(t, dtype=float)
|
||||
den = 0.0
|
||||
for w in wells.values():
|
||||
@@ -53,7 +53,7 @@ def build_lfm(t, target_h, target_xy, wells: dict, f_c_hz: float = 6.0, power: f
|
||||
|
||||
|
||||
def operator_reflectivity(logai: np.ndarray, nspike: int = 33) -> np.ndarray:
|
||||
"""Reflectivity theo đúng quy ước của PoststackLinearModelling (wavelet xung đơn vị)."""
|
||||
"""Reflectivity following the exact convention of PoststackLinearModelling (unit-spike wavelet)."""
|
||||
spike = np.zeros(nspike)
|
||||
spike[nspike // 2] = 1.0
|
||||
G0 = PoststackLinearModelling(spike, len(logai), explicit=True).A
|
||||
@@ -67,7 +67,7 @@ def estimate_wavelet(train_logai: list[np.ndarray], train_seis: list[np.ndarray]
|
||||
|
||||
|
||||
def invert(seis: np.ndarray, wav: np.ndarray, lfm: np.ndarray, e: float) -> np.ndarray:
|
||||
"""log(AI) nghịch đảo: Tikhonov về LFM với epsI = e·trace(GᵀG)/n."""
|
||||
"""Inverted log(AI): Tikhonov regularisation towards the LFM with epsI = e·trace(GᵀG)/n."""
|
||||
G = PoststackLinearModelling(wav, len(seis), explicit=True).A
|
||||
eps = e * np.trace(G.T @ G) / len(seis)
|
||||
m, _ = PoststackInversion(seis, wav, m0=lfm, explicit=True, epsI=eps, simultaneous=False)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Biến đổi bin (inline/crossline) ↔ XY theo file `.survey` của OpendTect.
|
||||
"""Bin (inline/crossline) ↔ XY transformation from the OpendTect `.survey` file.
|
||||
|
||||
`.survey` lưu phép biến đổi affine
|
||||
`.survey` stores the affine transformation
|
||||
X = x0 + a_x·IL + b_x·XL
|
||||
Y = y0 + a_y·IL + b_y·XL
|
||||
trong các dòng `Coord-X-BinID: x0`a_x`b_x` và `Coord-Y-BinID: y0`a_y`b_y`.
|
||||
in the lines `Coord-X-BinID: x0`a_x`b_x` and `Coord-Y-BinID: y0`a_y`b_y`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -62,7 +62,7 @@ class SurveyGeometry:
|
||||
|
||||
@classmethod
|
||||
def from_points(cls, il, xl, x, y, z_range=(np.nan, np.nan, np.nan), epsg: int | None = None) -> SurveyGeometry:
|
||||
"""Khớp affine bình phương tối thiểu từ các điểm (IL, XL, X, Y), ví dụ các nút của một horizon."""
|
||||
"""Least-squares affine fit from (IL, XL, X, Y) points, e.g. the nodes of a horizon."""
|
||||
il, xl, x, y = (np.asarray(v, dtype=float).ravel() for v in (il, xl, x, y))
|
||||
A = np.c_[np.ones_like(il), il, xl]
|
||||
cx, *_ = np.linalg.lstsq(A, x, rcond=None)
|
||||
@@ -87,7 +87,7 @@ class SurveyGeometry:
|
||||
return x, y
|
||||
|
||||
def xy_to_bin(self, x, y):
|
||||
"""Bin (thực, chưa làm tròn) tương ứng với XY."""
|
||||
"""Real-valued (unrounded) bin corresponding to XY."""
|
||||
x = np.asarray(x, dtype=float)
|
||||
y = np.asarray(y, dtype=float)
|
||||
rhs = np.stack([x - self.x_coef[0], y - self.y_coef[0]])
|
||||
@@ -99,7 +99,7 @@ class SurveyGeometry:
|
||||
return int(np.rint(il)), int(np.rint(xl))
|
||||
|
||||
def bin_spacing(self) -> tuple[float, float]:
|
||||
"""Khoảng cách (m) giữa hai inline liên tiếp và hai crossline liên tiếp."""
|
||||
"""Spacing (m) between consecutive inlines and between consecutive crosslines."""
|
||||
m = self._matrix()
|
||||
return float(np.hypot(*m[:, 0])), float(np.hypot(*m[:, 1]))
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Horizon F3 dạng ASCII (X, Y, TWT ms) trong Rawdata/Surface_data/."""
|
||||
"""F3 horizons in ASCII format (X, Y, TWT ms) under Rawdata/Surface_data/."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -9,7 +9,7 @@ import numpy as np
|
||||
from ml_porosity.data.geometry import SurveyGeometry
|
||||
from ml_porosity.paths import f3_root
|
||||
|
||||
# Thứ tự từ nông đến sâu tại khu vực giếng.
|
||||
# Ordered from shallow to deep in the well area.
|
||||
F3_HORIZONS = ("Shallow", "FS8", "FS7", "Truncation", "Top-Foresets", "FS6", "MFS4")
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ def horizon_path(name: str) -> Path:
|
||||
|
||||
|
||||
def load_horizon_bins(name: str, geom: SurveyGeometry) -> dict[tuple[int, int], float]:
|
||||
"""Ánh xạ (IL, XL) → TWT (ms). Mỗi dòng XY được gán về bin gần nhất."""
|
||||
"""Map (IL, XL) → TWT (ms). Each XY row is assigned to the nearest bin."""
|
||||
a = np.loadtxt(horizon_path(name))
|
||||
il, xl = geom.xy_to_bin(a[:, 0], a[:, 1])
|
||||
il, xl = np.rint(il).astype(int), np.rint(xl).astype(int)
|
||||
@@ -26,8 +26,8 @@ def load_horizon_bins(name: str, geom: SurveyGeometry) -> dict[tuple[int, int],
|
||||
|
||||
|
||||
def horizon_at(name: str, geom: SurveyGeometry, bins: list[tuple[int, int]], radius: int = 2) -> np.ndarray:
|
||||
"""TWT của horizon tại từng bin; nếu bin không có pick thì lấy trung bình các pick trong
|
||||
ô (2r+1)², NaN nếu ô cũng trống."""
|
||||
"""Horizon TWT at each bin; if a bin has no pick, the mean of the picks within the
|
||||
(2r+1)² window is used, or NaN if the window is also empty."""
|
||||
h = load_horizon_bins(name, geom)
|
||||
out = []
|
||||
for il, xl in bins:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Đọc dữ liệu giếng F3: LAS, marker, checkshot, track và các mô hình TD.
|
||||
"""Readers for F3 well data: LAS, markers, checkshots, tracks and TD models.
|
||||
|
||||
Quy ước độ sâu: MD tính từ KB (m). Bốn giếng F3 đều thẳng đứng nên MD = TVD + 0
|
||||
so với KB; TVDSS = MD − KB.
|
||||
Depth convention: MD is measured from KB (m). All four F3 wells are vertical, so MD = TVD + 0
|
||||
relative to KB; TVDSS = MD − KB.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +17,7 @@ from ml_porosity.paths import f3_root, f3_wells_dir
|
||||
|
||||
F3_WELLS = ("F02-1", "F03-2", "F03-4", "F06-1")
|
||||
|
||||
# Vị trí IL/XL mà luận văn dùng (test 2/prepare_data.py:17–21); chỉ để audit, không dùng.
|
||||
# IL/XL locations used in the thesis (test 2/prepare_data.py:17–21); for auditing only, not used.
|
||||
LEGACY_IL_XL = {"F03-4": (362, 821), "F02-1": (418, 608), "F06-1": (283, 842)}
|
||||
|
||||
|
||||
@@ -27,10 +27,10 @@ class Well:
|
||||
x: float
|
||||
y: float
|
||||
kb: float
|
||||
logs: pd.DataFrame # index = MD (m), cột = mnemonic, NaN thay cho NULL
|
||||
logs: pd.DataFrame # index = MD (m), columns = mnemonics, NaN in place of NULL
|
||||
units: dict[str, str] = field(default_factory=dict)
|
||||
markers: pd.DataFrame | None = None # cột: md, name
|
||||
checkshot: pd.DataFrame | None = None # cột: md, twt_ms (marker TD, xem plan mục 1.2e)
|
||||
markers: pd.DataFrame | None = None # columns: md, name
|
||||
checkshot: pd.DataFrame | None = None # columns: md, twt_ms (marker TD, see plan §1.2e)
|
||||
|
||||
@property
|
||||
def md(self) -> np.ndarray:
|
||||
@@ -50,8 +50,8 @@ def read_las(path: str | Path) -> tuple[pd.DataFrame, dict[str, str], lasio.LASF
|
||||
|
||||
|
||||
def read_two_columns(path: str | Path, skip_header: bool = False) -> np.ndarray:
|
||||
"""Đọc file hai cột số (depth, value). `skip_header=True` cho file OpendTect
|
||||
(.wlt, .csmdl) có phần đầu kết thúc bằng dòng `!` thứ hai."""
|
||||
"""Read a two-column numeric file (depth, value). `skip_header=True` for OpendTect files
|
||||
(.wlt, .csmdl) whose header ends at the second `!` line."""
|
||||
lines = Path(path).read_text(errors="replace").splitlines()
|
||||
if skip_header:
|
||||
bangs = [i for i, s in enumerate(lines) if s.strip() == "!"]
|
||||
@@ -79,7 +79,7 @@ def read_markers(path: str | Path) -> pd.DataFrame:
|
||||
|
||||
|
||||
def read_track(path: str | Path) -> np.ndarray:
|
||||
"""Cột: X, Y, TVDSS (m), MD (m)."""
|
||||
"""Columns: X, Y, TVDSS (m), MD (m)."""
|
||||
return np.loadtxt(path)
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ def load_well(name: str, wells_dir: Path | None = None) -> Well:
|
||||
kb = float(las.well["EKB"].value)
|
||||
|
||||
markers = read_markers(d / "Tops" / f"{name}_markers.txt")
|
||||
# File checkshot có dòng trùng (nhiều marker cùng độ sâu) và không theo thứ tự (F03-2, F03-4).
|
||||
# Checkshot files contain duplicate rows (several markers at the same depth) and are unsorted (F03-2, F03-4).
|
||||
cs = read_two_columns(d / "Checkshot" / f"{name}_TD.txt")
|
||||
checkshot = (
|
||||
pd.DataFrame({"md": cs[:, 0], "twt_ms": cs[:, 1] * 1000.0})
|
||||
@@ -102,12 +102,12 @@ def load_well(name: str, wells_dir: Path | None = None) -> Well:
|
||||
|
||||
|
||||
def load_td_source(name: str, source: str) -> np.ndarray:
|
||||
"""Cặp (MD m, TWT ms) từ một nguồn TD.
|
||||
"""(MD m, TWT ms) pairs from a TD source.
|
||||
|
||||
source:
|
||||
"checkshot" – Checkshot/*_TD.txt (thời gian marker đã tie với horizon, giây)
|
||||
"dt_model" – DT_model/*_TD.txt (ms; nguồn gốc chưa rõ, lệch checkshot, plan mục 1.2c)
|
||||
"wlt" – WellInfo/*.wlt (Depth2Time model của OpendTect, giây)
|
||||
"checkshot" – Checkshot/*_TD.txt (marker times tied to horizons, seconds)
|
||||
"dt_model" – DT_model/*_TD.txt (ms; unknown provenance, offset from checkshot, plan §1.2c)
|
||||
"wlt" – WellInfo/*.wlt (OpendTect Depth2Time model, seconds)
|
||||
"""
|
||||
d = f3_wells_dir()
|
||||
if source == "checkshot":
|
||||
@@ -118,4 +118,4 @@ def load_td_source(name: str, source: str) -> np.ndarray:
|
||||
if source == "wlt":
|
||||
a = read_two_columns(f3_root() / "WellInfo" / f"{name}.wlt", skip_header=True)
|
||||
return np.column_stack([a[:, 0], a[:, 1] * 1000.0])
|
||||
raise ValueError(f"nguồn TD không hợp lệ: {source}")
|
||||
raise ValueError(f"invalid TD source: {source}")
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Chuyển log từ miền độ sâu sang trục thời gian seismic, có lọc chống alias.
|
||||
"""Depth-to-time conversion of logs onto the seismic time axis, with anti-alias filtering.
|
||||
|
||||
Luận văn nội suy điểm log 0.15 m xuống 4 ms (prepare_data.py:203–204), gây alias
|
||||
(plan mục 1.1 #8). Ở đây log được đưa lên lưới thời gian mịn, lọc thông thấp
|
||||
Butterworth pha không (sosfiltfilt) ở `cutoff_frac`·Nyquist của lưới đích, rồi mới lấy mẫu.
|
||||
The thesis point-interpolates 0.15 m log samples directly to 4 ms (prepare_data.py:203–204),
|
||||
which causes aliasing (plan §1.1 #8). Here the log is first mapped onto a fine time grid,
|
||||
low-pass filtered with a zero-phase Butterworth filter (sosfiltfilt) at `cutoff_frac`·Nyquist
|
||||
of the target grid, and only then resampled.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,10 +23,10 @@ def log_to_time(
|
||||
cutoff_frac: float = 0.8,
|
||||
order: int = 6,
|
||||
) -> np.ndarray:
|
||||
"""Giá trị log tại `t_out_ms` (lưới đều). NaN ở nơi log không phủ tới.
|
||||
"""Log values at `t_out_ms` (regular grid). NaN where the log has no coverage.
|
||||
|
||||
Khoảng trống bên trong log được nội suy tuyến tính trước khi lọc rồi đặt lại NaN
|
||||
ở những mẫu đích rơi vào khoảng trống."""
|
||||
Internal gaps in the log are linearly interpolated before filtering, and target
|
||||
samples falling inside a gap are reset to NaN afterwards."""
|
||||
md = np.asarray(md, dtype=float)
|
||||
v = np.asarray(values, dtype=float)
|
||||
ok = np.isfinite(v)
|
||||
@@ -46,7 +47,7 @@ def log_to_time(
|
||||
|
||||
out = np.interp(t_out_ms, t_fine, v_fine, left=np.nan, right=np.nan)
|
||||
|
||||
# Đánh dấu NaN tại mẫu đích nằm trong khoảng trống log dài hơn một mẫu đích.
|
||||
# Set to NaN the target samples lying in log gaps longer than one target sample.
|
||||
gaps = np.flatnonzero(np.diff(t_log) > dt_out)
|
||||
for g in gaps:
|
||||
out[(t_out_ms > t_log[g]) & (t_out_ms < t_log[g + 1])] = np.nan
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""Đọc trace từ SEG-Y post-stack theo (IL, XL) mà không nạp cả cube.
|
||||
"""Read traces from a post-stack SEG-Y by (IL, XL) without loading the whole cube.
|
||||
|
||||
Lưu ý F3_entire.segy: DelayRecordingTime = 4 ms nên mẫu đầu ở 4 ms (segyio đã tính),
|
||||
trong khi `.survey` ghi Z range bắt đầu từ 0.
|
||||
Note on F3_entire.segy: DelayRecordingTime = 4 ms, so the first sample is at 4 ms (handled by segyio),
|
||||
whereas `.survey` gives a Z range starting at 0.
|
||||
|
||||
Lưu ý stack ST10010 của Volve: (1) thiếu 26 trace ở rìa nên segyio không mở được ở chế độ strict, phải tra
|
||||
trace theo header; (2) byte 215 (scalar cho các trường thời gian) = 3, không phải luỹ thừa của 10, nhưng segyio
|
||||
vẫn nhân DelayRecordingTime = 4 với 3, khiến mẫu đầu thành 12 ms thay vì 4 ms như textual header ghi.
|
||||
Note on the Volve ST10010 stack: (1) 26 edge traces are missing, so segyio cannot open it in strict mode and
|
||||
traces must be looked up from the headers; (2) byte 215 (scalar for the time fields) = 3, which is not a power
|
||||
of 10, yet segyio still multiplies DelayRecordingTime = 4 by 3, placing the first sample at 12 ms instead of
|
||||
the 4 ms stated in the textual header.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +18,7 @@ import segyio
|
||||
|
||||
from ml_porosity.paths import f3_segy
|
||||
|
||||
# Giá trị hợp lệ của scalar thời gian (byte 215) theo SEG-Y rev 1; 0 nghĩa là không áp dụng
|
||||
# Valid values of the time scalar (byte 215) per SEG-Y rev 1; 0 means not applied
|
||||
_TIME_SCALARS = {0, 1, -1, 10, -10, 100, -100, 1000, -1000, 10000, -10000}
|
||||
|
||||
|
||||
@@ -28,13 +29,13 @@ class SeismicCube:
|
||||
try:
|
||||
self._f = segyio.open(str(self.path), "r")
|
||||
if self._f.sorting != segyio.TraceSortingFormat.INLINE_SORTING:
|
||||
raise ValueError("chỉ hỗ trợ SEG-Y sắp xếp theo inline")
|
||||
raise ValueError("only inline-sorted SEG-Y is supported")
|
||||
self.ilines = np.asarray(self._f.ilines)
|
||||
self.xlines = np.asarray(self._f.xlines)
|
||||
except ValueError as e:
|
||||
if "sắp xếp" in str(e):
|
||||
if "inline-sorted" in str(e):
|
||||
raise
|
||||
# lưới không đủ trace: tra chỉ số trace theo header IL/XL
|
||||
# incomplete grid: look up trace indices from the IL/XL headers
|
||||
self._f = segyio.open(str(self.path), "r", ignore_geometry=True)
|
||||
il = self._f.attributes(segyio.TraceField.INLINE_3D)[:]
|
||||
xl = self._f.attributes(segyio.TraceField.CROSSLINE_3D)[:]
|
||||
@@ -58,16 +59,16 @@ class SeismicCube:
|
||||
def _index(self, il: int, xl: int) -> int:
|
||||
if self._lut is not None:
|
||||
if (il, xl) not in self._lut:
|
||||
raise KeyError(f"bin ({il}, {xl}) không có trace trong cube")
|
||||
raise KeyError(f"bin ({il}, {xl}) has no trace in the cube")
|
||||
return self._lut[(il, xl)]
|
||||
i = np.searchsorted(self.ilines, il)
|
||||
j = np.searchsorted(self.xlines, xl)
|
||||
if i >= len(self.ilines) or self.ilines[i] != il or j >= len(self.xlines) or self.xlines[j] != xl:
|
||||
raise KeyError(f"bin ({il}, {xl}) nằm ngoài cube")
|
||||
raise KeyError(f"bin ({il}, {xl}) lies outside the cube")
|
||||
return int(i * len(self.xlines) + j)
|
||||
|
||||
def coords(self, il: int, xl: int) -> tuple[float, float]:
|
||||
"""Toạ độ CDP (byte 181/185) của bin, đã áp scalar ở byte 71."""
|
||||
"""CDP coordinates (bytes 181/185) of the bin, with the byte-71 scalar applied."""
|
||||
h = self._f.header[self._index(il, xl)]
|
||||
sc = h[segyio.TraceField.SourceGroupScalar]
|
||||
mul = 1 / abs(sc) if sc < 0 else (sc or 1)
|
||||
@@ -77,8 +78,8 @@ class SeismicCube:
|
||||
return np.asarray(self._f.trace[self._index(il, xl)], dtype=np.float32)
|
||||
|
||||
def patch(self, il: int, xl: int, radius: int) -> np.ndarray:
|
||||
"""Các trace trong ô (2r+1)×(2r+1) quanh (il, xl), thứ tự IL rồi XL: shape (C, nt).
|
||||
Khác luận văn: không kẹp chỉ số ở biên mà báo lỗi nếu ô vượt ra ngoài cube."""
|
||||
"""Traces in the (2r+1)×(2r+1) window around (il, xl), ordered by IL then XL: shape (C, nt).
|
||||
Unlike the thesis, indices are not clamped at the edges; an error is raised if the window extends outside the cube."""
|
||||
return np.stack(
|
||||
[
|
||||
self.trace(il + di, xl + dx)
|
||||
@@ -88,5 +89,5 @@ class SeismicCube:
|
||||
)
|
||||
|
||||
def window(self, t0_ms: float, t1_ms: float) -> np.ndarray:
|
||||
"""Mặt nạ boolean cho các mẫu trong [t0, t1]."""
|
||||
"""Boolean mask of the samples within [t0, t1]."""
|
||||
return (self.times_ms >= t0_ms) & (self.times_ms <= t1_ms)
|
||||
|
||||
267
ml_porosity/data/synth_d2.py
Normal file
267
ml_porosity/data/synth_d2.py
Normal file
@@ -0,0 +1,267 @@
|
||||
"""D2: F3-calibrated synthetic dataset with known ground-truth registration (plan §5.1, §5.5).
|
||||
|
||||
Earth model in true time t: a stratigraphic framework from 5 laterally extensive F3 horizons (Shallow, FS8,
|
||||
FS7, Truncation, MFS4), subdivided into sub-units of thickness ≈ `sub_unit_ms` (proportional sub-surfaces
|
||||
between horizons, parallel above Shallow and below MFS4). Porosity
|
||||
|
||||
φ(t) = φ0 + slope·(t − 850) + o_u(x, y) + GRF(s(t)),
|
||||
|
||||
where s is the stratigraphic coordinate (strat_map onto the median horizon times), o_u is a per-unit offset
|
||||
(with a linear lateral gradient), and GRF is a sum of OU processes in s, independent across pseudo-wells
|
||||
(spaced ≥ 500 m apart). Exact F3 rock physics: DT = (φ + 0.2018)/0.0011, RHOB = 2650 − 1600φ,
|
||||
AI = RHOB·10⁶/DT. Seismic: 3×3 patch (using the horizons of neighbouring bins), forward model
|
||||
tie_likelihood.forward_fine with the F3 wavelet, and band-limited noise scaled to the target SNR.
|
||||
|
||||
Registration: logs lie on the τ axis (sonic time). True warp t(τ) = τ + b + ∫(e^g − 1) with
|
||||
g = c·(m_g + L z), b = c·σ_b·z_b, where (m_g, σ_g, ℓ, σ_b) come from the GP fit to the F3 anchors (scripts/09);
|
||||
z is shared across all drift factors c. Anchors: unit boundaries within the extended window, τ_k = t⁻¹(t_b),
|
||||
t_k = t_b + ε_k, with ε_k ~ N(0, σ_a²) shared across all c.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.baselines.inversion import strat_map
|
||||
from ml_porosity.registration.labels import antialias, invert_warps
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine
|
||||
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, kernel_matrix
|
||||
|
||||
PHI_DT_A, PHI_DT_B = -0.2018, 0.0011
|
||||
|
||||
|
||||
def phi_to_ai(phi: np.ndarray) -> np.ndarray:
|
||||
dt = (phi - PHI_DT_A) / PHI_DT_B # µs/m
|
||||
return (2650.0 - 1600.0 * phi) * 1e6 / dt
|
||||
|
||||
|
||||
def ou_process(n: int, d: float, sd: float, ell: float, rng) -> np.ndarray:
|
||||
rho = np.exp(-d / ell)
|
||||
e = rng.standard_normal(n) * sd * np.sqrt(1 - rho**2)
|
||||
x = np.empty(n)
|
||||
x[0] = sd * rng.standard_normal()
|
||||
for i in range(1, n):
|
||||
x[i] = rho * x[i - 1] + e[i]
|
||||
return x
|
||||
|
||||
|
||||
@dataclass
|
||||
class HorizonGrid:
|
||||
h: np.ndarray # (H, nIL, nXL) TWT ms, NaN if missing
|
||||
il0: int
|
||||
xl0: int
|
||||
geom: object
|
||||
|
||||
def at(self, il: int, xl: int) -> np.ndarray:
|
||||
return self.h[:, il - self.il0, xl - self.xl0]
|
||||
|
||||
def valid_mask(self, min_gap_ms: float = 8.0, radius: int = 1) -> np.ndarray:
|
||||
ok = np.all(np.isfinite(self.h), 0)
|
||||
ok[ok] &= np.all(np.diff(self.h[:, ok], axis=0) >= min_gap_ms, 0)
|
||||
out = ok.copy()
|
||||
for di in range(-radius, radius + 1):
|
||||
for dj in range(-radius, radius + 1):
|
||||
out &= np.roll(np.roll(ok, di, 0), dj, 1)
|
||||
out[:radius], out[-radius:], out[:, :radius], out[:, -radius:] = False, False, False, False
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class D2Well:
|
||||
name: str
|
||||
il: int
|
||||
xl: int
|
||||
x: float
|
||||
y: float
|
||||
seis_clean: np.ndarray # (9, L_ext) noise-free
|
||||
noise_unit: np.ndarray # (9, L_ext) band-limited noise, unit variance on the centre trace
|
||||
phi_t: np.ndarray # φ of the centre trace on t_fine
|
||||
z_g: np.ndarray # (n_grid,) standard normal draws for g
|
||||
z_b: float
|
||||
boundaries_t: np.ndarray # unit boundaries (true time) within the extended window
|
||||
eps_a: np.ndarray # standard normal pick noise, same length as boundaries_t
|
||||
extra: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
class D2Realization:
|
||||
"""A single realization: earth model, pseudo-well locations, noise, and standard normal draws for drift/picks."""
|
||||
|
||||
def __init__(self, cfg: dict, rid: int, hg: HorizonGrid, drift: WarpHyper, wavelet: np.ndarray):
|
||||
self.cfg, self.rid, self.drift = cfg, rid, drift
|
||||
rng = np.random.default_rng([int(rid), 20261026])
|
||||
f = cfg["fine_dt_ms"]
|
||||
self.dt = cfg["dt_ms"]
|
||||
self.t_fine = np.arange(cfg["model_t_ms"][0], cfg["model_t_ms"][1] + f / 2, f)
|
||||
self.tau_fine = np.arange(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1] + f / 2, f)
|
||||
self.grid = WarpGrid(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1], cfg["warp_dtau_ms"])
|
||||
e0, e1 = cfg["ext_window_ms"]
|
||||
m0, m1 = cfg["main_window_ms"]
|
||||
self.t_ext = np.arange(e0, e1 + self.dt / 2, self.dt)
|
||||
self.main = (self.t_ext >= m0) & (self.t_ext <= m1)
|
||||
self.t_main = self.t_ext[self.main]
|
||||
self.wavelet = wavelet
|
||||
self.w_fine = fine_wavelet(wavelet, int(round(self.dt / f)))
|
||||
|
||||
# Stratigraphic framework
|
||||
valid = hg.valid_mask(cfg["min_gap_ms"], cfg["patch_radius"])
|
||||
H = hg.h[:, valid]
|
||||
self.h_ref = np.median(H, axis=1)
|
||||
self.S_ref = self._unit_surfaces(self.h_ref, cfg["sub_unit_ms"], *cfg["model_t_ms"])
|
||||
self.hg = hg
|
||||
|
||||
# Well locations: test wells first, then the training pool (nested by order)
|
||||
ii, jj = np.nonzero(valid)
|
||||
il_all, xl_all = ii + hg.il0, jj + hg.xl0
|
||||
xy = np.column_stack(hg.geom.bin_to_xy(il_all, xl_all))
|
||||
order = rng.permutation(len(il_all))
|
||||
W = cfg["wells"]
|
||||
test, train = [], []
|
||||
for k in order:
|
||||
p = xy[k]
|
||||
if len(test) < W["n_test"]:
|
||||
if all(np.hypot(*(p - xy[q])) >= W["min_dist_test_m"] for q in test):
|
||||
test.append(k)
|
||||
elif len(train) < W["n_train_pool"]:
|
||||
if all(np.hypot(*(p - xy[q])) >= W["min_dist_test_m"] for q in test) and \
|
||||
all(np.hypot(*(p - xy[q])) >= W["min_dist_train_m"] for q in train):
|
||||
train.append(k)
|
||||
else:
|
||||
break
|
||||
if len(train) < W["n_train_pool"]:
|
||||
raise RuntimeError("not enough pseudo-well locations satisfying the spacing constraints")
|
||||
|
||||
# Realization-level properties
|
||||
P = cfg["property"]
|
||||
self.phi0 = P["phi0"] + P["phi0_sd"] * rng.standard_normal()
|
||||
nu = len(self.S_ref) + 1
|
||||
self.unit_off = P["unit_offset_sd"] * rng.standard_normal(nu)
|
||||
self.unit_grad = P["unit_lateral_sd"] * rng.standard_normal((nu, 2))
|
||||
xy_all = xy
|
||||
self.xy_c, self.xy_s = xy_all.mean(0), np.ptp(xy_all, 0) / 2
|
||||
Kg = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, drift.ell_ms, drift.kernel)
|
||||
self.Lg = np.linalg.cholesky(Kg + 1e-8 * np.eye(self.grid.n))
|
||||
|
||||
self.wells: list[D2Well] = []
|
||||
for tag, idx in [("T", test), ("P", train)]:
|
||||
for n, k in enumerate(idx):
|
||||
self.wells.append(self._make_well(f"{tag}{n:02d}", int(il_all[k]), int(xl_all[k]), rng))
|
||||
self.test = self.wells[: W["n_test"]]
|
||||
self.pool = self.wells[W["n_test"]:]
|
||||
|
||||
# ------------------------------------------------------------ earth model
|
||||
|
||||
@staticmethod
|
||||
def _unit_surfaces(h_ref, sub_ms, t0, t1) -> np.ndarray:
|
||||
s = [h_ref[0] - k * sub_ms for k in range(int((h_ref[0] - t0) // sub_ms), 0, -1)]
|
||||
for a, b in zip(h_ref[:-1], h_ref[1:]):
|
||||
n = max(1, int(round((b - a) / sub_ms)))
|
||||
s += list(a + (b - a) * np.arange(n) / n)
|
||||
s += [h_ref[-1] + k * sub_ms for k in range(0, int((t1 - h_ref[-1]) // sub_ms) + 1)]
|
||||
return np.array(s)
|
||||
|
||||
def _phi_trace(self, h_bin, xy, grf_s, s_axis):
|
||||
s = strat_map(self.t_fine, h_bin, self.h_ref)
|
||||
unit = np.searchsorted(self.S_ref, s)
|
||||
u = (np.asarray(xy) - self.xy_c) / self.xy_s
|
||||
off = self.unit_off[unit] + self.unit_grad[unit] @ u
|
||||
phi = self.phi0 + self.cfg["property"]["slope_per_100ms"] * (self.t_fine - 850.0) / 100.0 + off
|
||||
phi = phi + np.interp(s, s_axis, grf_s)
|
||||
return np.clip(phi, *self.cfg["property"]["clip"])
|
||||
|
||||
def _make_well(self, name, il, xl, rng) -> D2Well:
|
||||
P, r = self.cfg["property"], self.cfg["patch_radius"]
|
||||
f = self.cfg["fine_dt_ms"]
|
||||
s_axis = np.arange(self.t_fine[0] - 200, self.t_fine[-1] + 200 + f / 2, f)
|
||||
grf = sum(ou_process(len(s_axis), f, c["sd"], c["ell_ms"], rng) for c in P["grf"])
|
||||
traces, phi_c = [], None
|
||||
for di in range(-r, r + 1):
|
||||
for dj in range(-r, r + 1):
|
||||
h = self.hg.at(il + di, xl + dj)
|
||||
xy = np.array(self.hg.geom.bin_to_xy(il + di, xl + dj), dtype=float).ravel()
|
||||
phi = self._phi_trace(h, xy, grf, s_axis)
|
||||
if di == 0 and dj == 0:
|
||||
phi_c = phi
|
||||
traces.append(phi_to_ai(phi))
|
||||
seis = forward_fine(np.stack(traces), self.t_fine, self.t_ext, self.w_fine)
|
||||
white = rng.standard_normal((len(traces), len(self.t_ext) + len(self.wavelet)))
|
||||
noise = np.stack([np.convolve(wn, self.wavelet, "same")[len(self.wavelet) // 2: len(self.wavelet) // 2 + len(self.t_ext)]
|
||||
for wn in white])
|
||||
noise /= noise[len(traces) // 2].std()
|
||||
h0 = self.hg.at(il, xl)
|
||||
bt = strat_map(self.S_ref, self.h_ref, h0)
|
||||
bt = bt[(bt >= self.t_ext[0]) & (bt <= self.t_ext[-1])]
|
||||
x, y = (float(v) for v in np.ravel(self.hg.geom.bin_to_xy(il, xl)))
|
||||
return D2Well(name, il, xl, x, y, seis, noise, phi_c, rng.standard_normal(self.grid.n),
|
||||
float(rng.standard_normal()), bt, rng.standard_normal(len(bt)))
|
||||
|
||||
# ------------------------------------------------------------ observations per cell configuration
|
||||
|
||||
def true_warp(self, w: D2Well, c: float) -> tuple[float, np.ndarray]:
|
||||
d = self.drift
|
||||
g = c * (d.m_g + d.sigma_g * (self.Lg @ w.z_g))
|
||||
return c * d.sigma_b_ms * w.z_b, g
|
||||
|
||||
def observe(self, w: D2Well, c: float, snr_db: float | None, sigma_a_ms: float,
|
||||
anchor_density: str = "full") -> dict:
|
||||
"""Data for one well at drift factor c: noisy seismic, logs on τ, anchors and the true warp."""
|
||||
b, g = self.true_warp(w, c)
|
||||
t_tau_grid = self.grid.t_of_tau(b, g)[0]
|
||||
t_tau = np.interp(self.tau_fine, self.grid.tau, t_tau_grid)
|
||||
if t_tau[0] < self.t_fine[0] or t_tau[-1] > self.t_fine[-1]:
|
||||
raise ValueError(f"{w.name}: warp extends outside the earth-model domain (c = {c})")
|
||||
phi_log = np.interp(t_tau, self.t_fine, w.phi_t)
|
||||
seis = w.seis_clean.copy()
|
||||
if snr_db is not None and np.isfinite(snr_db):
|
||||
ps = np.mean(w.seis_clean[len(seis) // 2] ** 2)
|
||||
seis = seis + np.sqrt(ps / 10 ** (snr_db / 10)) * w.noise_unit
|
||||
tau_k = np.interp(w.boundaries_t, t_tau, self.tau_fine)
|
||||
t_k = w.boundaries_t + sigma_a_ms * w.eps_a
|
||||
keep = self._anchor_subset(len(tau_k), anchor_density)
|
||||
f = self.cfg["fine_dt_ms"]
|
||||
y_true = np.interp(self.t_main, self.t_fine, antialias(w.phi_t, f, self.dt))
|
||||
return {"name": w.name, "seis": seis.astype(np.float32), "tau_fine": self.tau_fine, "phi_log": phi_log,
|
||||
"ai_log": phi_to_ai(phi_log), "tau_k": tau_k[keep], "t_k": t_k[keep], "b": b, "g": g,
|
||||
"t_of_tau_true": t_tau, "y_true": y_true, "xy": (w.x, w.y)}
|
||||
|
||||
@staticmethod
|
||||
def _anchor_subset(n: int, density: str) -> np.ndarray:
|
||||
if density == "full":
|
||||
return np.arange(n)
|
||||
if density == "half":
|
||||
return np.arange(0, n, 2)
|
||||
if density == "topbottom":
|
||||
return np.array([0, n - 1]) if n > 1 else np.arange(n)
|
||||
if density == "none":
|
||||
return np.arange(0)
|
||||
raise ValueError(density)
|
||||
|
||||
def true_tau_at(self, obs: dict, t: np.ndarray) -> np.ndarray:
|
||||
return invert_warps(obs["t_of_tau_true"], self.tau_fine, t)[0]
|
||||
|
||||
|
||||
def load_horizon_grid(names, cache) -> HorizonGrid:
|
||||
"""IL×XL grid of the F3 horizons (cached as npz because the ASCII files are large)."""
|
||||
from ml_porosity.data.geometry import SurveyGeometry
|
||||
from ml_porosity.data.horizons import horizon_path
|
||||
from ml_porosity.paths import f3_root
|
||||
|
||||
geom = SurveyGeometry.from_survey(f3_root())
|
||||
il0, il1, _ = geom.il_range
|
||||
xl0, xl1, _ = geom.xl_range
|
||||
if cache is not None and cache.exists():
|
||||
z = np.load(cache)
|
||||
if list(z["names"]) == list(names):
|
||||
return HorizonGrid(z["h"], il0, xl0, geom)
|
||||
h = np.full((len(names), il1 - il0 + 1, xl1 - xl0 + 1), np.nan)
|
||||
for k, nm in enumerate(names):
|
||||
a = np.loadtxt(horizon_path(nm))
|
||||
il, xl = geom.xy_to_bin(a[:, 0], a[:, 1])
|
||||
il, xl = np.rint(il).astype(int), np.rint(xl).astype(int)
|
||||
ok = (il >= il0) & (il <= il1) & (xl >= xl0) & (xl <= xl1)
|
||||
h[k, il[ok] - il0, xl[ok] - xl0] = a[ok, 2]
|
||||
if cache is not None:
|
||||
cache.parent.mkdir(parents=True, exist_ok=True)
|
||||
np.savez_compressed(cache, h=h, names=np.array(names))
|
||||
return HorizonGrid(h, il0, xl0, geom)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Synthetic seismogram và đo lệch thời gian giữa synthetic và seismic."""
|
||||
"""Synthetic seismograms and time-shift measurement between synthetic and seismic."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -6,7 +6,7 @@ import numpy as np
|
||||
|
||||
|
||||
def reflectivity_from_ai(ai: np.ndarray) -> np.ndarray:
|
||||
"""r[i] = (AI[i+1] − AI[i]) / (AI[i+1] + AI[i]), đặt tại mẫu i; mẫu cuối = 0."""
|
||||
"""r[i] = (AI[i+1] − AI[i]) / (AI[i+1] + AI[i]), placed at sample i; the last sample is 0."""
|
||||
ai = np.asarray(ai, dtype=float)
|
||||
r = np.zeros_like(ai)
|
||||
r[:-1] = (ai[1:] - ai[:-1]) / (ai[1:] + ai[:-1])
|
||||
@@ -14,7 +14,7 @@ def reflectivity_from_ai(ai: np.ndarray) -> np.ndarray:
|
||||
|
||||
|
||||
def shift_signal(x: np.ndarray, shift_ms: float, dt_ms: float) -> np.ndarray:
|
||||
"""Dịch chuỗi theo thời gian (dương = muộn hơn) bằng nội suy tuyến tính; ngoài biên = 0."""
|
||||
"""Time-shift a series (positive = later) by linear interpolation; zero outside the support."""
|
||||
t = np.arange(len(x)) * dt_ms
|
||||
return np.interp(t - shift_ms, t, x, left=0.0, right=0.0)
|
||||
|
||||
@@ -27,7 +27,7 @@ def ncc(a: np.ndarray, b: np.ndarray) -> float:
|
||||
|
||||
|
||||
def best_shift(syn: np.ndarray, seis: np.ndarray, dt_ms: float, max_ms: float, step_ms: float = 0.5):
|
||||
"""Dịch synthetic trong ±max_ms để cực đại tương quan với seismic. Trả về (shift_ms, r)."""
|
||||
"""Shift the synthetic within ±max_ms to maximise its correlation with the seismic. Returns (shift_ms, r)."""
|
||||
shifts = np.arange(-max_ms, max_ms + step_ms / 2, step_ms)
|
||||
rs = np.array([ncc(shift_signal(syn, s, dt_ms), seis) for s in shifts])
|
||||
k = int(np.nanargmax(rs))
|
||||
@@ -42,8 +42,8 @@ def local_shifts(
|
||||
hop_ms: float = 20.0,
|
||||
max_ms: float = 16.0,
|
||||
):
|
||||
"""Lệch thời gian cục bộ trong cửa sổ trượt (taper Hann). Trả về (tâm cửa sổ theo chỉ số
|
||||
mẫu, shift_ms, r). Dương nghĩa là synthetic cần dịch muộn hơn để khớp seismic."""
|
||||
"""Local time shifts in a sliding window (Hann taper). Returns (window centres as sample
|
||||
indices, shift_ms, r). Positive means the synthetic must be shifted later to match the seismic."""
|
||||
n = int(round(win_ms / dt_ms))
|
||||
hop = max(1, int(round(hop_ms / dt_ms)))
|
||||
taper = np.hanning(n)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Đọc dữ liệu Volve: horizon xuất từ OpenWorks, well picks (cột cố định) và checkshot VSP.
|
||||
"""Readers for Volve data: horizons exported from OpenWorks, well picks (fixed-width columns) and VSP checkshots.
|
||||
|
||||
Quy ước: MD tính từ RKB (54.9 m trên MSL), TVDSS và TWT tính từ MSL, toạ độ ED50 / UTM 31N.
|
||||
Lưới horizon là lưới ST10010 (12.5 × 12.5 m). Các file ghi ST0202 cũng đánh số IL/XL theo lưới này
|
||||
(affine lệch < 0.11 m trong ROI giếng).
|
||||
Conventions: MD is measured from RKB (54.9 m above MSL), TVDSS and TWT from MSL; coordinates are ED50 / UTM 31N.
|
||||
The horizon grid is the ST10010 grid (12.5 × 12.5 m). Files labelled ST0202 also number IL/XL on this grid
|
||||
(affine discrepancy < 0.11 m within the well ROI).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +19,7 @@ from ml_porosity.data.geometry import SurveyGeometry
|
||||
VOLVE_RKB_M = 54.9
|
||||
VOLVE_EPSG = 23031
|
||||
|
||||
# 9 giếng có PHIF (D3) và F-15 A (không có PHIF nhưng có VSP checkshot), như ROI ở docs/research/volve-inventory.md
|
||||
# The 9 wells with PHIF (D3) plus F-15 A (no PHIF but a VSP checkshot), matching the ROI in docs/research/volve-inventory.md
|
||||
VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1 C", "NO 15/9-F-11 A",
|
||||
"NO 15/9-F-11 B", "NO 15/9-F-11 T2", "NO 15/9-F-12", "NO 15/9-F-15 A", "NO 15/9-F-15 D")
|
||||
|
||||
@@ -28,7 +28,7 @@ VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1
|
||||
class Horizon:
|
||||
survey: str
|
||||
name: str
|
||||
domain: str # "TIME" (TWT ms) hoặc "DEPTH" (m)
|
||||
domain: str # "TIME" (TWT ms) or "DEPTH" (m)
|
||||
il: np.ndarray
|
||||
xl: np.ndarray
|
||||
x: np.ndarray
|
||||
@@ -43,7 +43,7 @@ class Horizon:
|
||||
return {(int(i), int(j)): float(v) for i, j, v in zip(self.il, self.xl, self.z)}
|
||||
|
||||
def at(self, il: float, xl: float, radius: int = 1) -> float:
|
||||
"""Trung vị z của các nút trong cửa sổ (2·radius+1)² quanh bin gần nhất; NaN nếu không có nút."""
|
||||
"""Median z of the nodes within the (2·radius+1)² window around the nearest bin; NaN if there are no nodes."""
|
||||
i0, j0 = int(np.rint(il)), int(np.rint(xl))
|
||||
vals = [self.lut[k] for di in range(-radius, radius + 1) for dj in range(-radius, radius + 1)
|
||||
if (k := (i0 + di, j0 + dj)) in self.lut]
|
||||
@@ -51,8 +51,8 @@ class Horizon:
|
||||
|
||||
|
||||
def read_horizon(path: str | Path) -> Horizon:
|
||||
"""File `*.dat` dạng: các dòng chú thích `#`, 4 dòng metadata (survey, tên, người minh giải, miền),
|
||||
sau đó mỗi dòng `IL,XL,X,Y,Z`. Một số file để trống dòng survey (chỉ có `=`)."""
|
||||
"""`*.dat` file layout: `#` comment lines, 4 metadata lines (survey, name, interpreter, domain),
|
||||
followed by one `IL,XL,X,Y,Z` row per line. Some files leave the survey line empty (only `=`)."""
|
||||
meta, rows = [], []
|
||||
with open(path, errors="replace") as fh:
|
||||
for line in fh:
|
||||
@@ -78,7 +78,7 @@ PICK_COLUMNS = {"Well name": "well", "Surface name": "surface", "Obs#": "obs", "
|
||||
|
||||
|
||||
def read_well_picks(path: str | Path) -> pd.DataFrame:
|
||||
"""`Well_picks_Volve_v1.dat`: mỗi giếng có một dòng tiêu đề và một dòng gạch `---` xác định độ rộng cột.
|
||||
"""`Well_picks_Volve_v1.dat`: each well has a header line and a `---` dash line that defines the column widths.
|
||||
Qlf: ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached."""
|
||||
lines = Path(path).read_text(errors="replace").splitlines()
|
||||
spans, rows = None, []
|
||||
@@ -105,8 +105,8 @@ def read_well_picks(path: str | Path) -> pd.DataFrame:
|
||||
|
||||
|
||||
def read_checkshot(path: str | Path) -> pd.DataFrame:
|
||||
"""`TZV_TIME_CHECKSHOT_*.ASC` (3 cột MD, TVD-MSL, TWT ms). F-11 T2 ghi MD từ RKB, F-15 A ghi MD từ MSL
|
||||
(`MDMSL`), nên MD được quy về RKB. Trả về cột md (RKB), tvdss (dương xuống) và twt_ms."""
|
||||
"""`TZV_TIME_CHECKSHOT_*.ASC` (3 columns: MD, TVD-MSL, TWT ms). F-11 T2 records MD from RKB and F-15 A
|
||||
from MSL (`MDMSL`), so MD is referred to RKB. Returns columns md (RKB), tvdss (positive down) and twt_ms."""
|
||||
text = Path(path).read_text(errors="replace")
|
||||
rows = []
|
||||
for ln in text.splitlines():
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Wavelet: Ricker, wavelet thống kê pha không, xoay pha hằng và ước lượng từ giếng.
|
||||
"""Wavelets: Ricker, zero-phase statistical wavelet, constant phase rotation, and well-based estimation.
|
||||
|
||||
Mọi wavelet có số mẫu lẻ, tâm ở giữa, bước `dt_ms`.
|
||||
All wavelets have an odd number of samples, are centred, and are sampled at `dt_ms`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,15 +18,15 @@ def ricker(f_peak_hz: float, dt_ms: float = 4.0, length_ms: float = 128.0) -> np
|
||||
|
||||
|
||||
def rotate_phase(w: np.ndarray, phase_deg: float) -> np.ndarray:
|
||||
"""Xoay pha hằng: w·cos φ − H[w]·sin φ (H: biến đổi Hilbert)."""
|
||||
"""Constant phase rotation: w·cos φ − H[w]·sin φ (H: Hilbert transform)."""
|
||||
h = np.imag(signal.hilbert(w))
|
||||
p = np.deg2rad(phase_deg)
|
||||
return w * np.cos(p) - h * np.sin(p)
|
||||
|
||||
|
||||
def statistical_wavelet(traces: np.ndarray, dt_ms: float = 4.0, length_ms: float = 128.0) -> np.ndarray:
|
||||
"""Wavelet pha không có phổ biên độ bằng trung bình phổ của các trace (taper Hann),
|
||||
chuẩn hoá đỉnh = 1."""
|
||||
"""Zero-phase wavelet whose amplitude spectrum equals the mean spectrum of the traces
|
||||
(Hann taper), normalised to unit peak."""
|
||||
traces = np.atleast_2d(traces)
|
||||
nt = traces.shape[1]
|
||||
nfft = int(2 ** np.ceil(np.log2(4 * nt)))
|
||||
@@ -45,10 +45,10 @@ def estimate_wavelet_ls(
|
||||
length_ms: float = 128.0,
|
||||
damping: float = 0.05,
|
||||
) -> np.ndarray:
|
||||
"""Wavelet (biên độ theo đơn vị seismic) cực tiểu Σ‖s − w∗r‖² + ε‖w‖² trên nhiều giếng.
|
||||
"""Wavelet (amplitude in seismic units) minimising Σ‖s − w∗r‖² + ε‖w‖² over multiple wells.
|
||||
|
||||
Hệ chuẩn tắc dạng Toeplitz từ tự tương quan của r và tương quan chéo r–s; ε tính tương đối
|
||||
theo đường chéo. Chuỗi phải hữu hạn và cùng độ dài theo từng cặp."""
|
||||
Toeplitz normal equations built from the autocorrelation of r and the r–s cross-correlation;
|
||||
ε is relative to the diagonal. Series must be finite and pairwise of equal length."""
|
||||
n = int(round(length_ms / dt_ms)) // 2
|
||||
m = 2 * n + 1
|
||||
R = np.zeros(m)
|
||||
|
||||
35
ml_porosity/eval/figstyle.py
Normal file
35
ml_porosity/eval/figstyle.py
Normal file
@@ -0,0 +1,35 @@
|
||||
"""Matplotlib style for the P2 figures: reference palette of the dataviz skill (light mode), checked with validate_palette.
|
||||
|
||||
- Categorical (≤ 3 groups per figure): blue, orange, aqua — passes all-pairs (CVD ΔE ≥ 9.2); aqua is < 3:1, so always labelled directly.
|
||||
- Ordinal (drift factor c): a single blue hue, light → dark.
|
||||
- Diverging (M2/competitor ratio around 1): blue ↔ red, with a neutral grey midpoint.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import matplotlib as mpl
|
||||
from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
|
||||
|
||||
SURFACE, INK, INK2, MUTED, GRID, AXIS = "#fcfcfb", "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"
|
||||
BLUE, ORANGE, AQUA = "#2a78d6", "#eb6834", "#1baf7a"
|
||||
ORDINAL_BLUE = ["#86b6ef", "#2a78d6", "#104281"]
|
||||
GOOD, CRITICAL = "#0ca30c", "#d03b3b"
|
||||
DIVERGING = LinearSegmentedColormap.from_list(
|
||||
"blue_gray_red", ["#104281", "#2a78d6", "#86b6ef", "#f0efec", "#ec8a89", "#d23f3e", "#8f2626"])
|
||||
|
||||
|
||||
def diverging_norm(vmin: float, vcenter: float, vmax: float) -> TwoSlopeNorm:
|
||||
return TwoSlopeNorm(vcenter, vmin, vmax)
|
||||
|
||||
|
||||
def apply() -> None:
|
||||
mpl.rcParams.update({
|
||||
"figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
|
||||
"axes.edgecolor": AXIS, "axes.labelcolor": INK2, "axes.titlecolor": INK, "text.color": INK,
|
||||
"axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.6, "axes.axisbelow": True,
|
||||
"axes.spines.top": False, "axes.spines.right": False,
|
||||
"xtick.color": AXIS, "ytick.color": AXIS, "xtick.labelcolor": INK2, "ytick.labelcolor": INK2,
|
||||
"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "regular", "axes.titlelocation": "left",
|
||||
"lines.linewidth": 1.5, "lines.markersize": 5, "legend.frameon": False, "legend.fontsize": 8,
|
||||
"axes.prop_cycle": mpl.cycler(color=[BLUE, ORANGE, AQUA]),
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Metric điểm cơ bản; bỏ qua mẫu NaN ở cả hai phía."""
|
||||
"""Basic pointwise metrics; samples that are NaN on either side are ignored."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -27,7 +27,7 @@ def point_metrics(y_true, y_pred) -> dict[str, float]:
|
||||
|
||||
|
||||
def split_bands(y: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Tách chuỗi thành băng thấp (< f_c, Butterworth pha không) và phần còn lại (băng seismic)."""
|
||||
"""Split a series into a low band (< f_c, zero-phase Butterworth) and the remainder (seismic band)."""
|
||||
from scipy import signal
|
||||
|
||||
y = np.asarray(y, dtype=float)
|
||||
@@ -46,7 +46,7 @@ def band_metrics(y_true, y_pred, f_c_hz: float = 6.0, dt_ms: float = 4.0) -> dic
|
||||
|
||||
|
||||
def gaussian_metrics(y_true, mu, sigma) -> dict[str, float]:
|
||||
"""NLL, CRPS (dạng đóng của Gaussian) và coverage của khoảng trung tâm."""
|
||||
"""NLL, CRPS (Gaussian closed form) and coverage of central intervals."""
|
||||
from scipy import stats
|
||||
|
||||
y, mu, s = (np.asarray(a, dtype=float) for a in (y_true, mu, sigma))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Các loss của luận văn (`test 2/train_open_patch_v2.py`), chuyển nguyên trạng để dựng baseline B0.
|
||||
"""Losses from the thesis (`test 2/train_open_patch_v2.py`), ported verbatim to build baseline B0.
|
||||
|
||||
Lưu ý (plan mục 1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L nên chỉ có 5 ràng buộc độc lập.
|
||||
Note (plan §1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L, so there are only 5 independent constraints.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,7 +37,7 @@ def var_match_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
|
||||
def crosscorr_loss(pred: torch.Tensor, target: torch.Tensor, max_shift: int = 8) -> torch.Tensor:
|
||||
"""MSE nhỏ nhất trên dải shift [-max_shift, max_shift]."""
|
||||
"""Minimum MSE over the shift range [-max_shift, max_shift]."""
|
||||
x = pred.squeeze(1); y = target.squeeze(1)
|
||||
L = x.shape[1]
|
||||
losses = []
|
||||
|
||||
87
ml_porosity/losses/rml.py
Normal file
87
ml_porosity/losses/rml.py
Normal file
@@ -0,0 +1,87 @@
|
||||
"""Sub-window losses on the "label bank" (plan §4.4–4.5).
|
||||
|
||||
Each training well w has S candidate labels Y_w (S, L) and log-weights log π_w (S). For each sub-window j:
|
||||
|
||||
ℓ_wjs = Σ_{i ∈ j} log N(y_ws,i; μ_i, σ_i²)
|
||||
RML: −(1/(λ n_j)) · log Σ_s π_ws exp(λ ℓ_wjs)
|
||||
hard-min: −(1/n_j) · max_s ℓ_wjs (λ → ∞, uniform π; B4a)
|
||||
|
||||
S = 1 gives the mean Gaussian NLL (B3, point tie). A bank of ±K-sample shifts of a single label with
|
||||
uniform π gives soft-min/hard-min over bulk shifts (B4b/B4a). The same windowing mechanism is used for all methods.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
LOG_2PI = math.log(2 * math.pi)
|
||||
|
||||
|
||||
def window_starts(n_wells: int, L: int, win: int, J: int, margin: int, gen: torch.Generator, device) -> torch.Tensor:
|
||||
hi = L - win - margin
|
||||
return torch.randint(margin, hi + 1, (n_wells, J), generator=gen, device="cpu").to(device)
|
||||
|
||||
|
||||
def gather_windows(x: torch.Tensor, starts: torch.Tensor, win: int) -> torch.Tensor:
|
||||
"""x (B, ..., L), starts (B, J) → (B, J, ..., win)."""
|
||||
idx = starts[..., None] + torch.arange(win, device=x.device) # (B, J, win)
|
||||
B = x.shape[0]
|
||||
mid = x.shape[1:-1]
|
||||
xe = x.unsqueeze(1).expand(B, idx.shape[1], *mid, x.shape[-1])
|
||||
ie = idx.view(B, idx.shape[1], *([1] * len(mid)), win).expand(B, idx.shape[1], *mid, win)
|
||||
return torch.gather(xe, -1, ie)
|
||||
|
||||
|
||||
def window_loglik(mu, sigma, Y, starts, win):
|
||||
"""mu, sigma (B, L); Y (B, S, L) → ℓ (B, J, S)."""
|
||||
m = gather_windows(mu, starts, win)[:, :, None, :]
|
||||
s = gather_windows(sigma, starts, win)[:, :, None, :]
|
||||
y = gather_windows(Y, starts, win)
|
||||
return (-torch.log(s) - 0.5 * ((y - m) / s) ** 2 - 0.5 * LOG_2PI).sum(-1)
|
||||
|
||||
|
||||
def bank_loss(mu, sigma, Y, logpi, starts, win: int, lam: float | None):
|
||||
"""lam = None → hard-min (max ℓ); otherwise RML with power λ."""
|
||||
ll = window_loglik(mu, sigma, Y, starts, win)
|
||||
if lam is None:
|
||||
return -(ll.max(-1).values / win).mean()
|
||||
v = torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1)
|
||||
return -(v / (lam * win)).mean()
|
||||
|
||||
|
||||
def mse_bank_loss(mu, Y, starts, win: int):
|
||||
"""Mean MSE over the labels of the bank (H1: the optimum is the label blurred by p_δ)."""
|
||||
m = gather_windows(mu, starts, win)[:, :, None, :]
|
||||
y = gather_windows(Y, starts, win)
|
||||
return ((y - m) ** 2).mean()
|
||||
|
||||
|
||||
def shift_bank(y: np.ndarray, max_shift: int) -> np.ndarray:
|
||||
"""(2K+1, L): y shifted by k samples (label y_{i+k}), NaN outside the boundaries."""
|
||||
L = len(y)
|
||||
out = np.full((2 * max_shift + 1, L), np.nan)
|
||||
for n, k in enumerate(range(-max_shift, max_shift + 1)):
|
||||
lo, hi = max(0, -k), min(L, L - k)
|
||||
out[n, lo:hi] = y[lo + k: hi + k]
|
||||
return out
|
||||
|
||||
|
||||
def effective_lambda(labels: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0, max_lag: int = 32) -> tuple[float, float]:
|
||||
"""λ = 1/τ_c with τ_c = 1 + 2 Σ_k ρ(k)², where ρ is the pooled ACF of the training labels high-pass filtered
|
||||
above f_c (a proxy for the residual in the seismic band). Σ runs up to the first lag with ρ ≤ 0 (at most
|
||||
max_lag). Returns (λ, τ_c)."""
|
||||
from ml_porosity.eval.metrics import split_bands
|
||||
|
||||
acc = np.zeros(max_lag + 1)
|
||||
for y in labels:
|
||||
hi = split_bands(np.asarray(y, dtype=float), f_c_hz, dt_ms)[1]
|
||||
hi = hi - hi.mean()
|
||||
a = np.correlate(hi, hi, "full")[len(hi) - 1: len(hi) + max_lag]
|
||||
acc += a
|
||||
rho = acc / acc[0]
|
||||
k = np.argmax(rho[1:] <= 0) + 1 if np.any(rho[1:] <= 0) else max_lag + 1
|
||||
tau_c = 1.0 + 2.0 * float(np.sum(rho[1:k] ** 2))
|
||||
return 1.0 / tau_c, tau_c
|
||||
175
ml_porosity/losses/softdtw.py
Normal file
175
ml_porosity/losses/softdtw.py
Normal file
@@ -0,0 +1,175 @@
|
||||
"""Soft-DTW (Cuturi & Blondel 2017) and DILATE (Le Guen & Thome 2019) for B4c/B4d.
|
||||
|
||||
The cost of cell (i, j) is the Gaussian NLL of label j under prediction (μ_i, σ_i); Sakoe–Chiba band constraint
|
||||
|i − j| ≤ band. The NLL can be negative, so a weighted symmetric step pattern is used (diagonal step ×2,
|
||||
horizontal/vertical ×1; Sakoe & Chiba 1978): every path from (0, 0) to (n−1, m−1) has total weight n + m, so
|
||||
shifting the cost by a constant does not bias the choice of path length. The result is divided by n + m. The DP
|
||||
runs along anti-diagonals, vectorised over the batch, with gradients via autograd.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
BIG = 1e8
|
||||
|
||||
|
||||
def soft_dtw(D: torch.Tensor, gamma: float, band: int | None = None) -> torch.Tensor:
|
||||
"""D (B, n, m) → R(n−1, m−1) (B,) with R(i, j) = softmin_γ(R(i−1, j−1) + 2D_ij, R(i−1, j) + D_ij, R(i, j−1) + D_ij),
|
||||
R(−1, −1) = 0. R is stored per anti-diagonal k = i + j, indexed by i; cells outside the band = BIG."""
|
||||
B, n, m = D.shape
|
||||
big = torch.full((B, 1), BIG, device=D.device, dtype=D.dtype)
|
||||
prev2 = prev1 = torch.full((B, n), BIG, device=D.device, dtype=D.dtype)
|
||||
for k in range(n + m - 1):
|
||||
i0, i1 = max(0, k - m + 1), min(k, n - 1)
|
||||
i = torch.arange(i0, i1 + 1, device=D.device)
|
||||
d = D[:, i, k - i]
|
||||
sh2 = torch.cat([torch.zeros_like(big) if k == 0 else big, prev2[:, :-1]], 1) # sh2[:, i] = R(i−1, j−1)
|
||||
sh1 = torch.cat([big, prev1[:, :-1]], 1) # sh1[:, i] = R(i−1, j)
|
||||
r = torch.stack([sh2[:, i] + 2 * d, sh1[:, i] + d, prev1[:, i] + d], 0) # prev1[:, i] = R(i, j−1)
|
||||
val = -gamma * torch.logsumexp(-r / gamma, 0)
|
||||
if band is not None:
|
||||
val = torch.where(((2 * i - k).abs() <= band)[None, :], val, torch.full_like(val, BIG))
|
||||
prev2, prev1 = prev1, torch.cat([big.expand(B, i0), val, big.expand(B, n - 1 - i1)], 1)
|
||||
return prev1[:, n - 1]
|
||||
|
||||
|
||||
def nll_cost(mu: torch.Tensor, sigma: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
"""mu, sigma, y (B, n) → D (B, n, n), D_ij = −log N(y_j; μ_i, σ_i²)."""
|
||||
return torch.log(sigma)[:, :, None] + 0.5 * ((y[:, None, :] - mu[:, :, None]) / sigma[:, :, None]) ** 2 \
|
||||
+ 0.5 * math.log(2 * math.pi)
|
||||
|
||||
|
||||
def softdtw_loss(mu, sigma, y, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
|
||||
"""mu, sigma, y (B, n): batch mean of soft-DTW/(2n)."""
|
||||
n = mu.shape[-1]
|
||||
return (soft_dtw(nll_cost(mu, sigma, y), gamma, band) / (2 * n)).mean()
|
||||
|
||||
|
||||
def dilate_loss(mu, sigma, y, alpha: float = 0.5, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
|
||||
"""α·soft-DTW/(2n) + (1 − α)·TDI, TDI = ⟨A*, Ω⟩/(2n), A* = ∂R/∂D (step-weighted expected alignment),
|
||||
Ω_ij = ((i − j)/n)² penalises temporal distortion (Le Guen & Thome 2019)."""
|
||||
n = mu.shape[-1]
|
||||
D = nll_cost(mu, sigma, y)
|
||||
if not D.requires_grad:
|
||||
D.requires_grad_(True)
|
||||
v = soft_dtw(D, gamma, band)
|
||||
A = torch.autograd.grad(v.sum(), D, create_graph=True)[0]
|
||||
idx = torch.arange(n, device=mu.device, dtype=mu.dtype)
|
||||
omega = ((idx[:, None] - idx[None, :]) / n) ** 2
|
||||
tdi = (A * omega).sum((1, 2))
|
||||
return ((alpha * v + (1 - alpha) * tdi) / (2 * n)).mean()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- fast version (numba, analytic gradient)
|
||||
#
|
||||
# Same recursion as soft_dtw above. Backward: E(i, j) = ∂R_end/∂R(i, j) = Σ_s E(s)·q_{(i,j)}(s), where q is the
|
||||
# softmax weight of the predecessor in the softmin of cell s; ∂R_end/∂D_ij = E(i, j)·Σ_p w_p q_p(i, j). DILATE
|
||||
# additionally needs ∇_D TDI = H·Ω (Hessian–vector product): the directional derivative along Ω of the whole
|
||||
# forward pass (Ṙ, q̇) and backward pass (Ė) (Mensch & Blondel 2018). Verified against the autograd version in
|
||||
# tests/test_losses.py.
|
||||
|
||||
import numpy as np
|
||||
from numba import njit, prange
|
||||
|
||||
|
||||
@njit(parallel=True, cache=True)
|
||||
def _sdtw_nll(mu, sg, y, gamma, band, alpha):
|
||||
"""For each row b: loss_b = α·R_end + (1 − α)·TDI with D_ij = −log N(y_j; μ_i, σ_i²), Ω_ij = ((i − j)/n)²,
|
||||
together with ∂loss_b/∂μ, ∂loss_b/∂σ. Only cells inside the band are visited; cells outside have R = big, so
|
||||
E = 0, G = 0."""
|
||||
B, n = mu.shape
|
||||
big = 1e10
|
||||
bw = band if band >= 0 else 2 * n
|
||||
hvp = alpha < 1.0
|
||||
c0 = 0.5 * np.log(2.0 * np.pi)
|
||||
loss = np.empty(B)
|
||||
g_mu = np.zeros((B, n))
|
||||
g_s = np.zeros((B, n))
|
||||
for b in prange(B):
|
||||
R = np.full((n + 2, n + 2), big)
|
||||
Rd = np.zeros((n + 2, n + 2))
|
||||
Q = np.zeros((n + 2, n + 2, 3))
|
||||
Qd = np.zeros((n + 2, n + 2, 3))
|
||||
R[0, 0] = 0.0
|
||||
for i in range(1, n + 1):
|
||||
mi = mu[b, i - 1]
|
||||
si = sg[b, i - 1]
|
||||
ls = np.log(si)
|
||||
for j in range(max(1, i - bw), min(n, i + bw) + 1):
|
||||
r = (y[b, j - 1] - mi) / si
|
||||
d = ls + 0.5 * r * r + c0
|
||||
a0 = R[i - 1, j - 1] + 2.0 * d
|
||||
a1 = R[i - 1, j] + d
|
||||
a2 = R[i, j - 1] + d
|
||||
am = min(a0, min(a1, a2))
|
||||
e0 = np.exp(-(a0 - am) / gamma)
|
||||
e1 = np.exp(-(a1 - am) / gamma)
|
||||
e2 = np.exp(-(a2 - am) / gamma)
|
||||
s = e0 + e1 + e2
|
||||
R[i, j] = am - gamma * np.log(s)
|
||||
q0, q1, q2 = e0 / s, e1 / s, e2 / s
|
||||
Q[i, j, 0], Q[i, j, 1], Q[i, j, 2] = q0, q1, q2
|
||||
if hvp:
|
||||
z = ((i - j) / n) ** 2
|
||||
b0 = Rd[i - 1, j - 1] + 2.0 * z
|
||||
b1 = Rd[i - 1, j] + z
|
||||
b2 = Rd[i, j - 1] + z
|
||||
rd = q0 * b0 + q1 * b1 + q2 * b2
|
||||
Rd[i, j] = rd
|
||||
Qd[i, j, 0] = -q0 * (b0 - rd) / gamma
|
||||
Qd[i, j, 1] = -q1 * (b1 - rd) / gamma
|
||||
Qd[i, j, 2] = -q2 * (b2 - rd) / gamma
|
||||
E = np.zeros((n + 2, n + 2))
|
||||
Ed = np.zeros((n + 2, n + 2))
|
||||
E[n, n] = 1.0
|
||||
tdi = 0.0
|
||||
for i in range(n, 0, -1):
|
||||
mi = mu[b, i - 1]
|
||||
si = sg[b, i - 1]
|
||||
for j in range(min(n, i + bw), max(1, i - bw) - 1, -1):
|
||||
if i < n or j < n:
|
||||
E[i, j] = E[i + 1, j + 1] * Q[i + 1, j + 1, 0] + E[i + 1, j] * Q[i + 1, j, 1] + E[i, j + 1] * Q[i, j + 1, 2]
|
||||
if hvp:
|
||||
Ed[i, j] = (Ed[i + 1, j + 1] * Q[i + 1, j + 1, 0] + E[i + 1, j + 1] * Qd[i + 1, j + 1, 0]
|
||||
+ Ed[i + 1, j] * Q[i + 1, j, 1] + E[i + 1, j] * Qd[i + 1, j, 1]
|
||||
+ Ed[i, j + 1] * Q[i, j + 1, 2] + E[i, j + 1] * Qd[i, j + 1, 2])
|
||||
c = 2.0 * Q[i, j, 0] + Q[i, j, 1] + Q[i, j, 2]
|
||||
gd = alpha * E[i, j] * c # ∂loss/∂D_ij
|
||||
if hvp:
|
||||
cd = 2.0 * Qd[i, j, 0] + Qd[i, j, 1] + Qd[i, j, 2]
|
||||
gd += (1.0 - alpha) * (Ed[i, j] * c + E[i, j] * cd)
|
||||
tdi += E[i, j] * c * ((i - j) / n) ** 2
|
||||
r = y[b, j - 1] - mi
|
||||
g_mu[b, i - 1] -= gd * r / (si * si)
|
||||
g_s[b, i - 1] += gd * (1.0 / si - r * r / (si * si * si))
|
||||
loss[b] = alpha * R[n, n] + (1.0 - alpha) * tdi
|
||||
return loss, g_mu, g_s
|
||||
|
||||
|
||||
class _SoftDTWNLL(torch.autograd.Function):
|
||||
"""Batch mean of [α·R_end + (1 − α)·TDI]/(2n) with NLL cost; computed on the CPU (float64)."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, mu, sigma, y, gamma, band, alpha):
|
||||
m_, s_, y_ = (t.detach().double().cpu().numpy() for t in (mu, sigma, y))
|
||||
B, n = m_.shape
|
||||
loss, g_mu, g_s = _sdtw_nll(m_, s_, y_, float(gamma), -1 if band is None else int(band), float(alpha))
|
||||
T = lambda a: torch.as_tensor(a, dtype=mu.dtype, device=mu.device)
|
||||
ctx.save_for_backward(T(g_mu / (2 * n * B)), T(g_s / (2 * n * B)))
|
||||
return T(loss.mean() / (2 * n))
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, go):
|
||||
g_mu, g_s = ctx.saved_tensors
|
||||
return go * g_mu, go * g_s, None, None, None, None
|
||||
|
||||
|
||||
def softdtw_loss_fast(mu, sigma, y, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
|
||||
return _SoftDTWNLL.apply(mu, sigma, y, gamma, band, 1.0)
|
||||
|
||||
|
||||
def dilate_loss_fast(mu, sigma, y, alpha: float = 0.5, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
|
||||
return _SoftDTWNLL.apply(mu, sigma, y, gamma, band, alpha)
|
||||
83
ml_porosity/models/bank_train.py
Normal file
83
ml_porosity/models/bank_train.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Shared training routine for the P2 methods on D2 (plan §4.4–4.5, §5.3).
|
||||
|
||||
A single CNNGRUHetero predicts (μ, σ) over the full main window; the loss is computed on fixed 64-sample
|
||||
sub-windows (starting at 0, 2, …, L − 64), full batch, with the same optimizer for all methods. The methods
|
||||
differ only in:
|
||||
|
||||
- "bank": label bank Y (N, S, L), log π (N, S) and λ (None → hard-min). S = 1 gives the Gaussian NLL (Oracle,
|
||||
B3a–d); a bank of ±K shifts with uniform π gives B4a/B4b; posterior warp samples give M1/M2.
|
||||
- "softdtw" / "dilate": soft-DTW / DILATE with a Gaussian NLL cost on each sub-window (B4c/B4d).
|
||||
- "mse_win": MSE of μ against per-sub-window labels, Ywin (N, J, win) (H1: fixed per-window shift).
|
||||
|
||||
Test predictions are taken at the step counts in `budgets` along a single training trajectory (full batch,
|
||||
deterministic given the seed), which is equivalent to training separately for each budget.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from ml_porosity.losses.rml import bank_loss, gather_windows
|
||||
from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast
|
||||
from ml_porosity.models.train import CNNGRUHetero, predict
|
||||
|
||||
WIN = 64
|
||||
|
||||
|
||||
def window_starts_fixed(L: int, win: int = WIN, step: int = 2) -> np.ndarray:
|
||||
return np.arange(0, L - win + 1, step)
|
||||
|
||||
|
||||
def zscore_patch(seis: np.ndarray, sel: np.ndarray) -> np.ndarray:
|
||||
"""Patch (C, n_ext) → (C, L) on the main window, z-scored per channel (as in P1)."""
|
||||
p = seis[:, sel].astype(np.float64)
|
||||
return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8)
|
||||
|
||||
|
||||
def train_predict(X: np.ndarray, Xte: np.ndarray, spec: dict, cfg: dict, seed: int, budgets: list[int],
|
||||
device: str) -> dict[int, tuple[np.ndarray, np.ndarray]]:
|
||||
"""X (N, C, L), Xte (M, C, L); labels in spec are already standardised. Returns {budget: (μ, σ)} for
|
||||
Xte (M, L), on the standardised scale."""
|
||||
# Same RNG stream as torch.manual_seed, but only touches the selected device: manual_seed_all opens a CUDA
|
||||
# context on every visible GPU (shared machine).
|
||||
torch.default_generator.manual_seed(seed)
|
||||
if torch.device(device).type == "cuda":
|
||||
torch.cuda.set_device(device)
|
||||
torch.cuda.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
|
||||
x = T(X)
|
||||
N, _, L = X.shape
|
||||
starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device)
|
||||
kind = spec["kind"]
|
||||
if kind == "bank":
|
||||
Y, logpi, lam = T(spec["Y"]), T(spec["logpi"]), spec["lam"]
|
||||
loss_fn = lambda mu, s: bank_loss(mu, s, Y, logpi, starts, WIN, lam)
|
||||
elif kind in ("softdtw", "dilate"):
|
||||
yw = gather_windows(T(spec["Y"]).reshape(N, L), starts, WIN).reshape(-1, WIN)
|
||||
f = softdtw_loss_fast if kind == "softdtw" else dilate_loss_fast
|
||||
kw = {k: spec[k] for k in ("gamma", "band", "alpha") if k in spec}
|
||||
loss_fn = lambda mu, s: f(gather_windows(mu, starts, WIN).reshape(-1, WIN),
|
||||
gather_windows(s, starts, WIN).reshape(-1, WIN), yw, **kw)
|
||||
elif kind == "mse_win":
|
||||
Yw = T(spec["Ywin"])
|
||||
loss_fn = lambda mu, s: ((gather_windows(mu, starts, WIN) - Yw) ** 2).mean()
|
||||
else:
|
||||
raise ValueError(kind)
|
||||
|
||||
model = CNNGRUHetero(X.shape[1], cfg["d_channels"], cfg["p_dropout"]).to(device)
|
||||
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
|
||||
out = {}
|
||||
for step in range(1, max(budgets) + 1):
|
||||
model.train()
|
||||
opt.zero_grad()
|
||||
mu, s = model(x)
|
||||
loss = loss_fn(mu[:, 0], s[:, 0])
|
||||
loss.backward()
|
||||
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
|
||||
opt.step()
|
||||
if step in budgets:
|
||||
out[step] = predict(model, Xte, device)
|
||||
return out
|
||||
@@ -1,6 +1,6 @@
|
||||
"""CNN (dilated) + GRU 2 tầng hai chiều + skip head 1×1.
|
||||
"""Dilated CNN + 2-layer bidirectional GRU + 1×1 skip head.
|
||||
|
||||
Chuyển nguyên trạng từ `test 2/train_open_patch_v2.py` (lớp CNNGRU); không đổi kiến trúc.
|
||||
Ported verbatim from `test 2/train_open_patch_v2.py` (class CNNGRU); the architecture is unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Huấn luyện CNN–GRU cho B2 (loss gốc) và B3 (Gaussian NLL), chọn epoch theo vòng inner."""
|
||||
"""CNN–GRU training for B2 (original loss) and B3 (Gaussian NLL), with epoch selection in the inner loop."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,7 +12,7 @@ from ml_porosity.models.cnn_gru import CNNGRU
|
||||
|
||||
|
||||
class CNNGRUHetero(nn.Module):
|
||||
"""Backbone CNN–GRU v2 với head 2 kênh: μ và σ = softplus(·) + σ_min."""
|
||||
"""CNN–GRU v2 backbone with a 2-channel head: μ and σ = softplus(·) + σ_min."""
|
||||
|
||||
def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05, sigma_min: float = 1e-3):
|
||||
super().__init__()
|
||||
@@ -35,7 +35,7 @@ def gaussian_nll(mu, sigma, y):
|
||||
|
||||
def train_cnn(Xtr, Ytr, cfg: dict, kind: str, seed: int, epochs: int, device: str,
|
||||
Xva=None, Yva=None, eval_every: int = 25):
|
||||
"""kind: "legacy" (B2) hoặc "nll" (B3). Y ở thang đã chuẩn hoá. Trả về (model, [(epoch, val_mse)])."""
|
||||
"""kind: "legacy" (B2) or "nll" (B3). Y is on the standardised scale. Returns (model, [(epoch, val_mse)])."""
|
||||
torch.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
T = lambda a: torch.tensor(a, dtype=torch.float32, device=device)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Đường dẫn dự án. Không có đường dẫn tuyệt đối: mọi thứ tính từ gốc repo
|
||||
hoặc từ biến môi trường ML_POROSITY_F3_ROOT / ML_POROSITY_VOLVE_ROOT / ML_POROSITY_NLOG_ROOT / ML_POROSITY_OUTPUTS."""
|
||||
"""Project paths. No absolute paths: everything is resolved from the repository root
|
||||
or from the environment variables ML_POROSITY_F3_ROOT / ML_POROSITY_VOLVE_ROOT / ML_POROSITY_NLOG_ROOT / ML_POROSITY_OUTPUTS."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,7 +10,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def f3_root() -> Path:
|
||||
"""Thư mục survey F3 (chứa `.survey`)."""
|
||||
"""F3 survey directory (containing `.survey`)."""
|
||||
env = os.environ.get("ML_POROSITY_F3_ROOT")
|
||||
return Path(env) if env else REPO_ROOT / "data" / "F3_Demo_2023" / "F3_Demo_2023"
|
||||
|
||||
@@ -24,13 +24,13 @@ def f3_segy() -> Path:
|
||||
|
||||
|
||||
def volve_root() -> Path:
|
||||
"""Thư mục Volve tải từ data village (Geophysical_Interpretations/, Seismic/, ...)."""
|
||||
"""Volve directory downloaded from the Data Village (Geophysical_Interpretations/, Seismic/, ...)."""
|
||||
env = os.environ.get("ML_POROSITY_VOLVE_ROOT")
|
||||
return Path(env) if env else REPO_ROOT / "data" / "Volve"
|
||||
|
||||
|
||||
def nlog_root() -> Path:
|
||||
"""LAS và TD công khai của NLOG cho các giếng F3 (tải theo docs/research/f3-nlog-inventory.xlsx)."""
|
||||
"""Public NLOG LAS and TD files for the F3 wells (downloaded per docs/research/f3-nlog-inventory.xlsx)."""
|
||||
env = os.environ.get("ML_POROSITY_NLOG_ROOT")
|
||||
return Path(env) if env else REPO_ROOT / "data" / "NLOG"
|
||||
|
||||
|
||||
36
ml_porosity/registration/labels.py
Normal file
36
ml_porosity/registration/labels.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""Labels per warp sample (plan §4.3): y^(s)(t_i) = (𝒜φ)(τ^(s)(t_i)).
|
||||
|
||||
Logs live on the uniform fine τ grid (sonic time). 𝒜 is a zero-phase low-pass filter applied before 4 ms
|
||||
sampling (as in resample.log_to_time); τ^(s) is the inverse map of t(·; u^(s)), which exists because t is
|
||||
monotone.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
|
||||
def antialias(y: np.ndarray, d_fine_ms: float, out_dt_ms: float = 4.0, cutoff_frac: float = 0.8,
|
||||
order: int = 6) -> np.ndarray:
|
||||
"""Low-pass filter at cutoff_frac·Nyquist of the out_dt_ms grid (default 100 Hz for 4 ms)."""
|
||||
fc = cutoff_frac * 500.0 / out_dt_ms
|
||||
sos = signal.butter(order, fc, fs=1000.0 / d_fine_ms, output="sos")
|
||||
return signal.sosfiltfilt(sos, y, padtype="even")
|
||||
|
||||
|
||||
def invert_warps(t_of_tau: np.ndarray, tau: np.ndarray, t_out: np.ndarray) -> np.ndarray:
|
||||
"""τ(t_out) for each warp sample; t_of_tau (S, n) strictly increasing on the tau grid. NaN outside the
|
||||
domain."""
|
||||
t_of_tau = np.atleast_2d(t_of_tau)
|
||||
out = np.empty((len(t_of_tau), len(t_out)))
|
||||
for s, ts in enumerate(t_of_tau):
|
||||
out[s] = np.interp(t_out, ts, tau, left=np.nan, right=np.nan)
|
||||
return out
|
||||
|
||||
|
||||
def labels_for_warps(tau_fine: np.ndarray, y_filtered: np.ndarray, t_of_tau_fine: np.ndarray,
|
||||
t_out: np.ndarray) -> np.ndarray:
|
||||
"""(S, L): labels at t_out for each warp. y_filtered is the log after `antialias` on tau_fine."""
|
||||
tau_at = invert_warps(t_of_tau_fine, tau_fine, t_out)
|
||||
return np.where(np.isfinite(tau_at), np.interp(np.nan_to_num(tau_at), tau_fine, y_filtered), np.nan)
|
||||
122
ml_porosity/registration/pipeline.py
Normal file
122
ml_porosity/registration/pipeline.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Registration of the training wells of one D2 cell (plan §4.1–4.3, §5.3).
|
||||
|
||||
Uses training-well data only: warp hyperparameters (MAP-II on the training anchors), statistical wavelet from the
|
||||
centre trace + constant phase maximising the marginal likelihood over the posterior warp samples, posterior warp
|
||||
samples, physical M2 weights, label banks for each method, λ = 1/τ_c, and warp diagnostics against the true warp
|
||||
(for reporting only, not used for selection).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
|
||||
from ml_porosity.losses.rml import effective_lambda
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.sampler import ess, sample_warps, temper
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, phase_loglik, synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3a, tie_b3b, tie_b3c, warp_errors, warp_mean
|
||||
from ml_porosity.registration.warp_prior import WarpHyper, fit_hyper
|
||||
|
||||
|
||||
def fit_cell_hyper(R, obs: list[dict], reg: dict, seed: int = 0) -> tuple[WarpHyper, dict]:
|
||||
"""MAP-II for (m_g, σ_g, ℓ); σ_a, σ_b fixed; log-normal hyperprior (median, log sd) for σ_g, ℓ."""
|
||||
wells = [{"grid": R.grid, "tau_k": o["tau_k"], "d_k": o["t_k"] - o["tau_k"]} for o in obs]
|
||||
hp = reg["hyperprior"]
|
||||
init = WarpHyper(0.0, hp["sigma_g"][0], hp["ell_ms"][0], reg["sigma_b_ms"], reg["sigma_a_ms"], reg["kernel"])
|
||||
return fit_hyper(wells, init, fixed={"sigma_a_ms": reg["sigma_a_ms"], "sigma_b_ms": reg["sigma_b_ms"]},
|
||||
hyperprior={k: (np.log(m), s) for k, (m, s) in hp.items()}, n_starts=reg["hyper_starts"],
|
||||
seed=seed)
|
||||
|
||||
|
||||
def label_norm(R, obs: list[dict]) -> tuple[float, float]:
|
||||
"""Mean/standard deviation of the (anti-aliased) φ log over τ ∈ main window — independent of the tie,
|
||||
so all methods use the same normalisation."""
|
||||
m0, m1 = R.cfg["main_window_ms"]
|
||||
sel = (R.tau_fine >= m0) & (R.tau_fine <= m1)
|
||||
v = np.concatenate([antialias(o["phi_log"], R.cfg["fine_dt_ms"], R.dt)[sel] for o in obs])
|
||||
return float(v.mean()), float(v.std())
|
||||
|
||||
|
||||
PHASES = np.arange(-180, 180, 15)
|
||||
|
||||
|
||||
def register(R, obs: list[dict], reg: dict, seed: int, prior: WarpHyper | None = None) -> dict:
|
||||
"""prior = None: with anchors; returns banks for Oracle, B3a–d, B4 (±K shift bank), M1, M2.
|
||||
prior given: anchor-free variant (H4) — M1/M2 only, samples from the prior, zero-phase wavelet (the true phase
|
||||
of D2, i.e. favourable to the anchor-free variant).
|
||||
|
||||
banks[m]: (N, S_m, L) labels on t_main; logpi[m]: (N, S_m)."""
|
||||
f = R.cfg["fine_dt_ms"]
|
||||
fac = int(round(R.dt / f))
|
||||
anchors = prior is None
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
w0 = statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"])
|
||||
out = {"wells": [o["name"] for o in obs], "diag": [], "norm": label_norm(R, obs)}
|
||||
if anchors:
|
||||
h, info = fit_cell_hyper(R, obs, reg, seed)
|
||||
out["hyper_info"] = {k: info[k] for k in ("log_marginal", "at_bound")}
|
||||
else:
|
||||
h = prior
|
||||
out["hyper"] = h.as_dict()
|
||||
|
||||
# warp samples, labels and physical log-likelihood per constant phase for every well; one phase per cell
|
||||
lab = lambda y_aa, T, t=R.t_main: labels_for_warps(R.tau_fine, y_aa, np.atleast_2d(T), t)
|
||||
w0_fine = fine_wavelet(w0, fac)
|
||||
T_all, Y_all, ok_all, LL = [], [], [], []
|
||||
for i, o in enumerate(obs):
|
||||
rng = np.random.default_rng([seed, i, 11])
|
||||
tk, ttk = (o["tau_k"], o["t_k"]) if anchors else (np.zeros(0), np.zeros(0))
|
||||
smp = sample_warps(R.grid, h, tk, ttk, reg["S"], reg["g_max"], rng)
|
||||
T = R.grid.t_of_tau(smp["b"], smp["g"], tau=R.tau_fine)
|
||||
Y = lab(antialias(o["phi_log"], f, R.dt), T)
|
||||
ok = np.all(np.isfinite(Y), 1) # valid domain: keep only warps covering the whole main window
|
||||
Y[~ok] = Y[ok][0]
|
||||
T_all.append(T)
|
||||
Y_all.append(Y)
|
||||
ok_all.append(ok)
|
||||
LL.append(phase_loglik(synth_for_warps(R.tau_fine, o["ai_log"], T, R.t_fine, R.t_ext, w0_fine), seis[i], PHASES))
|
||||
k = fit_phase(LL, ok_all, PHASES) if anchors else int(np.flatnonzero(PHASES == 0)[0])
|
||||
out["phase"] = float(PHASES[k])
|
||||
w_fine = fine_wavelet(rotate_phase(w0, PHASES[k]), fac)
|
||||
|
||||
K = reg["shift_K"]
|
||||
t_wide = np.arange(R.t_main[0] - K * R.dt, R.t_main[-1] + K * R.dt + R.dt / 2, R.dt)
|
||||
L = len(R.t_main)
|
||||
names = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4", "M1", "M2"] if anchors else ["M1", "M2"]
|
||||
banks = {m: [] for m in names}
|
||||
logpi = {"M1": [], "M2": []}
|
||||
for i, o in enumerate(obs):
|
||||
T, Y, ok, ll = T_all[i], Y_all[i], ok_all[i], LL[i][k]
|
||||
tk, ttk = (o["tau_k"], o["t_k"]) if anchors else (np.zeros(0), np.zeros(0))
|
||||
lp2, gam, ess2 = temper(np.where(ok, ll, -np.inf), reg["ess_min_frac"])
|
||||
lp1 = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
|
||||
d = {"well": o["name"], "n_anchor": int(len(tk)), "n_valid": int(ok.sum()), "gamma": gam,
|
||||
"ess": ess2, "ess_gamma1": ess(np.where(ok, ll, -np.inf))}
|
||||
d |= {f"M1_{k_}": v for k_, v in warp_errors(T[ok], R.tau_fine, o["t_of_tau_true"], R.t_main).items()}
|
||||
d |= {f"M2_{k_}": v for k_, v in warp_errors(T[ok], R.tau_fine, o["t_of_tau_true"], R.t_main, lp2[ok]).items()}
|
||||
banks["M1"].append(Y)
|
||||
banks["M2"].append(Y)
|
||||
logpi["M1"].append(lp1)
|
||||
logpi["M2"].append(lp2)
|
||||
if anchors:
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
ties = {"Oracle": o["t_of_tau_true"], "B3a": tie_b3a(tk, ttk, R.tau_fine), "B3b": tie_b3b(tk, ttk, R.tau_fine)}
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], ties["B3b"], R.t_fine, R.t_ext, w_fine)[0]
|
||||
ties["B3c"] = tie_b3c(ties["B3b"], R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
ties["B3d"] = warp_mean(T[ok], lp2[ok])
|
||||
for m, t in ties.items():
|
||||
banks[m].append(lab(y_aa, t))
|
||||
if m != "Oracle":
|
||||
d[f"{m}_warp_rmse_ms"] = warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
yw = lab(y_aa, ties["B3b"], t_wide)[0]
|
||||
banks["B4"].append(np.stack([yw[K + j: K + j + L] for j in range(-K, K + 1)]))
|
||||
out["diag"].append(d)
|
||||
out["banks"] = {m: np.stack(v).astype(np.float32) for m, v in banks.items()}
|
||||
out["logpi"] = {m: np.stack(v).astype(np.float32) for m, v in logpi.items()}
|
||||
if anchors:
|
||||
ref = [b[0] for b in out["banks"]["B3b"]]
|
||||
else: # no point tie: M2-weighted mean label as a proxy
|
||||
ref = [np.exp(lp) @ Yb for lp, Yb in zip(out["logpi"]["M2"], out["banks"]["M2"])]
|
||||
out["lam"], out["tau_c"] = effective_lambda(ref, dt_ms=R.dt)
|
||||
return out
|
||||
104
ml_porosity/registration/sampler.py
Normal file
104
ml_porosity/registration/sampler.py
Normal file
@@ -0,0 +1,104 @@
|
||||
"""Warp posterior sampling: elliptical slice sampling (Murray, Adams & MacKay 2010) around the linearised
|
||||
Gaussian posterior, plus tempered importance weights and ESS (plan §4.1–4.2, §4.8).
|
||||
|
||||
Exact target: p(u | anchor) ∝ N(u; μ0, Σ0) · Π_k N(d_k; b + F(τ_k; g), σ_a²) · 1{|g| ≤ g_max},
|
||||
where F uses e^g − 1. Rewritten as N(u; μ_lin, Σ_lin) · exp(L(u)), L = exact log-lik − linearised log-lik
|
||||
(+ constraints), so elliptical slice sampling uses the linearised posterior (Gauss–Newton at the MAP) as the
|
||||
"prior" and L as the likelihood.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior, prior_moments
|
||||
|
||||
|
||||
def _ess_step(f, loglik_f, chol, mu, loglik, rng):
|
||||
nu = mu + chol @ rng.standard_normal(len(mu))
|
||||
log_y = loglik_f + np.log(rng.uniform())
|
||||
th = rng.uniform(0, 2 * np.pi)
|
||||
lo, hi = th - 2 * np.pi, th
|
||||
for _ in range(200):
|
||||
fp = mu + (f - mu) * np.cos(th) + (nu - mu) * np.sin(th)
|
||||
lp = loglik(fp)
|
||||
if lp > log_y:
|
||||
return fp, lp
|
||||
if th < 0:
|
||||
lo = th
|
||||
else:
|
||||
hi = th
|
||||
th = rng.uniform(lo, hi)
|
||||
return f, loglik_f
|
||||
|
||||
|
||||
def elliptical_slice(mu, cov, loglik, n_samples, rng, n_chains=4, burn=40, thin=4, init=None):
|
||||
"""Elliptical slice sampling with prior N(mu, cov). Returns (n_samples, d). Chains start from init (if given)
|
||||
or mu."""
|
||||
chol = np.linalg.cholesky(cov + 1e-9 * np.eye(len(mu)) * max(np.trace(cov) / len(mu), 1e-12))
|
||||
per = int(np.ceil(n_samples / n_chains))
|
||||
out = []
|
||||
for c in range(n_chains):
|
||||
f = mu.copy() if init is None else init.copy()
|
||||
lf = loglik(f)
|
||||
if not np.isfinite(lf):
|
||||
f, lf = mu.copy(), loglik(mu)
|
||||
for it in range(burn + per * thin):
|
||||
f, lf = _ess_step(f, lf, chol, mu, loglik, rng)
|
||||
if it >= burn and (it - burn) % thin == thin - 1:
|
||||
out.append(f.copy())
|
||||
return np.array(out[:n_samples])
|
||||
|
||||
|
||||
def sample_warps(grid: WarpGrid, h: WarpHyper, tau_k, t_k, n_samples: int = 64, g_max: float = 0.15,
|
||||
rng=None, **kw) -> dict:
|
||||
"""Samples (b, g) from the warp posterior conditioned on anchors (τ_k, t_k). No anchors ⇒ prior samples
|
||||
(truncated at g_max). Returns {"u": (S, n+1), "b", "g", "mu_lin", "cov_lin"}."""
|
||||
rng = rng or np.random.default_rng(0)
|
||||
tau_k = np.asarray(tau_k, dtype=float)
|
||||
d_k = np.asarray(t_k, dtype=float) - tau_k
|
||||
if tau_k.size:
|
||||
mu, cov, A, off = laplace_posterior(grid, h, tau_k, d_k)
|
||||
P = interp_matrix(tau_k, grid.tau) @ grid.Q
|
||||
else:
|
||||
mu, cov = prior_moments(grid, h)
|
||||
s2 = h.sigma_a_ms**2
|
||||
|
||||
def loglik(u):
|
||||
g = u[1:]
|
||||
if np.max(np.abs(g)) > g_max:
|
||||
return -np.inf
|
||||
if not tau_k.size:
|
||||
return 0.0
|
||||
exact = u[0] + P @ np.expm1(g)
|
||||
lin = A @ u + off
|
||||
return float(-0.5 * (np.sum((d_k - exact) ** 2) - np.sum((d_k - lin) ** 2)) / s2)
|
||||
|
||||
init = mu.copy()
|
||||
init[1:] = np.clip(init[1:], -0.9 * g_max, 0.9 * g_max)
|
||||
u = elliptical_slice(mu, cov, loglik, n_samples, rng, init=init, **kw)
|
||||
return {"u": u, "b": u[:, 0], "g": u[:, 1:], "mu_lin": mu, "cov_lin": cov}
|
||||
|
||||
|
||||
def ess(logw: np.ndarray) -> float:
|
||||
w = np.exp(logw - np.max(logw))
|
||||
return float(w.sum() ** 2 / np.sum(w**2))
|
||||
|
||||
|
||||
def temper(loglik: np.ndarray, min_frac: float = 0.25, tol: float = 1e-3) -> tuple[np.ndarray, float, float]:
|
||||
"""Weights π_s ∝ p_s^γ with the largest γ ∈ [0, 1] such that ESS ≥ min_frac·S (bisection).
|
||||
Returns (normalised log π, γ, ESS)."""
|
||||
ll = np.asarray(loglik, dtype=float)
|
||||
S = len(ll)
|
||||
target = min_frac * S
|
||||
if ess(ll) >= target:
|
||||
g = 1.0
|
||||
else:
|
||||
lo, hi = 0.0, 1.0
|
||||
while hi - lo > tol:
|
||||
mid = 0.5 * (lo + hi)
|
||||
lo, hi = (mid, hi) if ess(mid * ll) >= target else (lo, mid)
|
||||
g = lo
|
||||
lw = g * ll
|
||||
lw = lw - np.logaddexp.reduce(lw)
|
||||
return lw, g, ess(lw)
|
||||
288
ml_porosity/registration/smc.py
Normal file
288
ml_porosity/registration/smc.py
Normal file
@@ -0,0 +1,288 @@
|
||||
"""Warp posterior conditioned on anchors and seismic via SMC tempering (post-G-B diagnostic, plan §4.2, §9).
|
||||
|
||||
protocol_p2 draws S = 64 samples from the anchor posterior and then weights them by π ∝ p(s | u)^γ; the ESS at
|
||||
γ = 1 collapses to ≈ 1, so the rule ESS ≥ S/4 forces γ down to 0.02–0.11 and the samples carry almost no seismic
|
||||
information. Here we sample directly from
|
||||
|
||||
π_γ(u) ∝ p(u | anchor) · p(s | u)^γ
|
||||
|
||||
by SMC tempering (Del Moral, Doucet & Jasra 2006): start from anchor-posterior samples (sampler.sample_warps),
|
||||
increase γ in adaptive steps that keep ESS ≥ P/2, apply systematic resampling, then move the particles by
|
||||
elliptical slice sampling with a Gaussian reference q (Gauss–Newton approximation of π_γ around the particle mean,
|
||||
inflated) and "likelihood" π_γ/q — this leaves π_γ exactly invariant for any q with full support.
|
||||
|
||||
Whitened coordinates z: u = μ_lin + L z with Σ_lin = L Lᵀ (linearised anchor posterior), so
|
||||
log p(u | anchor) = −½‖z‖² + L_a(u) + const, with L_a as in sampler.sample_warps.
|
||||
|
||||
γ (power likelihood): −(n/2) log RSS treats the residual as white; band-limited noise and wavelet error make it
|
||||
over-count information. Matching the curvature to the sandwich variance of the score gives γ = 1/κ,
|
||||
κ = Σ_{|k| ≤ K} ρ_r(k) ρ_d(k), where ρ_r is the residual ACF and ρ_d is the ACF of the time derivative of the
|
||||
synthetic (residual_kappa).
|
||||
|
||||
Constant wavelet phase (smc_fit_phase): fit_phase in protocol_p2 takes log mean exp ℓ over S anchor-posterior
|
||||
samples at γ = 1 — essentially a max over a sample that is off by a few ms per well, so the phase compensates for
|
||||
warp error. Here we maximise Σ_w log Z_w(φ) with Z_w(φ) = ∫ p(u | anchor) p(s_w | u, φ)^{γ_w} du, where log Z_w
|
||||
is estimated by the SMC itself for each phase on a grid.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
import numpy as np
|
||||
from scipy.linalg import solve_triangular
|
||||
|
||||
from ml_porosity.data.wavelet import rotate_phase
|
||||
from ml_porosity.registration.sampler import ess
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine, profile_loglik
|
||||
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior
|
||||
|
||||
|
||||
def residual_kappa(syn: np.ndarray, seis: np.ndarray, max_lag: int = 16) -> float:
|
||||
"""κ = Σ_{|k| ≤ K} ρ_r(k) ρ_d(k) ≥ 1: score-variance inflation factor under correlated residuals (r = residual
|
||||
after profiling α ≥ 0, d = time derivative of the synthetic). A white residual gives κ ≈ 1."""
|
||||
a = max(float(syn @ seis) / max(float(syn @ syn), 1e-30), 0.0)
|
||||
|
||||
def acf(x):
|
||||
x = x - x.mean()
|
||||
c = np.correlate(x, x, "full")[len(x) - 1: len(x) + max_lag]
|
||||
return c / c[0]
|
||||
|
||||
rr, rd = acf(seis - a * syn), acf(np.gradient(syn))
|
||||
return max(1.0, 1.0 + 2.0 * float(np.sum(rr[1:] * rd[1:])))
|
||||
|
||||
|
||||
class TiePosterior:
|
||||
"""π_γ for one well in z coordinates; synthetics are computed for many particles at once.
|
||||
|
||||
t(τ) is piecewise linear between warp-grid nodes (as in WarpGrid.t_of_tau with a fine tau), so the inverse map
|
||||
τ(t) is also piecewise linear and AI as a function of t is obtained exactly by two interpolations; t_fine is
|
||||
cropped to the seismic window ± half a wavelet (result identical to tie_likelihood.synth_for_warps)."""
|
||||
|
||||
def __init__(self, grid: WarpGrid, h: WarpHyper, tau_k, t_k, g_max: float, tau_fine: np.ndarray,
|
||||
ai_log: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray, seis: np.ndarray,
|
||||
t_cover: tuple[float, float] | None = None):
|
||||
tau_k = np.asarray(tau_k, dtype=float)
|
||||
if tau_k.size == 0:
|
||||
raise ValueError("anchors required")
|
||||
self.d_k = np.asarray(t_k, dtype=float) - tau_k
|
||||
self.mu, cov, self.A, self.off = laplace_posterior(grid, h, tau_k, self.d_k)
|
||||
jit = 1e-9 * max(np.trace(cov) / len(self.mu), 1e-12) # as in sampler.elliptical_slice
|
||||
self.Lc = np.linalg.cholesky(cov + jit * np.eye(len(self.mu)))
|
||||
self.P = interp_matrix(tau_k, grid.tau) @ grid.Q
|
||||
self.s2a, self.g_max = h.sigma_a_ms**2, g_max
|
||||
self.tau_g, self.QT = grid.tau, grid.Q.T
|
||||
self.tau_fine, self.ai_log, self.t_fine = tau_fine, ai_log, t_fine
|
||||
self.t_out, self.seis = t_out, np.asarray(seis, dtype=float)
|
||||
self._set_wavelet(w_fine)
|
||||
self.cover = t_cover
|
||||
self.n_eval = 0
|
||||
|
||||
def _set_wavelet(self, w_fine: np.ndarray) -> None:
|
||||
self.w_fine = np.asarray(w_fine, dtype=float)
|
||||
m = (len(self.w_fine) // 2 + 2) * (self.t_fine[1] - self.t_fine[0])
|
||||
self.t_crop = self.t_fine[(self.t_fine >= self.t_out[0] - m) & (self.t_fine <= self.t_out[-1] + m)]
|
||||
|
||||
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosterior":
|
||||
"""Copy with a different wavelet (keeps the anchor posterior; Laplace is not recomputed)."""
|
||||
T = copy.copy(self)
|
||||
T._set_wavelet(w_fine)
|
||||
T.n_eval = 0
|
||||
return T
|
||||
|
||||
def u(self, Z: np.ndarray) -> np.ndarray:
|
||||
return self.mu + np.atleast_2d(Z) @ self.Lc.T
|
||||
|
||||
def z(self, U: np.ndarray) -> np.ndarray:
|
||||
return solve_triangular(self.Lc, (np.atleast_2d(U) - self.mu).T, lower=True).T
|
||||
|
||||
def t_grid(self, U: np.ndarray) -> np.ndarray:
|
||||
U = np.atleast_2d(U)
|
||||
return self.tau_g + U[:, :1] + np.expm1(U[:, 1:]) @ self.QT
|
||||
|
||||
def synth(self, U: np.ndarray) -> np.ndarray:
|
||||
ai = np.stack([np.interp(np.interp(self.t_crop, t, self.tau_g), self.tau_fine, self.ai_log)
|
||||
for t in self.t_grid(U)])
|
||||
self.n_eval += len(ai)
|
||||
return forward_fine(ai, self.t_crop, self.t_out, self.w_fine)
|
||||
|
||||
def loglik(self, U: np.ndarray) -> np.ndarray:
|
||||
return profile_loglik(self.synth(U), self.seis)
|
||||
|
||||
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""(log p(u | anchor) + const, ℓ_s(u)) for each row of Z; −inf for particles that violate |g| ≤ g_max or do
|
||||
not cover t_cover."""
|
||||
Z = np.atleast_2d(Z)
|
||||
U = self.u(Z)
|
||||
g = U[:, 1:]
|
||||
exact = U[:, :1] + np.expm1(g) @ self.P.T
|
||||
lin = U @ self.A.T + self.off
|
||||
la = -0.5 * (np.sum((self.d_k - exact) ** 2, 1) - np.sum((self.d_k - lin) ** 2, 1)) / self.s2a
|
||||
ok = np.max(np.abs(g), 1) <= self.g_max
|
||||
if self.cover is not None:
|
||||
tg = self.t_grid(U)
|
||||
ok &= (tg[:, 0] <= self.cover[0]) & (tg[:, -1] >= self.cover[1])
|
||||
ls = np.full(len(Z), -np.inf)
|
||||
if ok.any():
|
||||
ls[ok] = self.loglik(U[ok])
|
||||
return np.where(ok, -0.5 * np.sum(Z**2, 1) + la, -np.inf), ls
|
||||
|
||||
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
|
||||
"""Gaussian reference q = N(m, Λ⁻¹), Λ = I + γ G / infl, G = α̂² JᵀJ / σ̂² (Gauss–Newton of −ℓ_s at m, J by
|
||||
finite differences in z). Returns (m, L) with Λ = L Lᵀ. The Cholesky factor is unique and continuous in G, so
|
||||
samples of q with the same seed do not depend on the basis eigh would pick in a degenerate eigenspace (warp
|
||||
nodes outside the seismic window give zero columns of J) — the condition for smc_torch to match this version
|
||||
up to rounding error."""
|
||||
syn = self.synth(self.u(np.vstack([m, m + eps * np.eye(len(m))])))
|
||||
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
|
||||
a = max(float(s0 @ self.seis) / max(float(s0 @ s0), 1e-30), 0.0)
|
||||
s2 = float(np.sum((self.seis - a * s0) ** 2)) / len(self.seis)
|
||||
return m, np.linalg.cholesky(np.eye(len(m)) + (gamma / infl) * a**2 * (J.T @ J) / s2)
|
||||
|
||||
|
||||
def systematic_resample(logw: np.ndarray, rng) -> np.ndarray:
|
||||
w = np.exp(logw - np.max(logw))
|
||||
c = np.cumsum(w / w.sum())
|
||||
c[-1] = 1.0
|
||||
return np.searchsorted(c, (rng.uniform() + np.arange(len(w))) / len(w))
|
||||
|
||||
|
||||
def next_gamma(ll: np.ndarray, g0: float, g1: float, min_frac: float = 0.5, n_iter: int = 50) -> float:
|
||||
"""Largest γ ∈ (g0, g1] such that the ESS of the incremental weights (γ − g0)·ℓ stays ≥ min_frac·P (bisection)."""
|
||||
target = min_frac * len(ll)
|
||||
if ess((g1 - g0) * ll) >= target:
|
||||
return g1
|
||||
lo, hi = 0.0, g1 - g0
|
||||
for _ in range(n_iter):
|
||||
mid = 0.5 * (lo + hi)
|
||||
lo, hi = (mid, hi) if ess(mid * ll) >= target else (lo, mid)
|
||||
return g0 + max(lo, 1e-12)
|
||||
|
||||
|
||||
def ess_moves(T: TiePosterior, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60):
|
||||
"""n_moves elliptical slice steps for all particles simultaneously; the "prior" is q = ref, the "likelihood" is
|
||||
π_γ / q. Returns (Z, base, ll, mean number of shrinkages per step)."""
|
||||
m, L = ref
|
||||
logq = lambda X: -0.5 * np.sum(((X - m) @ L) ** 2, 1)
|
||||
comb = lambda b, l: np.where(np.isfinite(b), b + gamma * l, -np.inf)
|
||||
Z, base, ll = Z.copy(), base.copy(), ll.copy()
|
||||
Lq = comb(base, ll) - logq(Z)
|
||||
P, d = Z.shape
|
||||
shrink = 0
|
||||
for _ in range(n_moves):
|
||||
nu = m + solve_triangular(L, rng.standard_normal((P, d)).T, lower=True, trans="T").T
|
||||
log_y = Lq + np.log(rng.uniform(size=P))
|
||||
th = rng.uniform(0.0, 2 * np.pi, P)
|
||||
lo, hi = th - 2 * np.pi, th.copy()
|
||||
act = np.arange(P)
|
||||
for _ in range(max_iter):
|
||||
if act.size == 0:
|
||||
break
|
||||
c, s = np.cos(th[act])[:, None], np.sin(th[act])[:, None]
|
||||
zp = m + (Z[act] - m) * c + (nu[act] - m) * s
|
||||
b, l = T.parts(zp)
|
||||
lq = comb(b, l) - logq(zp)
|
||||
acc = lq > log_y[act]
|
||||
i = act[acc]
|
||||
Z[i], base[i], ll[i], Lq[i] = zp[acc], b[acc], l[acc], lq[acc]
|
||||
rej = act[~acc]
|
||||
neg = th[rej] < 0
|
||||
lo[rej[neg]] = th[rej[neg]]
|
||||
hi[rej[~neg]] = th[rej[~neg]]
|
||||
th[rej] = rng.uniform(lo[rej], hi[rej])
|
||||
shrink += rej.size
|
||||
act = rej
|
||||
return Z, base, ll, shrink / (P * n_moves)
|
||||
|
||||
|
||||
def smc_tie_posterior(T: TiePosterior, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
|
||||
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
|
||||
"""SMC tempering from Z0 (P, d) — anchor-posterior samples in z coordinates (γ = 0) — through increasing γ
|
||||
checkpoints.
|
||||
|
||||
Returns {"Z": {γ: (P, d)}, "ll": {γ: (P,)}, "logZ": {γ: log Ẑ_γ}, "stages": [...]}: at each checkpoint, the
|
||||
equally weighted particles after the move step and the estimate of log ∫ p(u | anchor) p(s | u)^γ du (product of
|
||||
the mean incremental weights); stages records γ, the ESS before resampling, the number of distinct particles
|
||||
after resampling, the mean number of shrinkages, and the RMS jump in z."""
|
||||
Z = np.atleast_2d(Z0).copy()
|
||||
base, ll = T.parts(Z)
|
||||
if not np.all(np.isfinite(base)):
|
||||
raise ValueError("initial samples violate the constraints")
|
||||
g, logZ = 0.0, 0.0
|
||||
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
|
||||
for gk in sorted(set(float(x) for x in checkpoints)):
|
||||
while g < gk:
|
||||
g_new = next_gamma(ll, g, gk, min_frac)
|
||||
logw = (g_new - g) * ll
|
||||
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
|
||||
idx = systematic_resample(logw, rng)
|
||||
Z, base, ll = Z[idx], base[idx], ll[idx]
|
||||
Zb = Z.copy()
|
||||
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference(Z.mean(0), g_new, infl), n_moves, rng)
|
||||
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
|
||||
"shrink": sh, "jump_z": float(np.sqrt(np.mean((Z - Zb) ** 2)))})
|
||||
g = g_new
|
||||
if len(out["stages"]) >= max_stages:
|
||||
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
|
||||
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.copy(), ll.copy(), logZ
|
||||
return out
|
||||
|
||||
|
||||
def phase_basis(w0: np.ndarray, factor: int) -> np.ndarray:
|
||||
"""(2, n_fine): fine wavelet of w0 and of w0 rotated by 90°. rotate_phase(w, φ) = cos φ·w + sin φ·rotate_phase(w,
|
||||
90°) and fine_wavelet is linear, so the fine wavelet at phase φ is cos φ·B[0] + sin φ·B[1] (exact, not an
|
||||
approximation)."""
|
||||
return np.stack([fine_wavelet(w0, factor), fine_wavelet(rotate_phase(w0, 90.0), factor)])
|
||||
|
||||
|
||||
def phase_wavelet(B: np.ndarray, phase_deg: float) -> np.ndarray:
|
||||
p = np.deg2rad(phase_deg)
|
||||
return np.cos(p) * B[0] + np.sin(p) * B[1]
|
||||
|
||||
|
||||
def gamma_acf(T: TiePosterior, Z: np.ndarray, ll: np.ndarray) -> float:
|
||||
"""γ = 1/κ, with κ evaluated at the particle with the largest ℓ_s."""
|
||||
return 1.0 / residual_kappa(T.synth(T.u(Z[int(np.argmax(ll))]))[0], T.seis)
|
||||
|
||||
|
||||
def smc_fit_phase(Ts: list[TiePosterior], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
|
||||
step: float = 15.0, half_width: int = 3, max_extra: int = 6, run=smc_tie_posterior,
|
||||
**smc_kw) -> tuple[float, dict]:
|
||||
"""Common constant phase for the training wells: maximise Σ_w log Z_w(φ),
|
||||
Z_w(φ) = ∫ p(u | anchor) p(s_w | u, φ)^{γ_w} du.
|
||||
|
||||
log Z_w(φ) is taken from the SMC itself (smc_tie_posterior from anchor-posterior samples Z0s[w] up to γ_w; the
|
||||
same random stream for every φ to reduce the variance of differences). γ_w = 1/κ_w (gamma_acf) is computed once
|
||||
at phase φ0 so that all φ are compared at the same γ. Grid φ0 + step·k, |k| ≤ half_width; when the argmax lies on
|
||||
the boundary, one node is added on that side (at most max_extra times); finally refined by a parabola through
|
||||
the argmax and its two neighbours. Importance sampling from the particles of one phase to another is unusable:
|
||||
ℓ changes by ~8 nat/5° after tempering, so ESS ≈ 1. Ts may use any wavelet; run is the SMC function (smc_torch
|
||||
for GPU). Returns (φ̂ ∈ [−180, 180), info)."""
|
||||
gam = []
|
||||
for T0, Z0 in zip(Ts, Z0s):
|
||||
T = T0.with_wavelet(phase_wavelet(B, phase0))
|
||||
gam.append(gamma_acf(T, Z0, T.parts(Z0)[1]))
|
||||
lz = {}
|
||||
|
||||
def evaluate(phi: float) -> None:
|
||||
lz[phi] = np.array([run(T0.with_wavelet(phase_wavelet(B, phi)), Z0, [g],
|
||||
np.random.default_rng([*seed, i]), **smc_kw)["logZ"][g]
|
||||
for i, (T0, Z0, g) in enumerate(zip(Ts, Z0s, gam))])
|
||||
|
||||
for k in range(-half_width, half_width + 1):
|
||||
evaluate(float(phase0) + step * k)
|
||||
for _ in range(max_extra):
|
||||
phis = sorted(lz)
|
||||
j = int(np.argmax([lz[p].sum() for p in phis]))
|
||||
if 0 < j < len(phis) - 1:
|
||||
break
|
||||
evaluate(phis[j] + (step if j > 0 else -step))
|
||||
phis = np.array(sorted(lz))
|
||||
s = np.array([lz[p].sum() for p in phis])
|
||||
j = int(np.argmax(s))
|
||||
phi = phis[j]
|
||||
edge = not 0 < j < len(phis) - 1
|
||||
if not edge and s[j - 1] - 2 * s[j] + s[j + 1] < 0:
|
||||
phi += 0.5 * step * (s[j - 1] - s[j + 1]) / (s[j - 1] - 2 * s[j] + s[j + 1])
|
||||
info = {"gamma": gam, "phases": phis.tolist(), "logZ": [lz[p].tolist() for p in phis], "edge": edge}
|
||||
return float((phi + 180.0) % 360.0 - 180.0), info
|
||||
301
ml_porosity/registration/smc_torch.py
Normal file
301
ml_porosity/registration/smc_torch.py
Normal file
@@ -0,0 +1,301 @@
|
||||
"""The SMC warp posterior of smc.py on GPU (torch, float64).
|
||||
|
||||
Same algorithm and same random stream: all random numbers are still drawn from the numpy Generator in exactly the
|
||||
order of smc.py (γ and resampling stay on the CPU); synthetics, likelihood, particle π_γ, the Gaussian reference and
|
||||
the whole elliptical slice shrinkage loop run batched on the device, with no host synchronisation inside each
|
||||
shrinkage step (ess_moves). With the same seed, results match the CPU version up to rounding error, unless an
|
||||
accept/reject decision falls exactly within that error — the chain then diverges but keeps the same distribution.
|
||||
|
||||
Synthetic: piecewise-linear warp inversion by batched searchsorted, AI interpolation, reflectivity, then the 'same'
|
||||
convolution and interpolation to t_out are merged into one fixed (n_r, L) matrix per wavelet (conv_interp_matrix).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from ml_porosity.registration import smc
|
||||
from ml_porosity.registration.sampler import ess
|
||||
from ml_porosity.registration.smc import TiePosterior, next_gamma, systematic_resample
|
||||
|
||||
F64 = torch.float64
|
||||
|
||||
|
||||
def interp_weights(x: np.ndarray, xp: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""(j, w) with np.interp(x, xp, f) = (1 − w)·f[j] + w·f[j + 1]; clamped at both ends as in np.interp."""
|
||||
j = np.clip(np.searchsorted(xp, x, side="right") - 1, 0, len(xp) - 2)
|
||||
return j, np.clip((x - xp[j]) / (xp[j + 1] - xp[j]), 0.0, 1.0)
|
||||
|
||||
|
||||
def conv_interp_matrix(w_fine: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray) -> np.ndarray:
|
||||
"""M (n_r, L) with tie_likelihood.forward_fine(ai, t_fine, t_out, w_fine) = r(ai) @ M: scipy's 'same'
|
||||
convolution (the segment starting at (n_w − 1) // 2 of the full convolution), then interpolation from the
|
||||
midpoints to t_out."""
|
||||
n_r, n_w = len(t_fine) - 1, len(w_fine)
|
||||
j, w = interp_weights(t_out, 0.5 * (t_fine[1:] + t_fine[:-1]))
|
||||
i = np.arange(n_r)[:, None]
|
||||
|
||||
def col(jj):
|
||||
k = jj[None, :] + (n_w - 1) // 2 - i
|
||||
return np.where((k >= 0) & (k < n_w), w_fine[np.clip(k, 0, n_w - 1)], 0.0)
|
||||
|
||||
return (1.0 - w) * col(j) + w * col(j + 1)
|
||||
|
||||
|
||||
def interp_t(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
|
||||
"""Batched np.interp: x (P, n); xp (P, m) (each row increasing) or (m,); fp (m,)."""
|
||||
j = (torch.searchsorted(xp, x, right=True) - 1).clamp_(0, xp.shape[-1] - 2)
|
||||
x0, x1 = (xp[j], xp[j + 1]) if xp.dim() == 1 else (xp.gather(1, j), xp.gather(1, j + 1))
|
||||
w = ((x - x0) / (x1 - x0)).clamp_(0.0, 1.0)
|
||||
return fp[j] + w * (fp[j + 1] - fp[j])
|
||||
|
||||
|
||||
def profile_loglik_t(syn: torch.Tensor, seis: torch.Tensor) -> torch.Tensor:
|
||||
"""tie_likelihood.profile_loglik on tensors."""
|
||||
a = torch.clamp(syn @ seis / torch.clamp((syn**2).sum(1), min=1e-30), min=0.0)
|
||||
return -0.5 * len(seis) * torch.log(((seis - a[:, None] * syn) ** 2).sum(1))
|
||||
|
||||
|
||||
class TiePosteriorTorch:
|
||||
"""TiePosterior with synthetics, likelihood and π_γ computed in batches on `device`. The numpy methods (u, z,
|
||||
synth, loglik, parts, reference, with_wavelet, n_eval, seis) keep the TiePosterior interface so that
|
||||
smc.gamma_acf, smc.smc_fit_phase and scripts/14 can be shared; the *_t versions take/return device tensors."""
|
||||
|
||||
def __init__(self, T: TiePosterior, device):
|
||||
self.cpu, self.device = T, torch.device(device)
|
||||
if self.device.type == "cuda":
|
||||
torch.cuda.set_device(self.device) # implicit-device operations also go to the right GPU
|
||||
f = self.tensor
|
||||
self.mu, self.Lc, self.Pk, self.A, self.off, self.d_k = map(f, (T.mu, T.Lc, T.P, T.A, T.off, T.d_k))
|
||||
self.tau_g, self.QT, self.tau_fine, self.ai_log = map(f, (T.tau_g, T.QT, T.tau_fine, T.ai_log))
|
||||
self.seis_t = f(T.seis)
|
||||
self._set_wavelet()
|
||||
self._cnt = torch.zeros((), dtype=torch.int64, device=self.device)
|
||||
|
||||
def tensor(self, x) -> torch.Tensor:
|
||||
return torch.as_tensor(np.asarray(x, dtype=float), dtype=F64, device=self.device)
|
||||
|
||||
def _set_wavelet(self) -> None:
|
||||
self.t_crop = self.tensor(self.cpu.t_crop)
|
||||
self.M = self.tensor(conv_interp_matrix(self.cpu.w_fine, self.cpu.t_crop, self.cpu.t_out))
|
||||
|
||||
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosteriorTorch":
|
||||
T = copy.copy(self)
|
||||
T.cpu = self.cpu.with_wavelet(w_fine)
|
||||
T._set_wavelet()
|
||||
T._cnt = torch.zeros_like(self._cnt)
|
||||
return T
|
||||
|
||||
@property
|
||||
def seis(self) -> np.ndarray:
|
||||
return self.cpu.seis
|
||||
|
||||
@property
|
||||
def w_fine(self) -> np.ndarray:
|
||||
return self.cpu.w_fine
|
||||
|
||||
@property
|
||||
def n_eval(self) -> int:
|
||||
"""Number of synthetics computed (as in TiePosterior: parts counts only valid particles)."""
|
||||
return int(self._cnt)
|
||||
|
||||
@n_eval.setter
|
||||
def n_eval(self, v: int) -> None:
|
||||
self._cnt.fill_(int(v))
|
||||
|
||||
def u_t(self, Z: torch.Tensor) -> torch.Tensor:
|
||||
return self.mu + Z @ self.Lc.T
|
||||
|
||||
def _synth_tg(self, tg: torch.Tensor) -> torch.Tensor:
|
||||
"""(P, L) from t at the warp-grid nodes (P, n_g)."""
|
||||
tau = interp_t(self.t_crop.expand(len(tg), -1).contiguous(), tg.contiguous(), self.tau_g)
|
||||
ai = interp_t(tau, self.tau_fine, self.ai_log)
|
||||
return ((ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])) @ self.M
|
||||
|
||||
def synth_t(self, U: torch.Tensor) -> torch.Tensor:
|
||||
self._cnt += len(U)
|
||||
return self._synth_tg(self.tau_g + U[:, :1] + torch.expm1(U[:, 1:]) @ self.QT)
|
||||
|
||||
def parts_t(self, Z: torch.Tensor, mask: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""TiePosterior.parts on tensors, without host synchronisation. Synthetics are computed for all rows and
|
||||
violating particles are then masked (cheaper than filtering on the GPU); `mask` (bool, optional) marks the rows
|
||||
actually needed — only these are counted in n_eval."""
|
||||
U = self.u_t(Z)
|
||||
g = U[:, 1:]
|
||||
eg = torch.expm1(g)
|
||||
exact = U[:, :1] + eg @ self.Pk.T
|
||||
lin = U @ self.A.T + self.off
|
||||
la = -0.5 * (((self.d_k - exact) ** 2).sum(1) - ((self.d_k - lin) ** 2).sum(1)) / self.cpu.s2a
|
||||
tg = self.tau_g + U[:, :1] + eg @ self.QT
|
||||
ok = g.abs().amax(1) <= self.cpu.g_max
|
||||
if self.cpu.cover is not None:
|
||||
ok &= (tg[:, 0] <= self.cpu.cover[0]) & (tg[:, -1] >= self.cpu.cover[1])
|
||||
self._cnt += (ok if mask is None else ok & mask).sum()
|
||||
ls = profile_loglik_t(self._synth_tg(tg), self.seis_t)
|
||||
return torch.where(ok, -0.5 * (Z**2).sum(1) + la, -np.inf), torch.where(ok, ls, -np.inf)
|
||||
|
||||
def reference_t(self, m: torch.Tensor, gamma: float, infl: float = 2.0, eps: float = 0.05):
|
||||
"""TiePosterior.reference on the device. Returns tensors (m, L)."""
|
||||
eye = torch.eye(len(m), dtype=F64, device=self.device)
|
||||
syn = self.synth_t(self.u_t(torch.cat([m[None], m + eps * eye])))
|
||||
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
|
||||
a = max(float(s0 @ self.seis_t) / max(float(s0 @ s0), 1e-30), 0.0)
|
||||
s2 = float(((self.seis_t - a * s0) ** 2).sum()) / len(self.seis_t)
|
||||
return m, torch.linalg.cholesky(eye + (gamma / infl) * a**2 * (J.T @ J) / s2)
|
||||
|
||||
def u(self, Z: np.ndarray) -> np.ndarray:
|
||||
return self.cpu.u(Z)
|
||||
|
||||
def z(self, U: np.ndarray) -> np.ndarray:
|
||||
return self.cpu.z(U)
|
||||
|
||||
def t_grid(self, U: np.ndarray) -> np.ndarray:
|
||||
return self.cpu.t_grid(U)
|
||||
|
||||
def synth(self, U: np.ndarray) -> np.ndarray:
|
||||
return self.synth_t(self.tensor(np.atleast_2d(U))).cpu().numpy()
|
||||
|
||||
def loglik(self, U: np.ndarray) -> np.ndarray:
|
||||
return profile_loglik_t(self.synth_t(self.tensor(np.atleast_2d(U))), self.seis_t).cpu().numpy()
|
||||
|
||||
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
b, ls = self.parts_t(self.tensor(np.atleast_2d(Z)))
|
||||
return b.cpu().numpy(), ls.cpu().numpy()
|
||||
|
||||
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
|
||||
return tuple(x.cpu().numpy() for x in self.reference_t(self.tensor(m), gamma, infl, eps))
|
||||
|
||||
|
||||
_LAST_GRAPH: dict = {}
|
||||
|
||||
|
||||
def cuda_graph(fn, device: torch.device):
|
||||
"""Capture fn() — no arguments, no host synchronisation, only in-place writes into pre-allocated tensors — as a
|
||||
CUDA graph; returns the replay function. fn is run once beforehand for warm-up (cuBLAS workspace, ...), so that
|
||||
run must be free of side effects.
|
||||
|
||||
All graphs on a device share one stream and the memory pool of the graph captured before them: the pool of a
|
||||
discarded graph is returned to the device only on empty_cache, so recapturing every SMC stage with a fresh pool
|
||||
would hold unbounded memory. The previous graph is kept until the new one has been captured (the shared pool must
|
||||
still have a user, on the host side too) and is never replayed again — sharing a pool is safe only when at most
|
||||
one graph is still replayed at any time; ess_moves drops its graph when done. capture_begin is called directly
|
||||
instead of torch.cuda.graph, which empties the memory cache on every capture."""
|
||||
side, prev = _LAST_GRAPH.get(device) or (torch.cuda.Stream(device), None)
|
||||
side.wait_stream(torch.cuda.current_stream(device))
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.stream(side):
|
||||
fn()
|
||||
graph.capture_begin(pool=None if prev is None else prev.pool(), capture_error_mode="thread_local")
|
||||
try:
|
||||
fn()
|
||||
finally:
|
||||
graph.capture_end()
|
||||
torch.cuda.current_stream(device).wait_stream(side)
|
||||
_LAST_GRAPH[device] = side, graph
|
||||
return graph.replay
|
||||
|
||||
|
||||
def ess_moves(T: TiePosteriorTorch, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60,
|
||||
check_every: int = 4):
|
||||
"""smc.ess_moves with Z, base, ll, ref as device tensors, without host synchronisation in the shrinkage loop.
|
||||
|
||||
Each shrinkage step evaluates all P particles and masks those already accepted (on the GPU one call costs almost
|
||||
the same regardless of P), writing in place into fixed state, so on CUDA the whole step is captured as one graph.
|
||||
Random numbers are still drawn on the CPU in exactly the order of the numpy version: ξ, u, initial angle, then
|
||||
the shrinkages — uniform(lo, hi) = lo + (hi − lo)·U with U the next number in the stream, so a pool of U(0, 1) is
|
||||
drawn in advance, the particles rejected at each step take numbers in index order, and the Generator is then
|
||||
reset and advanced by exactly the number used. The host reads the device only every `check_every` steps to check
|
||||
whether any particle remains unaccepted."""
|
||||
m, L = ref
|
||||
dev = Z.device
|
||||
logq = lambda X: -0.5 * (((X - m) @ L) ** 2).sum(1)
|
||||
comb = lambda b, l: torch.where(torch.isfinite(b), b + gamma * l, -np.inf)
|
||||
Z, base, ll = Z.clone(), base.clone(), ll.clone()
|
||||
Lq = comb(base, ll) - logq(Z)
|
||||
P, d = Z.shape
|
||||
nu = torch.zeros_like(Z)
|
||||
log_y, th, lo, hi = (torch.zeros_like(ll) for _ in range(4))
|
||||
pool = torch.zeros(P * max_iter, dtype=F64, device=dev)
|
||||
act = torch.zeros(P, dtype=torch.bool, device=dev)
|
||||
used = torch.zeros((), dtype=torch.int64, device=dev)
|
||||
|
||||
def step(): # act all False: no change
|
||||
zp = m + (Z - m) * torch.cos(th)[:, None] + (nu - m) * torch.sin(th)[:, None]
|
||||
b, l = T.parts_t(zp, act)
|
||||
lq = comb(b, l) - logq(zp)
|
||||
up = lq > log_y
|
||||
acc, rej = act & up, act & ~up
|
||||
Z.copy_(torch.where(acc[:, None], zp, Z))
|
||||
for x, y in ((base, b), (ll, l), (Lq, lq)):
|
||||
x.copy_(torch.where(acc, y, x))
|
||||
neg = th < 0
|
||||
lo.copy_(torch.where(rej & neg, th, lo))
|
||||
hi.copy_(torch.where(rej & ~neg, th, hi))
|
||||
u = pool[(used + rej.cumsum(0) - 1).clamp_(0, len(pool) - 1)]
|
||||
th.copy_(torch.where(rej, lo + (hi - lo) * u, th))
|
||||
used.add_(rej.sum())
|
||||
act.copy_(rej)
|
||||
|
||||
cuda = dev.type == "cuda"
|
||||
run = cuda_graph(step, dev) if cuda else step
|
||||
shrink = 0
|
||||
for _ in range(n_moves):
|
||||
head = [rng.standard_normal(P * d), np.log(rng.uniform(size=P)), rng.uniform(0.0, 2 * np.pi, P)]
|
||||
state = rng.bit_generator.state
|
||||
buf = torch.from_numpy(np.concatenate(head + [rng.random(P * max_iter)]))
|
||||
buf = (buf.pin_memory() if cuda else buf).to(dev, non_blocking=True)
|
||||
xi, log_u, th0, pool0 = torch.split(buf, [P * d, P, P, P * max_iter])
|
||||
nu.copy_(m + torch.linalg.solve_triangular(L.T, xi.view(P, d).T, upper=True).T)
|
||||
log_y.copy_(Lq + log_u)
|
||||
for x, y in ((th, th0), (lo, th0 - 2 * np.pi), (hi, th0), (pool, pool0)):
|
||||
x.copy_(y)
|
||||
act.fill_(True)
|
||||
used.zero_()
|
||||
for it in range(1, max_iter + 1):
|
||||
run()
|
||||
if it % check_every == 0 or it == max_iter:
|
||||
n_act, n_used = torch.stack([act.sum(), used]).tolist()
|
||||
if n_act == 0:
|
||||
break
|
||||
rng.bit_generator.state = state
|
||||
rng.random(n_used)
|
||||
shrink += n_used
|
||||
return Z, base, ll, shrink / (P * n_moves)
|
||||
|
||||
|
||||
def smc_tie_posterior(T: TiePosteriorTorch, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
|
||||
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
|
||||
"""smc.smc_tie_posterior on the device; numpy in/out as in the CPU version."""
|
||||
Z = T.tensor(np.atleast_2d(Z0))
|
||||
base, ll = T.parts_t(Z)
|
||||
if not bool(torch.isfinite(base).all()):
|
||||
raise ValueError("initial samples violate the constraints")
|
||||
g, logZ = 0.0, 0.0
|
||||
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
|
||||
for gk in sorted(set(float(x) for x in checkpoints)):
|
||||
while g < gk:
|
||||
ll_np = ll.cpu().numpy()
|
||||
g_new = next_gamma(ll_np, g, gk, min_frac)
|
||||
logw = (g_new - g) * ll_np
|
||||
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
|
||||
idx = systematic_resample(logw, rng)
|
||||
idx_t = torch.from_numpy(idx).to(Z.device)
|
||||
Z, base, ll = Z[idx_t], base[idx_t], ll[idx_t]
|
||||
Zb = Z.clone()
|
||||
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference_t(Z.mean(0), g_new, infl), n_moves, rng)
|
||||
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
|
||||
"shrink": sh, "jump_z": float(torch.sqrt(torch.mean((Z - Zb) ** 2)))})
|
||||
g = g_new
|
||||
if len(out["stages"]) >= max_stages:
|
||||
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
|
||||
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.cpu().numpy(), ll.cpu().numpy(), logZ
|
||||
return out
|
||||
|
||||
|
||||
def smc_fit_phase(Ts: list[TiePosteriorTorch], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
|
||||
**kw) -> tuple[float, dict]:
|
||||
"""smc.smc_fit_phase with the SMC run on the device."""
|
||||
return smc.smc_fit_phase(Ts, Z0s, B, phase0, seed, run=smc_tie_posterior, **kw)
|
||||
66
ml_porosity/registration/tie_likelihood.py
Normal file
66
ml_porosity/registration/tie_likelihood.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""Physical well-tie likelihood (plan §4.2): p(s | g) = N(s; α W r(g), σ_n² I).
|
||||
|
||||
Forward model shared by the D2 generator and the M2 weights: AI on a fine time axis → reflectivity at the
|
||||
sample midpoints → convolution with the fine wavelet → interpolation to the 4 ms sample times. α and σ_n² are
|
||||
profiled out: log p = −(n/2)·log RSS(α̂). Weights π_s ∝ p_s^γ with γ chosen by sampler.temper (ESS ≥ S/4).
|
||||
Constant wavelet phase: maximum marginal likelihood over the posterior warp samples (fit_phase).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
from ml_porosity.data.wavelet import rotate_phase
|
||||
|
||||
|
||||
def fine_wavelet(w: np.ndarray, factor: int) -> np.ndarray:
|
||||
"""Band-limited interpolation of the wavelet (odd length, centred) onto a grid `factor` times finer; keeps the
|
||||
centre."""
|
||||
wf = signal.resample_poly(w, factor, 1)
|
||||
n = len(w) // 2
|
||||
return wf[: 2 * n * factor + 1]
|
||||
|
||||
|
||||
def forward_fine(ai: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray) -> np.ndarray:
|
||||
"""Synthetic seismic at t_out from AI on the uniform fine time grid t_fine. ai (..., nf) → (..., L)."""
|
||||
ai = np.atleast_2d(ai)
|
||||
r = (ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])
|
||||
s = signal.fftconvolve(r, w_fine[None, :], mode="same", axes=1)
|
||||
tm = 0.5 * (t_fine[1:] + t_fine[:-1])
|
||||
return np.stack([np.interp(t_out, tm, si) for si in s])
|
||||
|
||||
|
||||
def synth_for_warps(tau_fine: np.ndarray, ai_log: np.ndarray, t_of_tau_fine: np.ndarray,
|
||||
t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray) -> np.ndarray:
|
||||
"""(S, L): synthetic for each warp. The AI log (τ axis) is mapped to the t axis by each warp sample."""
|
||||
t_of_tau_fine = np.atleast_2d(t_of_tau_fine)
|
||||
ai_t = np.stack([np.interp(t_fine, ts, ai_log) for ts in t_of_tau_fine])
|
||||
return forward_fine(ai_t, t_fine, t_out, w_fine)
|
||||
|
||||
|
||||
def profile_loglik(syn: np.ndarray, seis: np.ndarray) -> np.ndarray:
|
||||
"""log p_s = −(n/2)·log RSS_s after profiling out α_s ≥ 0 (constrained least squares; synthetic and seismic
|
||||
follow the same polarity convention, so phases φ and φ + 180° no longer give the same likelihood) and σ_n²."""
|
||||
syn = np.atleast_2d(syn)
|
||||
a = np.maximum(syn @ seis / np.maximum(np.sum(syn**2, 1), 1e-30), 0.0)
|
||||
rss = np.sum((seis[None, :] - a[:, None] * syn) ** 2, 1)
|
||||
return -0.5 * len(seis) * np.log(rss)
|
||||
|
||||
|
||||
def phase_loglik(syn0: np.ndarray, seis: np.ndarray, phases=np.arange(-180, 180, 15)) -> np.ndarray:
|
||||
"""(P, S): log p_s for each constant phase. syn0 (S, L) is the synthetic with the zero-phase wavelet; phase
|
||||
rotation commutes with convolution, so only the synthetic needs to be rotated."""
|
||||
return np.stack([profile_loglik(rotate_phase(np.atleast_2d(syn0), p), seis) for p in phases])
|
||||
|
||||
|
||||
def fit_phase(ll_list: list[np.ndarray], valid_list: list[np.ndarray], phases=np.arange(-180, 180, 15)) -> int:
|
||||
"""Phase maximising the marginal likelihood Σ_w log mean_s p(s_w | g_ws, φ) over the (anchor) posterior warp
|
||||
samples of each training well; ll_list[w] (P, S) from phase_loglik. Returns the phase index in `phases`.
|
||||
|
||||
Correlation against a single point tie is unusable: a tie error of a few ms already reduces ncc to ~0.1 and
|
||||
the estimated phase is almost random."""
|
||||
from scipy.special import logsumexp
|
||||
|
||||
score = sum(logsumexp(ll[:, ok], axis=1) - np.log(ok.sum()) for ll, ok in zip(ll_list, valid_list))
|
||||
return int(np.argmax(score))
|
||||
93
ml_porosity/registration/ties.py
Normal file
93
ml_porosity/registration/ties.py
Normal file
@@ -0,0 +1,93 @@
|
||||
"""Point ties for B3a–d on D2 (plan §5.3) and warp-error diagnostics.
|
||||
|
||||
Every tie returns t(τ) on the fine τ grid (strictly increasing), so that `labels_for_warps` can be shared:
|
||||
|
||||
- B3a: single-point tie at the shallowest anchor, t = τ + (t_0 − τ_0) — analogous to the thesis's "integrated DT
|
||||
hung at the first marker" (no drift correction).
|
||||
- B3b: marker-calibrated sonic (tdr.calibrate_to_anchors) after removing anchors that break monotonicity.
|
||||
- B3c: B3b + local shifts from synthetic–seismic correlation (synthetic.local_shifts), as in a manual tie.
|
||||
- B3d: M2-weighted mean warp, Σ_s π_s t_s(τ) (the plan states MAP; the mean is more stable than the MAP over a
|
||||
finite importance sample — recorded as a deviation in protocol_p2).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.data.synthetic import local_shifts
|
||||
from ml_porosity.data.tdr import TDR, calibrate_to_anchors
|
||||
from ml_porosity.registration.labels import invert_warps
|
||||
|
||||
|
||||
def clean_monotone(tau_k, t_k) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Longest strictly increasing subsequence of (τ_k, t_k) sorted by τ (pick noise can make t non-monotone)."""
|
||||
o = np.argsort(tau_k)
|
||||
tau, t = np.asarray(tau_k, float)[o], np.asarray(t_k, float)[o]
|
||||
n = len(t)
|
||||
if n == 0:
|
||||
return tau, t
|
||||
best, prev = np.ones(n, int), np.full(n, -1)
|
||||
for i in range(n):
|
||||
for j in range(i):
|
||||
if t[j] < t[i] and tau[j] < tau[i] and best[j] + 1 > best[i]:
|
||||
best[i], prev[i] = best[j] + 1, j
|
||||
k, keep = int(np.argmax(best)), []
|
||||
while k >= 0:
|
||||
keep.append(k)
|
||||
k = prev[k]
|
||||
keep = keep[::-1]
|
||||
return tau[keep], t[keep]
|
||||
|
||||
|
||||
def tie_b3a(tau_k, t_k, tau: np.ndarray) -> np.ndarray:
|
||||
k = int(np.argmin(tau_k))
|
||||
return tau + (t_k[k] - tau_k[k])
|
||||
|
||||
|
||||
def tie_b3b(tau_k, t_k, tau: np.ndarray) -> np.ndarray:
|
||||
tk, ttk = clean_monotone(tau_k, t_k)
|
||||
if len(tk) < 2:
|
||||
return tie_b3a(tk, ttk, tau) if len(tk) else tau.copy()
|
||||
return calibrate_to_anchors(TDR(tau, tau, "sonic"), tk, ttk).time_at(tau)
|
||||
|
||||
|
||||
def tie_b3c(t_b3b: np.ndarray, tau: np.ndarray, syn: np.ndarray, seis: np.ndarray, t_out: np.ndarray,
|
||||
dt_ms: float = 4.0, r_min: float = 0.3, smooth: int = 3, **kw) -> np.ndarray:
|
||||
"""syn: synthetic under the B3b tie on t_out; seis: centre trace on t_out. Shifts s(t) (positive = synthetic
|
||||
must be later) from windows with r ≥ r_min, smoothed by a moving average over `smooth` windows, then
|
||||
t(τ) = t_B3b(τ) + s(t_B3b(τ)); strict monotonicity is enforced (dt/dτ ≥ 0.05)."""
|
||||
c, s, r = local_shifts(syn, seis, dt_ms, **kw)
|
||||
ok = r >= r_min
|
||||
if ok.sum() == 0:
|
||||
return t_b3b.copy()
|
||||
tc, sc = t_out[c[ok]], s[ok]
|
||||
if smooth > 1 and len(sc) >= smooth:
|
||||
sc = np.convolve(np.pad(sc, smooth // 2, mode="edge"), np.ones(smooth) / smooth, "valid")
|
||||
t = t_b3b + np.interp(t_b3b, tc, sc)
|
||||
return np.maximum.accumulate(t - 0.05 * tau) + 0.05 * tau
|
||||
|
||||
|
||||
def warp_mean(t_of_tau: np.ndarray, logw: np.ndarray) -> np.ndarray:
|
||||
w = np.exp(logw - np.max(logw))
|
||||
return (w / w.sum()) @ np.atleast_2d(t_of_tau)
|
||||
|
||||
|
||||
def warp_errors(t_of_tau: np.ndarray, tau: np.ndarray, t_true_of_tau: np.ndarray, t_eval: np.ndarray,
|
||||
logw: np.ndarray | None = None) -> dict:
|
||||
"""Warp error in τ(t) on t_eval (ms). One warp: RMSE. Several warps: RMSE of the weighted mean,
|
||||
90% coverage (weighted 5–95% quantiles) and mean interval width."""
|
||||
tau_true = invert_warps(t_true_of_tau, tau, t_eval)[0]
|
||||
T = invert_warps(t_of_tau, tau, t_eval)
|
||||
if len(T) == 1:
|
||||
return {"warp_rmse_ms": float(np.sqrt(np.nanmean((T[0] - tau_true) ** 2)))}
|
||||
w = np.ones(len(T)) if logw is None else np.exp(logw - np.max(logw))
|
||||
w = w / w.sum()
|
||||
mean = w @ T
|
||||
o = np.argsort(T, 0)
|
||||
cw = np.cumsum(w[o], 0)
|
||||
Ts = np.take_along_axis(T, o, 0)
|
||||
lo = Ts[np.argmax(cw >= 0.05, 0), np.arange(T.shape[1])]
|
||||
hi = Ts[np.argmax(cw >= 0.95, 0), np.arange(T.shape[1])]
|
||||
return {"warp_rmse_ms": float(np.sqrt(np.mean((mean - tau_true) ** 2))),
|
||||
"warp_cov90": float(np.mean((tau_true >= lo) & (tau_true <= hi))),
|
||||
"warp_width90_ms": float(np.mean(hi - lo))}
|
||||
243
ml_porosity/registration/warp_prior.py
Normal file
243
ml_porosity/registration/warp_prior.py
Normal file
@@ -0,0 +1,243 @@
|
||||
"""GP log-slowness warp prior conditioned on anchors (plan §4.1).
|
||||
|
||||
The reference axis τ is sonic time (integrated DT, ms) and t is seismic time (ms):
|
||||
|
||||
t(τ) = τ + b + ∫_{τ0}^{τ} (e^{g(τ')} − 1) dτ', g ~ GP(m_g, k_{σ_g, ℓ}), b ~ N(0, σ_b²)
|
||||
|
||||
Anchors (markers with TWT): t_k = t(τ_k) + ε_k, ε_k ~ N(0, σ_a²). Writing dt/dτ = e^g is equivalent to the
|
||||
depth form in the plan (dt/dz = 2·DT·e^g) since dτ/dz = 2·DT. g is defined on a uniform τ grid; the integral is
|
||||
the trapezoid rule on that grid (the same quadrature for the linearised version e^g − 1 ≈ g and the exact one),
|
||||
so the difference between the two comes only from the nonlinearity of e^g.
|
||||
|
||||
Latent vector u = [b, g_1..g_n]. The linearised Gaussian posterior serves as the proposal for elliptical slice
|
||||
sampling (sampler.py). Hyperparameters (m_g, σ_g, ℓ, σ_b, σ_a) are fitted by type-II maximum likelihood on the
|
||||
anchors of the training wells (empirical Bayes).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy import optimize
|
||||
from scipy.linalg import cho_factor, cho_solve
|
||||
|
||||
|
||||
@dataclass
|
||||
class WarpHyper:
|
||||
m_g: float = 0.0
|
||||
sigma_g: float = 0.03
|
||||
ell_ms: float = 200.0
|
||||
sigma_b_ms: float = 30.0
|
||||
sigma_a_ms: float = 4.0
|
||||
kernel: str = "matern32"
|
||||
|
||||
def scaled(self, c: float) -> WarpHyper:
|
||||
"""Drift scaled by a factor c (used for the ×c drift grid of D2): g → c·g, b → c·b."""
|
||||
return WarpHyper(c * self.m_g, c * self.sigma_g, self.ell_ms, c * self.sigma_b_ms, self.sigma_a_ms, self.kernel)
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def kernel_matrix(x: np.ndarray, y: np.ndarray, sigma: float, ell: float, kind: str = "matern32") -> np.ndarray:
|
||||
r = np.abs(np.asarray(x)[:, None] - np.asarray(y)[None, :]) / ell
|
||||
if kind == "matern32":
|
||||
a = np.sqrt(3.0) * r
|
||||
return sigma**2 * (1.0 + a) * np.exp(-a)
|
||||
if kind == "se":
|
||||
return sigma**2 * np.exp(-0.5 * r**2)
|
||||
raise ValueError(kind)
|
||||
|
||||
|
||||
def cumtrapz_matrix(n: int, dx: float) -> np.ndarray:
|
||||
"""Q with (Q f)_i = ∫_{x_0}^{x_i} f by the trapezoid rule on a uniform grid."""
|
||||
Q = np.zeros((n, n))
|
||||
for i in range(1, n):
|
||||
Q[i, :i + 1] = dx
|
||||
Q[i, 0] = Q[i, i] = dx / 2
|
||||
return Q
|
||||
|
||||
|
||||
def interp_matrix(x: np.ndarray, grid: np.ndarray) -> np.ndarray:
|
||||
"""P with P f = linear interpolation of f (on grid) at x. x must lie within grid."""
|
||||
x = np.asarray(x, dtype=float)
|
||||
P = np.zeros((len(x), len(grid)))
|
||||
j = np.clip(np.searchsorted(grid, x) - 1, 0, len(grid) - 2)
|
||||
w = (x - grid[j]) / (grid[j + 1] - grid[j])
|
||||
P[np.arange(len(x)), j] = 1 - w
|
||||
P[np.arange(len(x)), j + 1] = w
|
||||
return P
|
||||
|
||||
|
||||
class WarpGrid:
|
||||
"""τ grid of one well and the associated linear operators."""
|
||||
|
||||
def __init__(self, tau0: float, tau1: float, dtau: float = 4.0):
|
||||
n = int(np.ceil((tau1 - tau0) / dtau)) + 1
|
||||
self.tau = tau0 + dtau * np.arange(n)
|
||||
self.dtau = dtau
|
||||
self.Q = cumtrapz_matrix(n, dtau)
|
||||
|
||||
@property
|
||||
def n(self) -> int:
|
||||
return len(self.tau)
|
||||
|
||||
def t_of_tau(self, b, g, tau=None) -> np.ndarray:
|
||||
"""t(τ) for samples (b, g); b scalar or (S,), g (n,) or (S, n). Returns (S, ·) on the grid or
|
||||
at tau (linear interpolation; tau must lie within the grid)."""
|
||||
g = np.atleast_2d(g)
|
||||
t = self.tau[None, :] + np.reshape(b, (-1, 1)) + np.expm1(g) @ self.Q.T
|
||||
if tau is not None:
|
||||
t = t @ interp_matrix(tau, self.tau).T
|
||||
return t
|
||||
|
||||
def anchor_operator(self, tau_k: np.ndarray) -> np.ndarray:
|
||||
"""A with t(τ_k) − τ_k ≈ A u (linearised), u = [b, g]."""
|
||||
C = interp_matrix(tau_k, self.tau) @ self.Q
|
||||
return np.hstack([np.ones((len(tau_k), 1)), C])
|
||||
|
||||
|
||||
def prior_moments(grid: WarpGrid, h: WarpHyper) -> tuple[np.ndarray, np.ndarray]:
|
||||
mu = np.concatenate([[0.0], np.full(grid.n, h.m_g)])
|
||||
S = np.zeros((grid.n + 1, grid.n + 1))
|
||||
S[0, 0] = h.sigma_b_ms**2
|
||||
S[1:, 1:] = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
|
||||
S[1:, 1:] += 1e-10 * np.eye(grid.n)
|
||||
return mu, S
|
||||
|
||||
|
||||
def linearize(grid: WarpGrid, tau_k: np.ndarray, g0: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""t(τ_k) − τ_k ≈ A u + off, linearising e^g − 1 at g0. g0 = 0 gives A = anchor_operator, off = 0."""
|
||||
C = interp_matrix(tau_k, grid.tau) @ grid.Q
|
||||
e = np.exp(g0)
|
||||
return np.hstack([np.ones((len(tau_k), 1)), C * e[None, :]]), C @ (e - 1.0 - e * g0)
|
||||
|
||||
|
||||
def linear_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, g0=None) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Gaussian posterior of u = [b, g] given d_k = t_k − τ_k ≈ A u + off + ε (linearised at g0,
|
||||
default 0). Without anchors: returns the prior."""
|
||||
mu, S = prior_moments(grid, h)
|
||||
tau_k = np.asarray(tau_k, dtype=float)
|
||||
if tau_k.size == 0:
|
||||
return mu, S
|
||||
A, off = linearize(grid, tau_k, np.zeros(grid.n) if g0 is None else g0)
|
||||
SA = S @ A.T
|
||||
G = A @ SA + h.sigma_a_ms**2 * np.eye(len(tau_k))
|
||||
cf = cho_factor(G)
|
||||
mu_p = mu + SA @ cho_solve(cf, np.asarray(d_k) - off - A @ mu)
|
||||
S_p = S - SA @ cho_solve(cf, SA.T)
|
||||
return mu_p, 0.5 * (S_p + S_p.T)
|
||||
|
||||
|
||||
def laplace_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, n_iter: int = 8, tol: float = 1e-7):
|
||||
"""Gauss–Newton: iterated linearisation at the posterior mean; converges to the MAP of the exact posterior
|
||||
(ignoring the g_max constraint). Returns (mu, S, A, off) with A, off the linearisation at mu."""
|
||||
g0 = np.full(grid.n, h.m_g)
|
||||
mu, S = linear_posterior(grid, h, tau_k, d_k, g0)
|
||||
for _ in range(n_iter):
|
||||
if np.max(np.abs(mu[1:] - g0)) < tol:
|
||||
break
|
||||
g0 = mu[1:].copy()
|
||||
mu, S = linear_posterior(grid, h, tau_k, d_k, g0)
|
||||
A, off = linearize(grid, np.asarray(tau_k, dtype=float), g0)
|
||||
return mu, S, A, off
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- type-II maximum likelihood
|
||||
|
||||
|
||||
def _marginal_cov(C: np.ndarray, Kgg: np.ndarray, h: WarpHyper) -> np.ndarray:
|
||||
n = C.shape[0]
|
||||
return h.sigma_b_ms**2 * np.ones((n, n)) + C @ Kgg @ C.T + h.sigma_a_ms**2 * np.eye(n)
|
||||
|
||||
|
||||
def log_marginal(wells: list[dict], h: WarpHyper) -> float:
|
||||
"""Σ_w log N(d_w; C_w m_g 1, σ_b² 11ᵀ + C_w K C_wᵀ + σ_a² I). wells[i] = {"grid", "tau_k", "d_k"}."""
|
||||
total = 0.0
|
||||
for w in wells:
|
||||
grid: WarpGrid = w["grid"]
|
||||
C = interp_matrix(w["tau_k"], grid.tau) @ grid.Q
|
||||
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
|
||||
V = _marginal_cov(C, K, h)
|
||||
r = np.asarray(w["d_k"]) - h.m_g * C.sum(1)
|
||||
try:
|
||||
cf = cho_factor(V)
|
||||
except np.linalg.LinAlgError:
|
||||
return -np.inf
|
||||
total += -0.5 * r @ cho_solve(cf, r) - np.log(np.diag(cf[0])).sum() - 0.5 * len(r) * np.log(2 * np.pi)
|
||||
return float(total)
|
||||
|
||||
|
||||
_FREE = ("m_g", "sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms")
|
||||
_LOG = {"sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms"}
|
||||
|
||||
|
||||
def fit_hyper(
|
||||
wells: list[dict],
|
||||
init: WarpHyper | None = None,
|
||||
fixed: dict | None = None,
|
||||
bounds: dict | None = None,
|
||||
hyperprior: dict | None = None,
|
||||
n_starts: int = 8,
|
||||
seed: int = 0,
|
||||
) -> tuple[WarpHyper, dict]:
|
||||
"""Type-II ML (or MAP-II if a hyperprior is given) for the hyperparameters that are not fixed.
|
||||
|
||||
hyperprior[name] = (mean, sd) of the parameter on the log scale (σ, ℓ) or the original scale (m_g).
|
||||
Returns (best hyperparameters, info containing the log-marginal and the starting points)."""
|
||||
init = init or WarpHyper()
|
||||
fixed = fixed or {}
|
||||
hyperprior = hyperprior or {}
|
||||
bnd = {"m_g": (-0.2, 0.2), "sigma_g": (1e-4, 0.3), "ell_ms": (10.0, 3000.0),
|
||||
"sigma_b_ms": (0.5, 200.0), "sigma_a_ms": (0.2, 50.0)} | (bounds or {})
|
||||
free = [k for k in _FREE if k not in fixed]
|
||||
to_x = lambda k, v: np.log(v) if k in _LOG else v
|
||||
from_x = lambda k, x: float(np.exp(x)) if k in _LOG else float(x)
|
||||
lo = np.array([to_x(k, bnd[k][0]) for k in free])
|
||||
hi = np.array([to_x(k, bnd[k][1]) for k in free])
|
||||
|
||||
def make(x):
|
||||
vals = asdict(init) | fixed | {k: from_x(k, xi) for k, xi in zip(free, x)}
|
||||
return WarpHyper(**vals)
|
||||
|
||||
def obj(x):
|
||||
h = make(x)
|
||||
lp = log_marginal(wells, h)
|
||||
for k, xi in zip(free, x):
|
||||
if k in hyperprior:
|
||||
m, s = hyperprior[k]
|
||||
lp += -0.5 * ((xi - m) / s) ** 2
|
||||
return -lp if np.isfinite(lp) else 1e12
|
||||
|
||||
rng = np.random.default_rng(seed)
|
||||
x0s = [np.clip([to_x(k, getattr(init, k)) for k in free], lo, hi)]
|
||||
x0s += [lo + (hi - lo) * rng.uniform(0.15, 0.85, len(free)) for _ in range(n_starts - 1)]
|
||||
best, starts = None, []
|
||||
for x0 in x0s:
|
||||
res = optimize.minimize(obj, x0, method="L-BFGS-B", bounds=list(zip(lo, hi)))
|
||||
starts.append(float(-res.fun))
|
||||
if best is None or res.fun < best.fun:
|
||||
best = res
|
||||
h = make(best.x)
|
||||
return h, {"log_marginal": log_marginal(wells, h), "objective": float(-best.fun), "starts": starts,
|
||||
"free": free, "at_bound": [k for k, xi, a, b in zip(free, best.x, lo, hi) if min(xi - a, b - xi) < 1e-3]}
|
||||
|
||||
|
||||
def loao_zscores(wells: list[dict], h: WarpHyper) -> list[np.ndarray]:
|
||||
"""Leave-one-anchor-out: z-score of d_k under the (linearised) posterior prediction from the remaining
|
||||
anchors of the same well (plan §5.4). Returns a list of z arrays, one per well."""
|
||||
out = []
|
||||
for w in wells:
|
||||
grid: WarpGrid = w["grid"]
|
||||
tk, dk = np.asarray(w["tau_k"]), np.asarray(w["d_k"])
|
||||
A = grid.anchor_operator(tk)
|
||||
z = np.empty(len(tk))
|
||||
for k in range(len(tk)):
|
||||
keep = np.arange(len(tk)) != k
|
||||
mu, S = linear_posterior(grid, h, tk[keep], dk[keep])
|
||||
m = A[k] @ mu
|
||||
v = A[k] @ S @ A[k] + h.sigma_a_ms**2
|
||||
z[k] = (dk[k] - m) / np.sqrt(v)
|
||||
out.append(z)
|
||||
return out
|
||||
358
ml_porosity/runlog.py
Normal file
358
ml_porosity/runlog.py
Normal file
@@ -0,0 +1,358 @@
|
||||
"""Log and runtime recording for every run.
|
||||
|
||||
python -m ml_porosity.runlog [-n NAME] [--note "..."] [--] <command> [args...]
|
||||
python -m ml_porosity.runlog ls [-k 30] # most recent runs + runs in progress
|
||||
python -m ml_porosity.runlog reindex # rebuild logs/index.csv from the meta.json files
|
||||
|
||||
Each run creates `logs/runs/<YYYYmmdd-HHMMSS>_<name>/` (root overridable via ML_POROSITY_LOGS):
|
||||
log.txt merged stdout + stderr, including child workers (ProcessPool); each line carries the elapsed time [h:mm:ss]
|
||||
meta.json command, cwd, git commit + dirty state + source hash, thread/GPU variables, device, start/end,
|
||||
wall/CPU time, peak RSS, peak VRAM of the process tree, exit code; written at start with status=running
|
||||
and appends one row to `logs/index.csv`. A `.py` file at the head of the command is run with the current python.
|
||||
For nested calls (RUNLOG_DIR already set, e.g. the individual steps of scripts/run_p2.sh), the child step is placed
|
||||
inside the parent run's directory, and the `parent` column of the index points to the parent run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import resource
|
||||
import shlex
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .paths import REPO_ROOT
|
||||
|
||||
FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall",
|
||||
"device", "git", "dirty", "code_sha", "source", "cmd"]
|
||||
ENV_KEYS = ["CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS",
|
||||
"PYTHONHASHSEED", "DEVICE", "WORKERS", "ML_POROSITY_OUTPUTS"]
|
||||
CODE_DIRS = ["ml_porosity", "scripts", "configs", "tests"]
|
||||
GPU_POLL_S = 15.0
|
||||
|
||||
|
||||
def logs_dir() -> Path:
|
||||
env = os.environ.get("ML_POROSITY_LOGS")
|
||||
return Path(env) if env else REPO_ROOT / "logs"
|
||||
|
||||
|
||||
def now() -> dt.datetime:
|
||||
return dt.datetime.now().astimezone()
|
||||
|
||||
|
||||
def fmt_wall(s: float | None) -> str:
|
||||
if s is None:
|
||||
return ""
|
||||
h, r = divmod(int(round(s)), 3600)
|
||||
return f"{h}:{r // 60:02d}:{r % 60:02d}"
|
||||
|
||||
|
||||
def _out(cmd: list[str]) -> str:
|
||||
try:
|
||||
return subprocess.run(cmd, capture_output=True, text=True, timeout=20, cwd=REPO_ROOT).stdout.strip()
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return ""
|
||||
|
||||
|
||||
def git_state() -> dict:
|
||||
"""Commit + working-tree state. Since uncommitted code may also be run, a content hash of the files in
|
||||
CODE_DIRS (tracked + untracked, excluding ignored files) is recorded to identify the exact code version run."""
|
||||
st = _out(["git", "status", "--porcelain"]).splitlines()
|
||||
files = sorted(_out(["git", "ls-files", "-co", "--exclude-standard", *CODE_DIRS]).splitlines())
|
||||
h = hashlib.sha256()
|
||||
for f in files:
|
||||
p = REPO_ROOT / f
|
||||
if p.is_file():
|
||||
h.update(f.encode() + b"\0" + p.read_bytes() + b"\0")
|
||||
return {"commit": _out(["git", "rev-parse", "--short=12", "HEAD"]), "branch": _out(["git", "branch", "--show-current"]),
|
||||
"dirty": any(not s.startswith("??") for s in st), "n_modified": sum(not s.startswith("??") for s in st),
|
||||
"n_untracked": sum(s.startswith("??") for s in st), "code_sha256": h.hexdigest()[:16] if files else ""}
|
||||
|
||||
|
||||
def gpu_state() -> list[dict]:
|
||||
rows = _out(["nvidia-smi", "--query-gpu=index,memory.used,memory.total,utilization.gpu",
|
||||
"--format=csv,noheader,nounits"])
|
||||
out = []
|
||||
for r in rows.splitlines():
|
||||
try:
|
||||
i, used, tot, util = (int(x) for x in r.split(","))
|
||||
except ValueError:
|
||||
continue
|
||||
out.append({"index": i, "mem_used_mib": used, "mem_total_mib": tot, "util_pct": util})
|
||||
return out
|
||||
|
||||
|
||||
def _group_pids(pgid: int) -> set[int]:
|
||||
pids = set()
|
||||
for d in Path("/proc").iterdir():
|
||||
if d.name.isdigit():
|
||||
try:
|
||||
if os.getpgid(int(d.name)) == pgid:
|
||||
pids.add(int(d.name))
|
||||
except OSError:
|
||||
pass
|
||||
return pids
|
||||
|
||||
|
||||
class GpuSampler(threading.Thread):
|
||||
"""Sample the VRAM of the process tree (same process group as the child process) every GPU_POLL_S seconds."""
|
||||
|
||||
def __init__(self, pgid: int):
|
||||
super().__init__(daemon=True)
|
||||
self.pgid, self.peak, self.stop = pgid, 0, threading.Event()
|
||||
|
||||
def run(self) -> None:
|
||||
wait = 2.0 # early first sample so that short jobs still get a reading
|
||||
while not self.stop.wait(wait):
|
||||
wait = GPU_POLL_S
|
||||
rows = _out(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"])
|
||||
if not rows:
|
||||
continue
|
||||
pids = _group_pids(self.pgid)
|
||||
tot = 0
|
||||
for r in rows.splitlines():
|
||||
try:
|
||||
pid, mem = (int(x) for x in r.split(","))
|
||||
except ValueError:
|
||||
continue
|
||||
tot += mem if pid in pids else 0
|
||||
self.peak = max(self.peak, tot)
|
||||
|
||||
|
||||
def default_name(cmd: list[str]) -> str:
|
||||
for a in cmd:
|
||||
m = re.search(r"(\d\d_\w+)\.py$", a) or re.search(r"(run_p\d+)\.sh$", a)
|
||||
if m:
|
||||
return m.group(1)
|
||||
if "pytest" in cmd:
|
||||
return "pytest"
|
||||
return re.sub(r"\W+", "_", Path(cmd[0]).stem) or "run"
|
||||
|
||||
|
||||
def device_of(cmd: list[str]) -> str:
|
||||
for i, a in enumerate(cmd):
|
||||
if a == "--device" and i + 1 < len(cmd):
|
||||
return cmd[i + 1]
|
||||
if a.startswith("--device="):
|
||||
return a.split("=", 1)[1]
|
||||
return os.environ.get("DEVICE", "")
|
||||
|
||||
|
||||
def write_json(path: Path, obj: dict) -> None:
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str))
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def append_index(row: dict, root: Path | None = None) -> None:
|
||||
root = root or logs_dir()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with open(root / "index.csv", "a+", newline="") as f:
|
||||
fcntl.flock(f, fcntl.LOCK_EX) # several concurrent runs may write to the index
|
||||
f.seek(0)
|
||||
new = not f.read(1)
|
||||
w = csv.DictWriter(f, FIELDS, extrasaction="ignore")
|
||||
if new:
|
||||
w.writeheader()
|
||||
w.writerow(row)
|
||||
fcntl.flock(f, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def index_row(meta: dict) -> dict:
|
||||
g = meta.get("git", {})
|
||||
return {"run_id": meta["run_id"], "parent": meta.get("parent") or "", "name": meta["name"], "status": meta["status"],
|
||||
"exit_code": "" if meta.get("exit_code") is None else meta["exit_code"], "start": meta.get("start") or "",
|
||||
"end": meta.get("end") or "", "wall_s": "" if meta.get("wall_s") is None else round(meta["wall_s"], 1),
|
||||
"wall": fmt_wall(meta.get("wall_s")), "device": meta.get("device", ""), "git": g.get("commit", ""),
|
||||
"dirty": g.get("dirty", ""), "code_sha": g.get("code_sha256", ""), "source": meta.get("source", "runlog"),
|
||||
"cmd": " ⏎ ".join(meta["cmd"].splitlines())}
|
||||
|
||||
|
||||
def new_run_dir(name: str, start: dt.datetime) -> tuple[Path, str, str | None]:
|
||||
parent = os.environ.get("RUNLOG_DIR")
|
||||
if parent and Path(parent).is_dir():
|
||||
k = sum(1 for p in Path(parent).iterdir() if p.is_dir()) + 1
|
||||
while any(Path(parent).glob(f"{k:02d}_*")):
|
||||
k += 1
|
||||
d = Path(parent) / f"{k:02d}_{name}"
|
||||
return d, f"{Path(parent).name}/{d.name}", os.environ.get("RUNLOG_ID")
|
||||
base = logs_dir() / "runs" / f"{start:%Y%m%d-%H%M%S}_{name}"
|
||||
d, k = base, 1
|
||||
while d.exists(): # two runs started in the same second
|
||||
k += 1
|
||||
d = base.with_name(f"{base.name}-{k}")
|
||||
return d, d.name, None
|
||||
|
||||
|
||||
class Tee:
|
||||
"""Write the child process bytes to the terminal (verbatim) and to log.txt (prefixing each line with [h:mm:ss])."""
|
||||
|
||||
def __init__(self, path: Path, t0: float, stamp: bool):
|
||||
self.f, self.t0, self.stamp, self.bol, self.echo = open(path, "ab"), t0, stamp, True, True
|
||||
|
||||
def write(self, b: bytes) -> None:
|
||||
if self.echo:
|
||||
try:
|
||||
sys.stdout.buffer.write(b)
|
||||
sys.stdout.buffer.flush()
|
||||
except (BrokenPipeError, ValueError): # terminal/pipe closed: keep writing to log.txt
|
||||
self.echo = False
|
||||
if self.stamp:
|
||||
parts = b.split(b"\n")
|
||||
out = []
|
||||
for i, p in enumerate(parts):
|
||||
if self.bol and (p or i < len(parts) - 1):
|
||||
out.append(f"[{fmt_wall(time.time() - self.t0)}] ".encode())
|
||||
self.bol = False
|
||||
out.append(p)
|
||||
if i < len(parts) - 1:
|
||||
out.append(b"\n")
|
||||
self.bol = True
|
||||
b = b"".join(out)
|
||||
self.f.write(b)
|
||||
self.f.flush()
|
||||
|
||||
def note(self, s: str) -> None:
|
||||
self.f.write(f"# {s}\n".encode())
|
||||
self.f.flush()
|
||||
|
||||
|
||||
def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
|
||||
if cmd and cmd[0].endswith(".py"):
|
||||
cmd = [sys.executable, *cmd]
|
||||
name = re.sub(r"[^\w.-]+", "_", name or default_name(cmd))
|
||||
start = now()
|
||||
rdir, run_id, parent = new_run_dir(name, start)
|
||||
rdir.mkdir(parents=True)
|
||||
t0 = time.time()
|
||||
meta = {"run_id": run_id, "parent": parent, "name": name, "note": note, "status": "running", "exit_code": None,
|
||||
"cmd": shlex.join(cmd), "argv": cmd, "cwd": os.getcwd(), "start": start.isoformat(timespec="seconds"),
|
||||
"end": None, "wall_s": None, "device": device_of(cmd), "host": socket.gethostname(),
|
||||
"user": os.environ.get("USER", ""), "launcher_pid": os.getpid(), "python": platform.python_version(),
|
||||
"env": {k: os.environ[k] for k in ENV_KEYS if k in os.environ}, "git": git_state(),
|
||||
"gpu_start": gpu_state(), "source": "runlog"}
|
||||
write_json(rdir / "meta.json", meta)
|
||||
tee = Tee(rdir / "log.txt", t0, stamp)
|
||||
tee.note(f"{run_id} {meta['start']} {meta['cmd']}")
|
||||
|
||||
env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1"}
|
||||
try:
|
||||
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, process_group=0)
|
||||
except OSError as e:
|
||||
tee.note(f"failed to launch: {e}")
|
||||
child = None
|
||||
got = []
|
||||
|
||||
def forward(sig, _frame): # Ctrl-C / kill: forward to the whole child process group and record it
|
||||
got.append(signal.Signals(sig).name)
|
||||
if child is not None:
|
||||
try:
|
||||
os.killpg(child.pid, sig)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
||||
signal.signal(s, forward)
|
||||
sampler = None
|
||||
if child is not None:
|
||||
sampler = GpuSampler(child.pid)
|
||||
sampler.start()
|
||||
fd = child.stdout.fileno()
|
||||
while True:
|
||||
try:
|
||||
b = os.read(fd, 65536)
|
||||
except InterruptedError:
|
||||
continue
|
||||
if not b:
|
||||
break
|
||||
tee.write(b)
|
||||
code = child.wait()
|
||||
sampler.stop.set()
|
||||
else:
|
||||
code = 127
|
||||
ru = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
wall = time.time() - t0
|
||||
status = "ok" if code == 0 else ("interrupted" if got or code < 0 else "failed")
|
||||
meta |= {"status": status, "exit_code": code, "signals": got, "end": now().isoformat(timespec="seconds"),
|
||||
"wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1),
|
||||
"cpu_sys_s": round(ru.ru_stime, 1), "max_rss_mib": round(ru.ru_maxrss / 1024),
|
||||
"gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()}
|
||||
write_json(rdir / "meta.json", meta)
|
||||
tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)")
|
||||
append_index(index_row(meta))
|
||||
print(f"[runlog] {status} exit {code} wall {fmt_wall(wall)} -> {rdir}", file=sys.stderr, flush=True)
|
||||
return code if code >= 0 else 128 - code
|
||||
|
||||
|
||||
def all_metas(root: Path) -> list[dict]:
|
||||
metas = [json.loads(m.read_text()) for m in [*(root / "runs").glob("*/meta.json"), *(root / "runs").glob("*/*/meta.json")]]
|
||||
return sorted(metas, key=lambda m: (m.get("start") or m.get("end") or "", m["run_id"]))
|
||||
|
||||
|
||||
def reindex() -> None:
|
||||
root = logs_dir()
|
||||
metas = [m for m in all_metas(root) if m.get("status") != "running"]
|
||||
(root / "index.csv").unlink(missing_ok=True)
|
||||
for m in metas:
|
||||
append_index(index_row(m), root)
|
||||
print(f"{len(metas)} rows -> {root / 'index.csv'}")
|
||||
|
||||
|
||||
def ls(k: int) -> None:
|
||||
root = logs_dir()
|
||||
rows = list(csv.DictReader(open(root / "index.csv"))) if (root / "index.csv").exists() else []
|
||||
done = {r["run_id"] for r in rows}
|
||||
for meta in all_metas(root):
|
||||
if meta["run_id"] in done or meta.get("status") != "running":
|
||||
continue
|
||||
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists()
|
||||
meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted
|
||||
start = dt.datetime.fromisoformat(meta["start"])
|
||||
meta["wall_s"] = (now() - start).total_seconds() if alive else None
|
||||
rows.append(index_row(meta))
|
||||
rows = rows[-k:]
|
||||
cols = ["run_id", "status", "exit_code", "start", "wall", "device", "cmd"]
|
||||
w = {c: min(60, max([len(c)] + [len(str(r[c])) for r in rows])) for c in cols}
|
||||
print(" ".join(c.ljust(w[c]) for c in cols))
|
||||
for r in rows:
|
||||
print(" ".join(str(r[c])[:w[c]].ljust(w[c]) for c in cols))
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
argv = sys.argv[1:] if argv is None else argv
|
||||
if argv[:1] == ["ls"]:
|
||||
ap = argparse.ArgumentParser(prog="python -m ml_porosity.runlog ls")
|
||||
ap.add_argument("-k", type=int, default=30)
|
||||
ls(ap.parse_args(argv[1:]).k)
|
||||
return 0
|
||||
if argv == ["reindex"]:
|
||||
reindex()
|
||||
return 0
|
||||
ap = argparse.ArgumentParser(prog="python -m ml_porosity.runlog", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("-n", "--name", help="run name (default: script name, e.g. 11_run_d2)")
|
||||
ap.add_argument("--note", default="", help="free-text note stored in meta.json")
|
||||
ap.add_argument("--no-stamp", action="store_true", help="do not prefix log.txt lines with [h:mm:ss]")
|
||||
ap.add_argument("cmd", nargs=argparse.REMAINDER)
|
||||
a = ap.parse_args(argv)
|
||||
cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd
|
||||
if not cmd:
|
||||
ap.error("missing command to run")
|
||||
return run(cmd, a.name, a.note, not a.no_stamp)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user