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,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)
|
||||
|
||||
Reference in New Issue
Block a user