P0 + P1: ml_porosity package, audited F3 data, LOWO baselines, protocol v2

P0
- ml_porosity/: survey geometry, LAS/TDR/SEG-Y readers (4 ms delay fix,
  invalid time scalar, header LUT for incomplete cubes), anti-aliased
  log-to-time resampling, CNN-GRU v2 with the thesis loss, 41+ unit tests.
- Full F3 Demo 2023 under data/ (text well/fault files tracked, bulk data
  ignored); the filtered copy and its cleanup notes are removed.
- SHA-256 manifests for F3, Volve, NLOG and the thesis outputs.

P1
- configs/protocol.yaml v2, locked by SHA-256 at 2026-10-26T04:28:09Z,
  before the first LOWO run (04:30:50Z); 05_lowo.py refuses to run on a
  hash mismatch. This commit postdates the runs.
- Wavelet/synthetic tie QC, residual misregistration, LOWO 5 seeds for
  B0a, B0b, B1, B2, B3a, B3b (scripts 04-06); gate G-A: no pivot.
- Volve D3: horizons, well picks, checkshots and the ST10010 cube read
  from data/Volve (scripts/07).
- D-1 label check against measured NLOG density (scripts/08): PHIE_DT
  stays the primary label.
- docs/plan.md, Volve and NLOG inventories, report.html.

Full-text reference PDFs in refs/ stay local (ignored).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 08:41:11 +00:00
parent d11b7b1bb5
commit a76e61398a
163 changed files with 120177 additions and 2742 deletions

3
ml_porosity/__init__.py Normal file
View File

@@ -0,0 +1,3 @@
"""ML-Porosity: seismic porosity prediction under well-tie uncertainty."""
__version__ = "0.1.0"

View File

View File

@@ -0,0 +1,26 @@
"""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."""
from __future__ import annotations
import numpy as np
from scipy import signal
FEATURES = ("amplitude", "envelope", "cos_phase", "sin_phase", "inst_freq", "relative_ai", "twt")
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."""
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
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
rai = np.cumsum(s)
sos = signal.butter(4, 5.0, btype="highpass", fs=1000.0 / dt_ms, output="sos")
rai = signal.sosfiltfilt(sos, rai)
return np.column_stack([s, env, np.cos(np.angle(a)), np.sin(np.angle(a)), f_inst, rai, times_ms])

View File

@@ -0,0 +1,74 @@
"""B1: post-stack model-based AI inversion (PyLops) với LFM nội suy theo horizon, rồi φ = a + b·AI."""
from __future__ import annotations
import numpy as np
from pylops.avo.poststack import PoststackInversion, PoststackLinearModelling
from scipy import signal
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."""
x = np.asarray(x, dtype=float).copy()
ok = np.isfinite(x)
x[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), x[ok])
return x
def lowpass(x: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> np.ndarray:
sos = signal.butter(order, f_c_hz, fs=1000.0 / dt_ms, output="sos")
return signal.sosfiltfilt(sos, x, padtype="even")
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."""
ok = np.isfinite(h_from) & np.isfinite(h_to)
a, b = h_from[ok], h_to[ok]
order = np.argsort(a)
a, b = a[order], b[order]
keep = np.concatenate([[True], (np.diff(a) > 0) & (np.diff(b) > 0)])
a, b = a[keep], b[keep]
out = np.interp(t, a, b)
out[t < a[0]] = t[t < a[0]] + (b[0] - a[0])
out[t > a[-1]] = t[t > a[-1]] + (b[-1] - a[-1])
return out
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)."""
num = np.zeros_like(t, dtype=float)
den = 0.0
for w in wells.values():
lf = lowpass(fill_edges(w["logai"]), f_c_hz)
tw = strat_map(t, np.asarray(target_h), np.asarray(w["h"]))
val = np.interp(tw, t, lf)
d = max(float(np.hypot(*(np.asarray(target_xy) - np.asarray(w["xy"])))), 1.0)
wt = d ** (-power)
num += wt * val
den += wt
return num / den
def operator_reflectivity(logai: np.ndarray, nspike: int = 33) -> np.ndarray:
"""Reflectivity theo đúng quy ước của PoststackLinearModelling (wavelet xung đơn vị)."""
spike = np.zeros(nspike)
spike[nspike // 2] = 1.0
G0 = PoststackLinearModelling(spike, len(logai), explicit=True).A
return G0 @ logai
def estimate_wavelet(train_logai: list[np.ndarray], train_seis: list[np.ndarray], mask: np.ndarray,
dt_ms: float = 4.0, length_ms: float = 128.0, damping: float = 0.05) -> np.ndarray:
refl = [operator_reflectivity(fill_edges(m))[mask] for m in train_logai]
return estimate_wavelet_ls(refl, [s[mask] for s in train_seis], dt_ms, length_ms, damping)
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."""
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)
return np.asarray(m).ravel()

View File

View File

@@ -0,0 +1,110 @@
"""Biến đổi bin (inline/crossline) ↔ XY theo file `.survey` của OpendTect.
`.survey` lưu phép biến đổi affine
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`.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import numpy as np
@dataclass(frozen=True)
class SurveyGeometry:
x_coef: tuple[float, float, float]
y_coef: tuple[float, float, float]
il_range: tuple[int, int, int]
xl_range: tuple[int, int, int]
z_range: tuple[float, float, float]
set_points: tuple[tuple[int, int, float, float], ...] = ()
epsg: int | None = None
@classmethod
def from_survey(cls, path: str | Path) -> SurveyGeometry:
path = Path(path)
if path.is_dir():
path = path / ".survey"
kv: dict[str, str] = {}
for line in path.read_text(errors="replace").splitlines():
if ":" in line:
k, v = line.split(":", 1)
kv[k.strip()] = v.strip()
def nums(key: str) -> list[float]:
return [float(s) for s in kv[key].split("`")[:3]]
set_points = []
for k, v in kv.items():
if k.startswith("Set Point."):
binid, xy = v.split("`")
il, xl = (int(s) for s in binid.split("/"))
x, y = (float(s) for s in xy.strip("()").split(","))
set_points.append((il, xl, x, y))
epsg = None
if "Coordinate System.Projection.ID" in kv:
epsg = int(kv["Coordinate System.Projection.ID"].split("`")[-1])
return cls(
x_coef=tuple(nums("Coord-X-BinID")),
y_coef=tuple(nums("Coord-Y-BinID")),
il_range=tuple(int(v) for v in nums("In-line range")),
xl_range=tuple(int(v) for v in nums("Cross-line range")),
z_range=tuple(nums("Z range")),
set_points=tuple(set_points),
epsg=epsg,
)
@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."""
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)
cy, *_ = np.linalg.lstsq(A, y, rcond=None)
def rng(v):
u = np.unique(v)
step = int(np.diff(u).min()) if len(u) > 1 else 1
return int(u[0]), int(u[-1]), step
return cls(x_coef=tuple(float(c) for c in cx), y_coef=tuple(float(c) for c in cy),
il_range=rng(il), xl_range=rng(xl), z_range=tuple(z_range), epsg=epsg)
def _matrix(self) -> np.ndarray:
return np.array([[self.x_coef[1], self.x_coef[2]], [self.y_coef[1], self.y_coef[2]]])
def bin_to_xy(self, il, xl):
il = np.asarray(il, dtype=float)
xl = np.asarray(xl, dtype=float)
x = self.x_coef[0] + self.x_coef[1] * il + self.x_coef[2] * xl
y = self.y_coef[0] + self.y_coef[1] * il + self.y_coef[2] * xl
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."""
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]])
il, xl = np.tensordot(np.linalg.inv(self._matrix()), rhs, axes=1)
return il, xl
def nearest_bin(self, x: float, y: float) -> tuple[int, int]:
il, xl = self.xy_to_bin(x, y)
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."""
m = self._matrix()
return float(np.hypot(*m[:, 0])), float(np.hypot(*m[:, 1]))
def in_survey(self, il: int, xl: int) -> bool:
return (
self.il_range[0] <= il <= self.il_range[1]
and self.xl_range[0] <= xl <= self.xl_range[1]
)

View File

@@ -0,0 +1,40 @@
"""Horizon F3 dạng ASCII (X, Y, TWT ms) trong Rawdata/Surface_data/."""
from __future__ import annotations
from pathlib import Path
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.
F3_HORIZONS = ("Shallow", "FS8", "FS7", "Truncation", "Top-Foresets", "FS6", "MFS4")
def horizon_path(name: str) -> Path:
return f3_root() / "Rawdata" / "Surface_data" / f"F3-Horizon-{name}.txt"
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."""
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)
return {(i, j): t for i, j, t in zip(il, xl, a[:, 2])}
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."""
h = load_horizon_bins(name, geom)
out = []
for il, xl in bins:
if (il, xl) in h:
out.append(h[(il, xl)])
continue
vals = [h[(il + a, xl + b)] for a in range(-radius, radius + 1)
for b in range(-radius, radius + 1) if (il + a, xl + b) in h]
out.append(float(np.mean(vals)) if vals else np.nan)
return np.asarray(out)

121
ml_porosity/data/las_io.py Normal file
View File

@@ -0,0 +1,121 @@
"""Đọc dữ liệu giếng F3: LAS, marker, checkshot, track và các mô hình TD.
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.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
import lasio
import numpy as np
import pandas as pd
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.
LEGACY_IL_XL = {"F03-4": (362, 821), "F02-1": (418, 608), "F06-1": (283, 842)}
@dataclass
class Well:
name: str
x: float
y: float
kb: float
logs: pd.DataFrame # index = MD (m), cột = mnemonic, NaN thay cho 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)
@property
def md(self) -> np.ndarray:
return self.logs.index.to_numpy(dtype=float)
def curve(self, name: str) -> np.ndarray:
return self.logs[name].to_numpy(dtype=float)
def read_las(path: str | Path) -> tuple[pd.DataFrame, dict[str, str], lasio.LASFile]:
las = lasio.read(str(path))
df = las.df()
df.index = df.index.astype(float)
df.index.name = "MD"
units = {c.mnemonic: (c.unit or "") for c in las.curves}
return df, units, las
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."""
lines = Path(path).read_text(errors="replace").splitlines()
if skip_header:
bangs = [i for i, s in enumerate(lines) if s.strip() == "!"]
lines = lines[bangs[1] + 1 :] if len(bangs) >= 2 else lines
rows = []
for s in lines:
parts = s.split()
if len(parts) >= 2:
try:
rows.append((float(parts[0]), float(parts[1])))
except ValueError:
continue
return np.asarray(rows, dtype=float)
def read_markers(path: str | Path) -> pd.DataFrame:
rows = []
for s in Path(path).read_text(errors="replace").splitlines():
s = s.strip()
if not s:
continue
depth, name = s.split(None, 1)
rows.append((float(depth), name.strip()))
return pd.DataFrame(rows, columns=["md", "name"])
def read_track(path: str | Path) -> np.ndarray:
"""Cột: X, Y, TVDSS (m), MD (m)."""
return np.loadtxt(path)
def load_well(name: str, wells_dir: Path | None = None) -> Well:
d = wells_dir or f3_wells_dir()
df, units, las = read_las(d / "Lasfiles" / f"{name}_logs.las")
track = read_track(d / "Track" / f"{name}.track")
x, y = float(track[0, 0]), float(track[0, 1])
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).
cs = read_two_columns(d / "Checkshot" / f"{name}_TD.txt")
checkshot = (
pd.DataFrame({"md": cs[:, 0], "twt_ms": cs[:, 1] * 1000.0})
.drop_duplicates()
.sort_values("md", ignore_index=True)
)
return Well(name, x, y, kb, df, units, markers, checkshot)
def load_td_source(name: str, source: str) -> np.ndarray:
"""Cặp (MD m, TWT ms) từ một nguồn TD.
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)
"""
d = f3_wells_dir()
if source == "checkshot":
a = read_two_columns(d / "Checkshot" / f"{name}_TD.txt")
return np.column_stack([a[:, 0], a[:, 1] * 1000.0])
if source == "dt_model":
return read_two_columns(d / "DT_model" / f"{name}_TD.txt")
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}")

View File

@@ -0,0 +1,53 @@
"""Chuyển log từ miền độ sâu sang trục thời gian seismic, có lọc chống alias.
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.
"""
from __future__ import annotations
import numpy as np
from scipy import signal
from ml_porosity.data.tdr import TDR
def log_to_time(
md: np.ndarray,
values: np.ndarray,
tdr: TDR,
t_out_ms: np.ndarray,
fine_dt_ms: float = 0.25,
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.
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."""
md = np.asarray(md, dtype=float)
v = np.asarray(values, dtype=float)
ok = np.isfinite(v)
t_log = tdr.time_at(md[ok])
v = v[ok]
if v.size < 2:
return np.full(t_out_ms.shape, np.nan)
dt_out = float(t_out_ms[1] - t_out_ms[0])
t_fine = np.arange(t_log[0], t_log[-1] + fine_dt_ms / 2, fine_dt_ms)
v_fine = np.interp(t_fine, t_log, v)
if t_fine.size > 3 * (order + 1):
nyq_out = 0.5 / dt_out
nyq_fine = 0.5 / fine_dt_ms
sos = signal.butter(order, cutoff_frac * nyq_out / nyq_fine, output="sos")
v_fine = signal.sosfiltfilt(sos, v_fine)
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.
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
return out

View File

@@ -0,0 +1,92 @@
"""Đọc trace từ SEG-Y post-stack theo (IL, XL) mà không nạp cả 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.
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.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
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
_TIME_SCALARS = {0, 1, -1, 10, -10, 100, -100, 1000, -1000, 10000, -10000}
class SeismicCube:
def __init__(self, path: str | Path | None = None):
self.path = Path(path) if path else f3_segy()
self._lut: dict[tuple[int, int], int] | None = None
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")
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):
raise
# lưới không đủ trace: tra chỉ số trace theo header IL/XL
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)[:]
self._lut = {(int(i), int(j)): k for k, (i, j) in enumerate(zip(il, xl))}
self.ilines, self.xlines = np.unique(il), np.unique(xl)
self.times_ms = np.asarray(self._f.samples, dtype=float)
h = self._f.header[0]
if h[segyio.TraceField.ScalarTraceHeader] not in _TIME_SCALARS:
self.times_ms += h[segyio.TraceField.DelayRecordingTime] - self.times_ms[0]
self.dt_ms = float(self.times_ms[1] - self.times_ms[0])
def __enter__(self) -> SeismicCube:
return self
def __exit__(self, *exc) -> None:
self.close()
def close(self) -> None:
self._f.close()
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")
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")
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."""
h = self._f.header[self._index(il, xl)]
sc = h[segyio.TraceField.SourceGroupScalar]
mul = 1 / abs(sc) if sc < 0 else (sc or 1)
return h[segyio.TraceField.CDP_X] * mul, h[segyio.TraceField.CDP_Y] * mul
def trace(self, il: int, xl: int) -> np.ndarray:
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."""
return np.stack(
[
self.trace(il + di, xl + dx)
for di in range(-radius, radius + 1)
for dx in range(-radius, radius + 1)
]
)
def window(self, t0_ms: float, t1_ms: float) -> np.ndarray:
"""Mặt nạ boolean cho các mẫu trong [t0, t1]."""
return (self.times_ms >= t0_ms) & (self.times_ms <= t1_ms)

View File

@@ -0,0 +1,64 @@
"""Synthetic seismogram và đo lệch thời gian giữa synthetic và seismic."""
from __future__ import annotations
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."""
ai = np.asarray(ai, dtype=float)
r = np.zeros_like(ai)
r[:-1] = (ai[1:] - ai[:-1]) / (ai[1:] + ai[:-1])
return np.nan_to_num(r)
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."""
t = np.arange(len(x)) * dt_ms
return np.interp(t - shift_ms, t, x, left=0.0, right=0.0)
def ncc(a: np.ndarray, b: np.ndarray) -> float:
a = a - a.mean()
b = b - b.mean()
d = np.sqrt((a * a).sum() * (b * b).sum())
return float((a * b).sum() / d) if d > 0 else float("nan")
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)."""
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))
return float(shifts[k]), float(rs[k])
def local_shifts(
syn: np.ndarray,
seis: np.ndarray,
dt_ms: float,
win_ms: float = 120.0,
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."""
n = int(round(win_ms / dt_ms))
hop = max(1, int(round(hop_ms / dt_ms)))
taper = np.hanning(n)
centers, shifts, rs = [], [], []
pad = int(np.ceil(max_ms / dt_ms)) + 1
for i0 in range(pad, len(syn) - n - pad + 1, hop):
sl = slice(i0 - pad, i0 + n + pad)
a, b = syn[sl], seis[sl]
best = (0.0, -np.inf)
for s in np.arange(-max_ms, max_ms + 0.25, 0.5):
sa = shift_signal(a, s, dt_ms)[pad:-pad] * taper
r = ncc(sa, b[pad:-pad] * taper)
if r > best[1]:
best = (float(s), r)
centers.append(i0 + n // 2)
shifts.append(best[0])
rs.append(best[1])
return np.array(centers), np.array(shifts), np.array(rs)

142
ml_porosity/data/tdr.py Normal file
View File

@@ -0,0 +1,142 @@
"""Quan hệ thời gian–độ sâu (TDR): MD (m, từ KB) ↔ TWT (ms, từ datum seismic).
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.
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from scipy import integrate
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
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")
if np.any(np.diff(md) <= 0):
raise ValueError(f"TDR {self.name!r}: MD không tăng nghiêm ngặt")
if np.any(np.diff(t) <= 0):
raise ValueError(f"TDR {self.name!r}: TWT không tăng nghiêm ngặt")
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)."""
pairs = np.asarray(pairs, dtype=float)
pairs = pairs[np.argsort(pairs[:, 0], kind="stable")]
if drop_flat:
keep = [0]
for i in range(1, len(pairs)):
if pairs[i, 0] > pairs[keep[-1], 0] and pairs[i, 1] > pairs[keep[-1], 1]:
keep.append(i)
pairs = pairs[keep]
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."""
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."""
return 2000.0 * np.diff(self.md) / np.diff(self.twt_ms)
def _interp_extrap(x, xp, fp) -> np.ndarray:
x = np.asarray(x, dtype=float)
y = np.interp(x, xp, fp)
lo, hi = x < xp[0], x > xp[-1]
if np.any(lo):
y[lo] = fp[0] + (x[lo] - xp[0]) * (fp[1] - fp[0]) / (xp[1] - xp[0])
if np.any(hi):
y[hi] = fp[-1] + (x[hi] - xp[-1]) * (fp[-1] - fp[-2]) / (xp[-1] - xp[-2])
return y
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)."""
a = np.asarray(a, dtype=float).copy()
ok = np.isfinite(a)
if not ok.any():
raise ValueError("toàn bộ giá trị là 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)."""
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."""
md = np.asarray(md, dtype=float)
dt = np.asarray(dt_us_per_m, dtype=float)
ok = np.isfinite(dt) & (dt > 0)
md_v, dt_v = md[ok], dt[ok]
t = 2000.0 * integrate.cumulative_trapezoid(dt_v * US_PER_M_TO_S_PER_M, md_v, initial=0.0)
if md0 < md_v[0]:
t_md0 = -2000.0 * (md_v[0] - md0) * dt_v[0] * US_PER_M_TO_S_PER_M
else:
t_md0 = float(_interp_extrap(md0, md_v, t))
return TDR(md_v, t - t_md0 + t0_ms, "sonic")
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})
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.
"""
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")
z = np.union1d(base.md, za)
tb = base.time_at(z)
tba = base.time_at(za)
t = np.empty_like(z)
k = np.clip(np.searchsorted(za, z, side="right") - 1, 0, len(za) - 2)
inside = (z >= za[0]) & (z <= za[-1])
scale = (ta[k + 1] - ta[k]) / (tba[k + 1] - tba[k])
t[inside] = ta[k[inside]] + (tb[inside] - tba[k[inside]]) * scale[inside]
above, below = z < za[0], z > za[-1]
t[above] = tb[above] + (ta[0] - tba[0])
t[below] = tb[below] + (ta[-1] - tba[-1])
return TDR(z, t, name)
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."""
return tdr.time_at(anchor_md) - np.asarray(anchor_twt_ms, dtype=float)

View File

@@ -0,0 +1,121 @@
"""Đọc dữ liệu Volve: horizon xuất từ OpenWorks, well picks (cột cố định) và checkshot VSP.
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).
"""
from __future__ import annotations
from dataclasses import dataclass
from functools import cached_property
from pathlib import Path
import numpy as np
import pandas as pd
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
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")
@dataclass(frozen=True)
class Horizon:
survey: str
name: str
domain: str # "TIME" (TWT ms) hoặc "DEPTH" (m)
il: np.ndarray
xl: np.ndarray
x: np.ndarray
y: np.ndarray
z: np.ndarray
def geometry(self) -> SurveyGeometry:
return SurveyGeometry.from_points(self.il, self.xl, self.x, self.y, epsg=VOLVE_EPSG)
@cached_property
def lut(self) -> dict[tuple[int, int], float]:
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."""
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]
return float(np.median(vals)) if vals else float("nan")
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ó `=`)."""
meta, rows = [], []
with open(path, errors="replace") as fh:
for line in fh:
if line.startswith("#") or not line.strip():
continue
parts = line.strip().split(",")
if len(parts) == 5:
try:
rows.append([float(v) for v in parts])
continue
except ValueError:
pass
meta.append(line.strip())
a = np.asarray(rows)
survey, name, _, domain = (meta + [""] * 4)[:4]
return Horizon(survey=survey, name=name, domain=domain, il=a[:, 0].astype(int), xl=a[:, 1].astype(int),
x=a[:, 2], y=a[:, 3], z=a[:, 4])
PICK_COLUMNS = {"Well name": "well", "Surface name": "surface", "Obs#": "obs", "Qlf": "qlf", "MD": "md",
"TVD": "tvd", "TVDSS": "tvdss", "TWT": "twt_ms", "Dip": "dip", "Azi": "azi",
"Easting": "x", "Northing": "y", "Intrp": "interpreter"}
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.
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, []
for i, ln in enumerate(lines):
if ln.strip().startswith("Well name") and i + 1 < len(lines) and lines[i + 1].strip().startswith("---"):
dash = lines[i + 1]
spans, j = [], 0
while j < len(dash):
if dash[j] == "-":
k = j
while k < len(dash) and dash[k] == "-":
k += 1
spans.append((j, k, ln[j:k + 1].strip()))
j = k
else:
j += 1
elif spans and ln.startswith(" NO "):
rows.append({PICK_COLUMNS[n]: ln[s:e + 1].strip() for s, e, n in spans})
df = pd.DataFrame(rows)
for c in ("obs", "md", "tvd", "tvdss", "twt_ms", "dip", "azi", "x", "y"):
df[c] = pd.to_numeric(df[c], errors="coerce")
df["obs"] = df["obs"].astype(int)
return df
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."""
text = Path(path).read_text(errors="replace")
rows = []
for ln in text.splitlines():
p = ln.split()
if len(p) == 3:
try:
rows.append([float(v) for v in p])
except ValueError:
pass
a = np.asarray(rows)
md = a[:, 0] + (VOLVE_RKB_M if "MDMSL" in text else 0.0)
return pd.DataFrame({"md": md, "tvdss": a[:, 1], "twt_ms": a[:, 2]})

View File

@@ -0,0 +1,69 @@
"""Wavelet: Ricker, wavelet thống kê pha không, xoay pha hằng và ước lượng từ giếng.
Mọi wavelet có số mẫu lẻ, tâm ở giữa, bước `dt_ms`.
"""
from __future__ import annotations
import numpy as np
from scipy import signal
from scipy.linalg import toeplitz
def ricker(f_peak_hz: float, dt_ms: float = 4.0, length_ms: float = 128.0) -> np.ndarray:
n = int(round(length_ms / dt_ms)) // 2
t = np.arange(-n, n + 1) * dt_ms / 1000.0
a = (np.pi * f_peak_hz * t) ** 2
return (1 - 2 * a) * np.exp(-a)
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)."""
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."""
traces = np.atleast_2d(traces)
nt = traces.shape[1]
nfft = int(2 ** np.ceil(np.log2(4 * nt)))
spec = np.mean(np.abs(np.fft.rfft(traces * np.hanning(nt), nfft)), axis=0)
w = np.fft.fftshift(np.fft.irfft(spec, nfft))
n = int(round(length_ms / dt_ms)) // 2
c = nfft // 2
w = w[c - n : c + n + 1] * np.hanning(2 * n + 1)
return w / np.max(np.abs(w))
def estimate_wavelet_ls(
reflectivity: list[np.ndarray],
seismic: list[np.ndarray],
dt_ms: float = 4.0,
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.
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."""
n = int(round(length_ms / dt_ms)) // 2
m = 2 * n + 1
R = np.zeros(m)
g = np.zeros(m)
for r, s in zip(reflectivity, seismic):
L = len(r)
acf = np.correlate(r, r, mode="full")[L - 1 : L - 1 + m]
R += acf
ccf = np.correlate(s, r, mode="full") # ccf[L-1+k] = Σ s[i+k] r[i]
g += ccf[L - 1 - n : L + n]
A = toeplitz(R)
A[np.diag_indices(m)] += damping * R[0]
w = np.linalg.solve(A, g)
return w * np.hanning(m + 2)[1:-1]
def convolve_same(r: np.ndarray, w: np.ndarray) -> np.ndarray:
return np.convolve(r, w, mode="same")

View File

View File

@@ -0,0 +1,60 @@
"""Metric điểm cơ bản; bỏ qua mẫu NaN ở cả hai phía."""
from __future__ import annotations
import numpy as np
def _valid(y_true, y_pred):
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
ok = np.isfinite(y_true) & np.isfinite(y_pred)
return y_true[ok], y_pred[ok]
def point_metrics(y_true, y_pred) -> dict[str, float]:
t, p = _valid(y_true, y_pred)
err = p - t
var_t = float(np.var(t))
return {
"n": int(t.size),
"mae": float(np.mean(np.abs(err))),
"rmse": float(np.sqrt(np.mean(err**2))),
"pcc": float(np.corrcoef(t, p)[0, 1]) if t.size > 1 else float("nan"),
"r2": float(1.0 - np.mean(err**2) / var_t) if var_t > 0 else float("nan"),
"std_ratio": float(np.std(p) / np.std(t)) if np.std(t) > 0 else float("nan"),
}
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)."""
from scipy import signal
y = np.asarray(y, dtype=float)
sos = signal.butter(order, f_c_hz, fs=1000.0 / dt_ms, output="sos")
low = signal.sosfiltfilt(sos, y, padtype="even")
return low, y - low
def band_metrics(y_true, y_pred, f_c_hz: float = 6.0, dt_ms: float = 4.0) -> dict[str, float]:
lt, ht = split_bands(y_true, f_c_hz, dt_ms)
lp, hp = split_bands(y_pred, f_c_hz, dt_ms)
lo, hi = point_metrics(lt, lp), point_metrics(ht, hp)
return {f"low_{k}": lo[k] for k in ("rmse", "pcc", "std_ratio")} | {
f"band_{k}": hi[k] for k in ("rmse", "pcc", "std_ratio")
}
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."""
from scipy import stats
y, mu, s = (np.asarray(a, dtype=float) for a in (y_true, mu, sigma))
z = (y - mu) / s
nll = float(np.mean(0.5 * np.log(2 * np.pi * s**2) + 0.5 * z**2))
crps = float(np.mean(s * (z * (2 * stats.norm.cdf(z) - 1) + 2 * stats.norm.pdf(z) - 1 / np.sqrt(np.pi))))
out = {"nll": nll, "crps": crps, "mean_sigma": float(np.mean(s))}
for level in (50, 80, 90, 95):
q = stats.norm.ppf(0.5 + level / 200)
out[f"coverage_{level}"] = float(np.mean(np.abs(z) <= q))
return out

View File

View File

@@ -0,0 +1,73 @@
"""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.
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.
"""
from __future__ import annotations
from dataclasses import dataclass
import torch
import torch.nn as nn
def pcc_loss(pred: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
x = pred.squeeze(1); y = target.squeeze(1)
x = (x - x.mean(dim=1, keepdim=True)) / (x.std(dim=1, keepdim=True) + eps)
y = (y - y.mean(dim=1, keepdim=True)) / (y.std(dim=1, keepdim=True) + eps)
return 1.0 - (x * y).mean(dim=1).mean()
def grad_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
dx = pred[..., 1:] - pred[..., :-1]
dy = target[..., 1:] - target[..., :-1]
return torch.mean((dx - dy) ** 2)
def shape_loss(pred: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
x = pred.squeeze(1); y = target.squeeze(1)
x = (x - x.mean(dim=1, keepdim=True)) / (x.std(dim=1, keepdim=True) + eps)
y = (y - y.mean(dim=1, keepdim=True)) / (y.std(dim=1, keepdim=True) + eps)
return ((x - y) ** 2).mean()
def var_match_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
x = pred.squeeze(1); y = target.squeeze(1)
return ((x.std(dim=1) - y.std(dim=1)) ** 2).mean()
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]."""
x = pred.squeeze(1); y = target.squeeze(1)
L = x.shape[1]
losses = []
for lag in range(-max_shift, max_shift + 1):
if lag < 0: xs, ys = x[:, -lag:], y[:, :L + lag]
elif lag > 0: xs, ys = x[:, :L - lag], y[:, lag:]
else: xs, ys = x, y
losses.append(((xs - ys) ** 2).mean(dim=1))
return torch.stack(losses, dim=1).min(dim=1).values.mean()
@dataclass
class LegacyV2Loss:
lambda_pcc: float = 0.60
lambda_grad: float = 0.05
lambda_shape: float = 0.10
lambda_var: float = 0.10
lambda_xcorr: float = 0.20
xcorr_max_shift: int = 8
huber_beta: float = 0.02
def __post_init__(self):
self._reg = nn.SmoothL1Loss(beta=self.huber_beta)
def __call__(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return (
self._reg(pred, target)
+ self.lambda_pcc * pcc_loss(pred, target)
+ self.lambda_grad * grad_loss(pred, target)
+ self.lambda_shape * shape_loss(pred, target)
+ self.lambda_var * var_match_loss(pred, target)
+ self.lambda_xcorr * crosscorr_loss(pred, target, self.xcorr_max_shift)
)

View File

View File

@@ -0,0 +1,36 @@
"""CNN (dilated) + GRU 2 tầng hai chiều + skip head 1×1.
Chuyển nguyên trạng từ `test 2/train_open_patch_v2.py` (lớp CNNGRU); không đổi kiến trúc.
"""
from __future__ import annotations
import torch
import torch.nn as nn
class CNNGRU(nn.Module):
def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05):
super().__init__()
self.cnn = nn.Sequential(
nn.Conv1d(in_ch, d, kernel_size=5, padding=2, dilation=1), nn.ReLU(),
nn.Dropout(pdrop),
nn.Conv1d(d, d, kernel_size=5, padding=4, dilation=2), nn.ReLU(),
nn.Dropout(pdrop),
nn.Conv1d(d, d, kernel_size=5, padding=8, dilation=4), nn.ReLU(),
)
self.gru = nn.GRU(
input_size=d, hidden_size=d, num_layers=2,
batch_first=True, bidirectional=True, dropout=0.0,
)
self.head = nn.Conv1d(2 * d, 1, kernel_size=1)
self.head_skip = nn.Conv1d(in_ch, 1, kernel_size=1)
self.bias = nn.Parameter(torch.zeros(1))
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: (B, C, L) -> (B, 1, L)
h = self.cnn(x)
h2, _ = self.gru(h.transpose(1, 2))
y_main = self.head(h2.transpose(1, 2))
y_skip = self.head_skip(x)
return y_main + y_skip + self.bias.view(1, 1, 1)

View File

@@ -0,0 +1,78 @@
"""Huấn luyện CNN–GRU cho B2 (loss gốc) và B3 (Gaussian NLL), chọn epoch theo vòng inner."""
from __future__ import annotations
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
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."""
def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05, sigma_min: float = 1e-3):
super().__init__()
self.net = CNNGRU(in_ch, d, pdrop)
self.net.head = nn.Conv1d(2 * d, 2, kernel_size=1)
self.net.head_skip = nn.Conv1d(in_ch, 2, kernel_size=1)
self.net.bias = nn.Parameter(torch.zeros(2))
self.sigma_min = sigma_min
def forward(self, x):
h = self.net.cnn(x)
h2, _ = self.net.gru(h.transpose(1, 2))
out = self.net.head(h2.transpose(1, 2)) + self.net.head_skip(x) + self.net.bias.view(1, 2, 1)
return out[:, :1], F.softplus(out[:, 1:]) + self.sigma_min
def gaussian_nll(mu, sigma, y):
return torch.mean(torch.log(sigma) + 0.5 * ((y - mu) / sigma) ** 2)
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)])."""
torch.manual_seed(seed)
np.random.seed(seed)
T = lambda a: torch.tensor(a, dtype=torch.float32, device=device)
x, y = T(Xtr), T(Ytr)[:, None]
in_ch = Xtr.shape[1]
if kind == "legacy":
model = CNNGRU(in_ch, cfg["d_channels"], cfg["p_dropout"]).to(device)
loss_fn = LegacyV2Loss()
else:
model = CNNGRUHetero(in_ch, cfg["d_channels"], cfg["p_dropout"]).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
curve = []
xv = T(Xva) if Xva is not None else None
for ep in range(1, epochs + 1):
model.train()
opt.zero_grad()
if kind == "legacy":
pred = model(x)
if ep <= 50:
pred = pred + 0.01 * torch.randn_like(pred)
loss = loss_fn(pred, y)
else:
mu, sig = model(x)
loss = gaussian_nll(mu, sig, y)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
if xv is not None and ep % eval_every == 0:
mu_v = predict(model, Xva, device)[0]
curve.append((ep, float(np.mean((mu_v - Yva) ** 2))))
return model, curve
@torch.no_grad()
def predict(model, X, device):
model.eval()
out = model(torch.tensor(X, dtype=torch.float32, device=device))
if isinstance(out, tuple):
return out[0][:, 0].cpu().numpy(), out[1][:, 0].cpu().numpy()
return out[:, 0].cpu().numpy(), None

42
ml_porosity/paths.py Normal file
View File

@@ -0,0 +1,42 @@
"""Đườ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."""
from __future__ import annotations
import os
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
def f3_root() -> Path:
"""Thư mục survey F3 (chứa `.survey`)."""
env = os.environ.get("ML_POROSITY_F3_ROOT")
return Path(env) if env else REPO_ROOT / "data" / "F3_Demo_2023" / "F3_Demo_2023"
def f3_wells_dir() -> Path:
return f3_root() / "Rawdata" / "Well_data" / "All_wells_RawData" / "All_wells_RawData"
def f3_segy() -> Path:
return f3_root() / "Rawdata" / "F3_entire.segy"
def volve_root() -> Path:
"""Thư mục Volve tải từ 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)."""
env = os.environ.get("ML_POROSITY_NLOG_ROOT")
return Path(env) if env else REPO_ROOT / "data" / "NLOG"
def outputs_dir() -> Path:
env = os.environ.get("ML_POROSITY_OUTPUTS")
p = Path(env) if env else REPO_ROOT / "outputs"
p.mkdir(parents=True, exist_ok=True)
return p

View File