Initial commit: ML-Porosity project setup

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 08:46:21 +07:00
commit f557fe4a6c
117 changed files with 133910 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

212
test 2/plot_figure.py Normal file
View File

@@ -0,0 +1,212 @@
# -*- coding: utf-8 -*-
"""
Figure 3.2 – Seismic volume (subset) + well locations (train/test)
- Đọc SEGY, cắt cửa sổ thời gian theo ms (t_min, t_max)
- Downsample để vẽ 3D nhẹ nhàng
- Đánh dấu 3 giếng (F03-4, F02-1 = Train; F06-1 = Test)
- Xuất ảnh PNG
"""
import os
import numpy as np
import segyio
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 (needed for 3D)
# =========================
# 1) CẤU HÌNH
# =========================
SEGY_PATH = r"C:\Users\PC\Documents\Thesis\F3_Demo_2023\F3_Demo_2023\Rawdata\F3_entire.segy" # <-- Điền đường dẫn file SEGY
OUT_PNG = "figure_3_2_wells_in_volume.png"
# Cửa sổ thời gian (ms)
T_MIN_MS, T_MAX_MS = 600, 1100
# Hệ số downsample cho vẽ (càng lớn càng nhẹ)
DS_INLINE = 20 # lấy 1/20 số inline
DS_XLINE = 20 # lấy 1/20 số xline
DS_TIME = 4 # lấy 1/4 số mẫu theo thời gian
# WELL_LINES: nhập theo **số hiệu** inline/xline thực trong SEGY (không phải index)
# LƯU Ý: Cần thay các số dưới đây thành giá trị thực (ilines/xlines) của bạn
WELL_LINES = {
"F03-4": {"iline": 362, "xline": 821, "role": "Train"},
"F02-1": {"iline": 418, "xline": 608, "role": "Train"},
"F06-1": {"iline": 283, "xline": 842, "role": "Test"},
}
# Mức ngưỡng hiển thị voxel (percentile)
VOXEL_PERCENTILE = 90 # 90–98 tùy bạn; cao hơn = thưa hơn, nhẹ hơn
# =========================
# 2) HÀM TIỆN ÍCH
# =========================
def time_slice_indices(twt_ms: np.ndarray, t_min: float, t_max: float):
"""Trả về slice index (i0:i1) theo cửa sổ thời gian t_min..t_max (ms)."""
i0 = int(np.searchsorted(twt_ms, t_min, side="left"))
i1 = int(np.searchsorted(twt_ms, t_max, side="right"))
i1 = min(i1, len(twt_ms)) # tránh vượt biên
if i0 >= i1:
raise ValueError(f"Invalid time window: [{t_min}, {t_max}] ms outside [{twt_ms.min()}, {twt_ms.max()}] ms")
return slice(i0, i1)
def line_to_index(sorted_line_numbers: np.ndarray, line_value: int):
"""
Ánh xạ số hiệu inline/xline thực sang index trong mảng đã SORT tăng dần.
Nếu line_value không tồn tại chính xác, trả về vị trí gần nhất.
"""
idx = int(np.searchsorted(sorted_line_numbers, line_value))
if idx == len(sorted_line_numbers):
idx -= 1
elif idx > 0:
# Chọn phần tử gần nhất
left = sorted_line_numbers[idx-1]
right = sorted_line_numbers[idx]
if abs(line_value - left) <= abs(right - line_value):
idx -= 1
return idx
def safe_down_index(idx: int, ds_step: int):
"""Chuyển index gốc sang index sau khi downsample bằng stride ds_step."""
return idx // ds_step
def fmt_tick_values(n_points: int, label_values: np.ndarray):
"""
Lấy tối đa 6 ticks đều nhau cho trục, dùng nhãn từ label_values (đã downsample).
"""
if n_points <= 1:
return [0], [int(label_values[0]) if len(label_values) else 0]
idxs = np.linspace(0, n_points-1, num=min(6, n_points), dtype=int)
labels = [int(label_values[i]) for i in idxs]
return idxs.tolist(), labels
# =========================
# 3) ĐỌC SEGY & TỰ DỰNG CUBE
# =========================
print("[INFO] Loading SEGY:", SEGY_PATH)
with segyio.open(SEGY_PATH, "r", ignore_geometry=True) as f:
# Trục thời gian (ms)
twt_ms_full = np.asarray(f.samples, dtype=float)
t_slice = time_slice_indices(twt_ms_full, T_MIN_MS, T_MAX_MS)
twt_ms = twt_ms_full[t_slice]
# Lấy header INLINE/XLINE cho từng trace
inl_arr = f.attributes(segyio.TraceField.INLINE_3D)[:]
xln_arr = f.attributes(segyio.TraceField.CROSSLINE_3D)[:]
# Unique + sort -> hệ toạ độ lưới
inlines = np.unique(inl_arr)
xlines = np.unique(xln_arr)
n_inl = len(inlines)
n_xln = len(xlines)
n_t = len(twt_ms)
print(f"[INFO] Grid size (full): inlines={n_inl}, xlines={n_xln}, nt={len(twt_ms_full)} → window nt={n_t}")
# Map giá trị INLINE/XLINE sang index
inl_to_idx = {v:i for i, v in enumerate(inlines)}
xln_to_idx = {v:i for i, v in enumerate(xlines)}
# Khởi tạo cube (n_inl, n_xln, n_t_window)
cube = np.empty((n_inl, n_xln, n_t), dtype=np.float32)
# Duyệt toàn bộ trace và gán vào cube
# Chỉ lấy lát thời gian t_slice để tiết kiệm RAM
for tr_idx in range(f.tracecount):
il = inl_arr[tr_idx]
xl = xln_arr[tr_idx]
ii = inl_to_idx[il]
jj = xln_to_idx[xl]
tr = f.trace[tr_idx]
cube[ii, jj, :] = tr[t_slice]
print("[INFO] Cube shape (windowed):", cube.shape)
# =========================
# 4) DOWNSAMPLE CHO VẼ
# =========================
cube_ds = cube[::DS_INLINE, ::DS_XLINE, ::DS_TIME]
ilines_ds = inlines[::DS_INLINE]
xlines_ds = xlines[::DS_XLINE]
twt_ds = twt_ms[::DS_TIME]
print("[INFO] Cube downsampled shape:", cube_ds.shape)
# =========================
# 5) NGƯỠNG VOXELS
# =========================
thr = np.percentile(np.abs(cube_ds), VOXEL_PERCENTILE)
mask = np.abs(cube_ds) >= thr # True/False để vẽ voxels
print(f"[INFO] Voxel threshold at |amp| >= P{VOXEL_PERCENTILE} = {thr:.3f}")
# =========================
# 6) CHUẨN BỊ TỌA ĐỘ TRỤC VẼ (INDEX KHÔNG GIAN)
# =========================
nx, ny, nz = cube_ds.shape
# X, Y, Z = np.meshgrid(np.arange(nx), np.arange(ny), np.arange(nz), indexing="ij")
# =========================
# 7) TÍNH VỊ TRÍ GIẾNG TRONG KHÔNG GIAN DOWNSAMPLE
# =========================
well_plot_data = []
for name, info in WELL_LINES.items():
iln, xln = info["iline"], info["xline"]
role = info.get("role", "Well")
# index trong mảng full (đã SORT)
i_full = line_to_index(inlines, iln)
x_full = line_to_index(xlines, xln)
# index trong mảng downsample
i_ds = safe_down_index(i_full, DS_INLINE)
x_ds = safe_down_index(x_full, DS_XLINE)
# biên an toàn:
i_ds = max(0, min(i_ds, nx-1))
x_ds = max(0, min(x_ds, ny-1))
well_plot_data.append((name, role, i_ds, x_ds))
print("[INFO] Wells (downsampled indices):", well_plot_data)
# =========================
# 8) VẼ HÌNH 3D
# =========================
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection="3d")
ax.voxels(mask, facecolors="tab:blue", edgecolor=None, alpha=0.07)
# Vẽ wells dưới dạng cột/điểm (dọc trục thời gian)
for (name, role, i_ds, x_ds) in well_plot_data:
z_line = np.arange(nz)
ax.plot(
[i_ds]*nz, [x_ds]*nz, z_line,
linewidth=2.2,
label=f"{name} ({role})"
)
ax.scatter(i_ds, x_ds, nz//2, s=40, depthshade=True)
# Nhãn trục (hiển thị số hiệu gần đúng)
xticks, xticklabels = fmt_tick_values(nx, ilines_ds)
yticks, yticklabels = fmt_tick_values(ny, xlines_ds)
zticks, zticklabels = fmt_tick_values(nz, twt_ds.astype(int))
ax.set_xticks(xticks); ax.set_xticklabels(xticklabels)
ax.set_yticks(yticks); ax.set_yticklabels(yticklabels)
ax.set_zticks(zticks); ax.set_zticklabels(zticklabels)
ax.set_xlabel("Inline (number)")
ax.set_ylabel("Crossline (number)")
ax.set_zlabel("Two-Way Time (ms)")
ax.set_title("Well Locations within F3 Seismic Volume (Subset)")
ax.legend(loc="upper left")
plt.tight_layout()
plt.savefig(OUT_PNG, dpi=300)
plt.close(fig)
print(f"[DONE] Saved figure → {os.path.abspath(OUT_PNG)}")

View File

@@ -0,0 +1,42 @@
# plot_porosity_maps.py
# ------------------------------------------------------------
# Vẽ bản đồ porosity tại một thời gian (ms) hoặc chỉ số mẫu
import numpy as np
import matplotlib.pyplot as plt
NPZ_VOL = "outputs/porosity_volume_600_1100ms.npz"
# chọn 1 trong 2 cách:
TARGET_MS = 900.0 # thời gian (ms) trong [600,1100]
TARGET_INDEX = None # hoặc chỉ số sample trong [0, L-1]
def descale(y_scaled, lo, hi):
return y_scaled * (hi - lo) + lo
def main():
D = np.load(NPZ_VOL)
vol = D["vol"] # (nI,nX,L) scaled
il = D["ilines"]; xl = D["xlines"]; t = D["times_ms"]
y_lo = float(D["y_lo"]); y_hi = float(D["y_hi"])
if TARGET_INDEX is None:
idx = int(np.argmin(np.abs(t - TARGET_MS)))
title = f"Porosity map {t[idx]:.1f} ms"
else:
idx = int(TARGET_INDEX)
title = f"Porosity map index {idx} (~{t[idx]:.1f} ms)"
slice_scaled = vol[:, :, idx]
slice_orig = descale(slice_scaled, y_lo, y_hi)
plt.figure(figsize=(7,6))
im = plt.imshow(slice_orig.T, origin="lower", aspect="auto",
extent=[il.min(), il.max(), xl.min(), xl.max()])
plt.colorbar(im, label="Porosity")
plt.xlabel("Inline")
plt.ylabel("Crossline")
plt.title(title)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()

85
test 2/plot_pred.py Normal file
View File

@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
"""
plot_pred.py — Hiển thị lát cắt porosity từ file .npz đã predict
• Vẽ lát cắt theo inline hoặc crossline hoặc time-slice
• Chỉnh các tham số ở mục cấu hình bên dưới
"""
import numpy as np
import matplotlib.pyplot as plt
import os
# ----------------------------
# CẤU HÌNH
# ----------------------------
NPZ_PATH = "outputs/porosity_volume_600_1100ms.npz"
MODE = "inline" # "inline", "xline", hoặc "time"
SLICE_INDEX = 362 # số hiệu inline hoặc xline hoặc thời gian (ms)
CMAP = "Spectral" # hoặc "plasma", "seismic", "inferno"
OUT_FILE = f"{MODE}_{SLICE_INDEX}.png"
# ----------------------------
# TẢI DỮ LIỆU
# ----------------------------
D = np.load(NPZ_PATH)
vol = D["vol"] # (nI, nX, L)
ilines = D["ilines"] # (nI,)
xlines = D["xlines"] # (nX,)
times_ms = D["times_ms"] # (L,)
y_lo = float(D["y_lo"])
y_hi = float(D["y_hi"])
# Giải scale về porosity thật
vol_real = vol * (y_hi - y_lo) + y_lo # scale [0,1] → [y_lo, y_hi]
# ----------------------------
# CHỌN lát cắt
# ----------------------------
if MODE == "inline":
if SLICE_INDEX not in ilines:
raise ValueError(f"Inline {SLICE_INDEX} không có trong tập dữ liệu.")
idx = np.where(ilines == SLICE_INDEX)[0][0]
img = vol_real[idx, :, :] # (nX, L)
xlabel = "Crossline"
ylabel = "Time (ms)"
xticks = xlines
yticks = times_ms
elif MODE == "xline":
if SLICE_INDEX not in xlines:
raise ValueError(f"Xline {SLICE_INDEX} không có trong tập dữ liệu.")
idx = np.where(xlines == SLICE_INDEX)[0][0]
img = vol_real[:, idx, :] # (nI, L)
xlabel = "Inline"
ylabel = "Time (ms)"
xticks = ilines
yticks = times_ms
elif MODE == "time":
if SLICE_INDEX not in times_ms:
raise ValueError(f"Time {SLICE_INDEX} ms không có trong tập dữ liệu.")
idx = np.where(times_ms == SLICE_INDEX)[0][0]
img = vol_real[:, :, idx] # (nI, nX)
xlabel = "Crossline"
ylabel = "Inline"
xticks = xlines
yticks = ilines
else:
raise ValueError("MODE phải là 'inline', 'xline' hoặc 'time'")
# ----------------------------
# HIỂN THỊ
# ----------------------------
plt.figure(figsize=(10, 6))
im = plt.imshow(img.T, aspect="auto", cmap=CMAP,
origin="lower", vmin=y_lo, vmax=y_hi)
plt.colorbar(im, label="Porosity")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(f"Predicted Porosity — {MODE.capitalize()} {SLICE_INDEX}")
plt.tight_layout()
plt.savefig(OUT_FILE, dpi=300)

View File

@@ -0,0 +1,163 @@
# predict_porosity_volume.py
# ------------------------------------------------------------
# Suy luận porosity cho toàn khối F3 trong cửa sổ thời gian 600–1100 ms
# Đầu vào:
# - SEGY_PATH: đường dẫn tới F3 .segy
# - WEIGHTS: trọng số đã train (open_loop_patch_best.pt hoặc open_loop_patch_best_C25.pt)
# - NPZ_PATH: outputs/f3_wells_dataset.npz (để lấy y_lo,y_hi và time grid)
# - PATCH_RADIUS: 1 -> 3x3 (C=9), 2 -> 5x5 (C=25) (phải đúng với lúc train)
# Đầu ra:
# - outputs/porosity_volume_600_1100ms.npz chứa:
# vol: (nI, nX, L) porosity đã scale [0,1]
# ilines, xlines, times_ms, y_lo, y_hi
import os
import numpy as np
import torch
import torch.nn as nn
import segyio
# ================== CONFIG ==================
SEGY_PATH = "C:\\Users\\PC\\Documents\\Thesis\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\F3_entire.segy"
WEIGHTS = "outputs/open_loop_patch_best_v2.pt" # file bạn đã train xong
NPZ_PATH = "outputs/f3_wells_dataset.npz"
PATCH_RADIUS = 1 # 1 -> 3x3 (C=9); 2 -> 5x5 (C=25)
BATCH_COORDS = 64 # số patch suy luận / batch
OUT_PATH = "outputs/porosity_volume_600_1100ms.npz"
TMIN_MS, TMAX_MS = 600.0, 1100.0
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# ============================================
# ------- tiện ích -------
def zscore_1d(x):
x = np.asarray(x, dtype=float)
mu = np.nanmean(x); sd = np.nanstd(x) + 1e-8
return (x - mu) / sd
def zscore_ch(X): # (C,L)
X = X.astype(float, copy=True)
for c in range(X.shape[0]):
X[c] = zscore_1d(X[c])
return X
# ------- model giống lúc train (CNN dilated + GRU) -------
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): # x: (B,C,L)
h = self.cnn(x) # (B,d,L)
h2, _ = self.gru(h.transpose(1, 2)) # (B,L,2d)
y_main = self.head(h2.transpose(1, 2)) # (B,1,L)
y_skip = self.head_skip(x) # (B,1,L)
return y_main + y_skip + self.bias.view(1, 1, 1)
def main():
# 1) Đọc NPZ để lấy time grid và scale (y_lo,y_hi nếu có)
D = np.load(NPZ_PATH, allow_pickle=True)
# times lấy từ 1 giếng (các giếng giống nhau vì cùng mask 600–1100 ms)
times_ms = D["F03-4"].item()["seismic_times_ms"]
# Thử đọc y_min/y_max (có thể lưu là y_min/y_max hoặc y_lo/y_hi tuỳ script trước)
# Nếu không có, sẽ estimate lại từ train wells trong file NPZ
y_lo = None; y_hi = None
for k in D.files:
if k in ["y_min","y_lo"]: y_lo = float(D[k])
if k in ["y_max","y_hi"]: y_hi = float(D[k])
if (y_lo is None) or (y_hi is None):
# estimate từ train wells
y_F34 = D["F03-4"].item()["porosity_resampled"]
y_F21 = D["F02-1"].item()["porosity_resampled"]
y_all = np.concatenate([y_F34, y_F21])
y_lo = float(np.nanpercentile(y_all, 1.0))
y_hi = float(np.nanpercentile(y_all, 99.0))
if not (np.isfinite(y_lo) and np.isfinite(y_hi) and y_hi>y_lo):
y_lo = float(np.nanmin(y_all)); y_hi = float(np.nanmax(y_all))
# 2) Đọc SEGY cube
with segyio.open(SEGY_PATH, "r", ignore_geometry=False) as f:
cube = segyio.tools.cube(f) # (nI, nX, nS)
ilines = np.array(f.ilines)
xlines = np.array(f.xlines)
t_all = np.array(f.samples) # ms
nI, nX, nS = cube.shape
# mask thời gian
mask = (t_all >= TMIN_MS) & (t_all <= TMAX_MS)
idx_t = np.where(mask)[0]
L = int(mask.sum()) # ~126
times_win = t_all[mask]
assert len(times_ms) == L, "Time grid trong NPZ và SEGY không khớp (mask)."
# 3) Chuẩn bị model
C = (2*PATCH_RADIUS + 1)**2
model = CNNGRU(in_ch=C, d=64, pdrop=0.15).to(DEVICE)
model.load_state_dict(torch.load(WEIGHTS, map_location=DEVICE))
model.eval()
# 4) Duyệt toàn bộ toạ độ, gom batch
vol = np.zeros((nI, nX, L), dtype=np.float32)
coords = [(i,j) for i in range(nI) for j in range(nX)]
def get_patch(ii, jj):
chans = []
for di in range(-PATCH_RADIUS, PATCH_RADIUS+1):
for dx in range(-PATCH_RADIUS, PATCH_RADIUS+1):
i = np.clip(ii+di, 0, nI-1)
j = np.clip(jj+dx, 0, nX-1)
tr_full = cube[i, j, :]
chans.append(tr_full[idx_t])
X = np.stack(chans, axis=0) # (C, L)
X = zscore_ch(X)
return X
batch_X = []
batch_pos = []
with torch.no_grad():
for k, (ii, jj) in enumerate(coords, 1):
X = get_patch(ii, jj) # (C,L)
batch_X.append(X)
batch_pos.append((ii, jj))
if len(batch_X) == BATCH_COORDS or k == len(coords):
xb = torch.tensor(np.stack(batch_X, axis=0), dtype=torch.float32).to(DEVICE) # (B,C,L)
yp = model(xb).cpu().numpy()[:, 0, :] # (B,L), scaled [0,1]
# ghi vào volume
for b, (i0, j0) in enumerate(batch_pos):
vol[i0, j0, :] = yp[b]
batch_X.clear(); batch_pos.clear()
if k % (nI*nX//10 or 1) == 0:
print(f"Progress: {100.0*k/(nI*nX):.1f}%")
# 5) Lưu output
os.makedirs(os.path.dirname(OUT_PATH), exist_ok=True)
np.savez_compressed(
OUT_PATH,
vol=vol, # porosity scaled [0,1]
ilines=ilines,
xlines=xlines,
times_ms=times_win,
y_lo=y_lo, y_hi=y_hi,
patch_radius=PATCH_RADIUS
)
print("Saved:", OUT_PATH)
if __name__ == "__main__":
main()

378
test 2/prepare_data.py Normal file
View File

@@ -0,0 +1,378 @@
# save as prepare_f3_data.py
import os
import segyio
import lasio
import numpy as np
from scipy.interpolate import interp1d
from scipy import integrate
# ------------ USER CONFIG ------------
SEGY_PATH = "C:\\Users\\PC\\Documents\\Thesis\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\F3_entire.segy"
WELL_LAS_PATHS = {
"F03-4": "C:\\Users\\PC\\Documents\\Thesis\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F03-4_logs.las",
"F02-1": "C:\\Users\\PC\\Documents\\Thesis\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F02-1_logs.las",
"F06-1": "C:\\Users\\PC\\Documents\\Thesis\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F06-1_logs.las",
}
# If you know inline/xline for each well, fill here; otherwise set to None
WELL_ILINE_XLINE = {
"F03-4": (362, 821),
"F02-1": (418, 608),
"F06-1": (283, 842),
}
OUT_DIR = "outputs"
TIME_WINDOW_MS = (600, 1100) # window in ms
TARGET_DT_MS = 4.0 # seismic sampling interval in ms
PATCH_RADIUS = 1 # =1 -> patch 3x3; =2 -> 5x5, ...
# -------------------------------------
os.makedirs(OUT_DIR, exist_ok=True)
def read_segy(segy_path):
f = segyio.open(segy_path, "r", ignore_geometry=False)
cube = segyio.tools.cube(f) # shape: [iline, xline, samples]
ilines = np.array(f.ilines)
xlines = np.array(f.xlines)
times = np.array(f.samples) # sample times in ms (seg-y sample index info)
return f, cube, ilines, xlines, times
def read_las(las_path):
las = lasio.read(las_path)
return las
def compute_twt_from_dt(las):
"""
Tính TWT (ms) từ log DT trong LAS.
Trả về: depth (m), twt_two_way_ms, dt_raw, unit
"""
# --- Depth ---
if "DEPTH" in las.keys():
depth = np.asarray(las["DEPTH"])
elif "DEPT" in las.keys():
depth = np.asarray(las["DEPT"])
else:
raise ValueError("LAS file has no DEPTH/DEPT column")
# --- Tìm curve DT ---
# Ưu tiên mnemonic "DT", "DTC", "DTS"...
dt_candidates = [k for k in las.keys() if "DT" in k.upper()]
if not dt_candidates:
# fallback: quét theo description
dt_candidates = [c.mnemonic for c in las.curves if "SONIC" in (c.descr or "").upper()]
if not dt_candidates:
raise ValueError("No DT (sonic) curve found in LAS")
dt_curve = dt_candidates[0]
dt_raw = np.asarray(las[dt_curve], dtype=float)
# --- Xử lý giá trị null ---
dt_raw[dt_raw < 0] = np.nan
if np.all(np.isnan(dt_raw)):
raise ValueError(f"All DT values are NaN in {dt_curve}")
# Nội suy lấp chỗ NaN
mask = ~np.isnan(dt_raw)
dt_raw = np.interp(np.arange(len(dt_raw)), np.where(mask)[0], dt_raw[mask])
# --- Đoán đơn vị ---
unit = None
for c in las.curves:
if c.mnemonic == dt_curve:
unit = (c.unit or "").lower()
break
mean_dt = np.nanmean(dt_raw)
if "us/ft" in unit:
conv = 1e-6 / 0.3048 # us/ft -> s/m
elif "us/m" in unit:
conv = 1e-6 # us/m -> s/m
elif "ms/m" in unit:
conv = 1e-3 # ms/m -> s/m
else:
# Heuristic nếu unit không rõ
if mean_dt > 1000: # rất lớn => us/m
conv = 1e-6
unit = "us/m"
elif 40 < mean_dt < 200: # kiểu ~100 => us/ft
conv = 1e-6 / 0.3048
unit = "us/ft"
else:
conv = 1e-6
unit = "us/m"
# --- Tính TWT ---
dt_s_per_m = dt_raw * conv
# One-way travel time bằng tích phân
twt_oneway_s = integrate.cumulative_trapezoid(dt_s_per_m, depth, initial=0.0)
twt_two_way_ms = 2.0 * twt_oneway_s * 1000.0
return depth, twt_two_way_ms, dt_raw, unit
"""
Compute TWT (ms) from DT (sonic) log in LAS.
Handles typical unit conventions: DT in us/ft, us/m, or ms/m.
Returns arrays: twt_ms (in ms), depth (as in LAS), and dt_raw.
"""
dt_raw = las[dt_keys[0]].astype(float)
# Replace null values (e.g., -999.25) with NaN
dt_raw[dt_raw < 0] = np.nan
# Fill NaN by interpolation
mask = ~np.isnan(dt_raw)
dt_raw = np.interp(np.arange(len(dt_raw)), np.where(mask)[0], dt_raw[mask])
# Depth array from LAS
if "DEPTH" in las.keys():
depth = las["DEPTH"]
elif "DEPT" in las.keys():
depth = las["DEPT"]
else:
raise ValueError("LAS file has no DEPTH column")
# find DT curve name (common mnemonics)
dt_keys = [k for k in las.keys() if k.upper() in ("DT","DTS","DTCO","DTM","DTF")]
if not dt_keys:
# fallback: look for curve called 'DT' in curves by description
dt_keys = [c.mnemonic for c in las.curves if "DT" in c.mnemonic.upper() or "SONIC" in (c.descr or "").upper()]
if not dt_keys:
raise ValueError("No DT/sonic curve found in LAS")
dt_raw = las[dt_keys[0]] # numeric values
# Try to infer units from curve header (las.curves metadata)
# lasio stores unit in las.curves.units (may be '', 'us/ft', etc.)
unit = None
for c in las.curves:
if c.mnemonic == dt_keys[0]:
unit = c.unit or c.descr or ""
break
unit = (unit or "").lower()
# Common cases:
# - DT in microseconds per foot (us/ft)
# - DT in microseconds per meter (us/m)
# - DT in ms/m (rare)
# We'll convert to seconds per meter then to two-way-time (ms).
# If DT is us/ft: convert to s/m -> dt_usft * (1e-6 s/us) * (1/0.3048 ft/m)
# If DT is us/m: dt_usperm * 1e-6 s/us
# Finally, one-way travel time through layer = integral(dt) along depth (s)
# Two-way time = 2 * cumulative_one_way_time (s) -> *1000 to ms
# Heuristic for unit detection:
if "us/ft" in unit or "us/ ft" in unit or "/ft" in unit and "us" in unit:
conv = 1e-6 / 0.3048 # us/ft -> s/m
elif "us/m" in unit or "us / m" in unit or (np.nanmean(dt_raw) > 100 and np.nanmean(dt_raw) < 20000):
# if values look large (hundreds -> could be us/m)
conv = 1e-6 # us/m -> s/m
elif "ms" in unit and "/m" in unit:
conv = 1e-3 # ms/m -> s/m
else:
# final fallback: inspect magnitudes (typical dt_us/ft ~ 50-250, us/m ~ 200-8000)
mean_dt = np.nanmean(dt_raw)
if mean_dt > 1000:
# likely us/m
conv = 1e-6
elif mean_dt > 50 and mean_dt < 1000:
# ambiguous; assume us/ft (common)
conv = 1e-6 / 0.3048
else:
conv = 1e-6 / 0.3048
# convert dt_raw -> seconds per meter
dt_s_per_m = dt_raw * conv # s/m
# compute cumulative one-way travel time (s) by trapezoidal integration over depth
# t_one_way(depth[i]) = integral from top to depth[i] of dt_s_per_m(z) dz
# use cumulative trapezoidal integration
twt_oneway_s = integrate.cumulative_trapezoid(dt_s_per_m, depth, initial=0.0)
twt_two_way_ms = 2.0 * twt_oneway_s * 1000.0 # ms
return depth, twt_two_way_ms, dt_raw, unit
def resample_log_to_seismic(twt_ms, log_values, seismic_times_ms):
"""
Interpolate log_values defined at twt_ms -> sampled at seismic_times_ms
Returns array of same length as seismic_times_ms (nan for out-of-range).
"""
interp = interp1d(twt_ms, log_values, bounds_error=False, fill_value=np.nan)
return interp(seismic_times_ms)
def get_well_inline_xline_from_segy(segy_f, well_las):
"""
Attempt to read well XY coordinate from LAS and find nearest inline/xline in SEGY headers.
Returns (iline, xline) or None if cannot find.
"""
# try standard LAS header locations
header = well_las.well
# heuristics for X,Y fields
x_keys = [k for k in header.keys() if "x" in k.lower()]
y_keys = [k for k in header.keys() if "y" in k.lower()]
x = None; y = None
for k in x_keys:
try:
x = float(header[k])
break
except Exception:
continue
for k in y_keys:
try:
y = float(header[k])
break
except Exception:
continue
if x is None or y is None:
return None
# extract trace headers for geometry from segy
# collect all traces' inline/xline and their coordinates
# segyio.header gives geometry for each trace
coords = []
ilines = []
xlines = []
for tr in range(segy_f.tracecount):
try:
ih = segyio.tracefield.segyio_tracefield(segy_f, tr)
except Exception:
pass
# easier: use segyio.xlines/ilines arrays and map by index (we'll approximate)
# Here we'll simply return None to avoid overcomplication - user can supply inline/xline
return None
def find_nearest_iline_xline(ilines_arr, xlines_arr, iline_val=None, xline_val=None):
"""
If user provided inline/xline numeric values, snap to closest available indices.
"""
if iline_val is None or xline_val is None:
return None
il_idx = int( np.argmin(np.abs(ilines_arr - iline_val)))
xl_idx = int(np.argmin(np.abs(xlines_arr - xline_val)))
return il_idx, xl_idx
def extract_trace_at_well(cube, ilines_arr, xlines_arr, well_name, well_las, user_supply=None):
"""
Return seismic_trace (1D array) aligned to seismic times, and resampled phi (porosity) aligned same times.
user_supply: either None or tuple (iline_val, xline_val)
"""
# compute TWT from DT
depth, twt_ms, dt_raw, dt_unit = compute_twt_from_dt(well_las)
print(f"[{well_name}] DT unit heuristic: '{dt_unit}', mean DT value {np.nanmean(dt_raw):.2f}")
# get porosity curve
# possible curve names: PHIE, PHI, PORO, POR
phi_keys = [k for k in well_las.keys() if k.upper() in ("PHIE","PHI","PORO","POR","PHI_E")]
if not phi_keys:
# try scanning curves by description
phi_keys = [c.mnemonic for c in well_las.curves if "poro" in (c.descr or "").lower() or "phi" in c.mnemonic.lower()]
if not phi_keys:
raise ValueError(f"No porosity curve found in LAS for {well_name}")
phi_raw = well_las[phi_keys[0]]
# read seismic sampling times from global (will be passed later). We don't have it here,
# so caller should pass seismic times or we will read segy externally.
return depth, twt_ms, phi_raw, dt_raw
def main():
# 1) Read SEGY
segy_f, cube, ilines, xlines, seismic_times = read_segy(SEGY_PATH)
print("Seismic shape:", cube.shape)
print("Number of time samples:", seismic_times.shape[0])
# build seismic_times array in ms; segyio.samples usually is floats in ms already
seismic_times_ms = seismic_times # already ms
# Loop wells -> prepare traces and resampled porosity
saved = {}
for well_name, las_path in WELL_LAS_PATHS.items():
print(f"\nProcessing well {well_name} ...")
las = read_las(las_path)
# compute TWT and porosity
depth, twt_ms, phi_raw, dt_raw = None, None, None, None
try:
depth, twt_ms, dt_raw, dt_unit = compute_twt_from_dt(las)
print(f" -> computed TWT range: {twt_ms.min():.1f} ms to {twt_ms.max():.1f} ms")
except Exception as e:
print(" Error computing TWT from DT:", e)
continue
# get porosity curve name & values
phi_keys = [k for k in las.keys() if k.upper() in ("PHIE","PHI","PORO","POR","PHI_E")]
if not phi_keys:
phi_keys = [c.mnemonic for c in las.curves if "poro" in (c.descr or "").lower() or "phi" in c.mnemonic.lower()]
phi_raw = las[phi_keys[0]]
print(f" -> using porosity curve '{phi_keys[0]}'")
# 2) resample porosity to seismic_times_ms
phi_resampled = resample_log_to_seismic(twt_ms, phi_raw, seismic_times_ms) # nan outside
# 3) select TIME WINDOW
t0, t1 = TIME_WINDOW_MS
mask = (seismic_times_ms >= t0) & (seismic_times_ms <= t1)
phi_win = phi_resampled[mask]
times_win = seismic_times_ms[mask]
print(f" -> window samples: {times_win.shape[0]} (from {t0} to {t1} ms)")
# 4) find inline/xline location for well
user_il_xl = WELL_ILINE_XLINE.get(well_name)
ix = find_nearest_iline_xline(ilines, xlines, *(user_il_xl or (None, None)))
if ix is None:
# fallback: ask segy headers for closest trace via well XY (not implemented robustly here)
print(" -> No inline/xline provided for well; please provide WELL_ILINE_XLINE in config.")
# For now skip extracting seismic trace
seismic_trace = None
else:
il_idx, xl_idx = ix
# --- 1) Trace tại chính vị trí giếng ---
seismic_trace_full = cube[il_idx, xl_idx, :] # (samples,)
seismic_trace_win = seismic_trace_full[mask] # (L_window,)
seismic_trace = seismic_trace_win
# --- 2) Patch không gian (3x3 nếu PATCH_RADIUS = 1) ---
if PATCH_RADIUS is not None and PATCH_RADIUS >= 1:
chans = []
for di in range(-PATCH_RADIUS, PATCH_RADIUS + 1):
for dx in range(-PATCH_RADIUS, PATCH_RADIUS + 1):
ii = np.clip(il_idx + di, 0, cube.shape[0] - 1)
xx = np.clip(xl_idx + dx, 0, cube.shape[1] - 1)
tr_full = cube[ii, xx, :] # (samples,)
chans.append(tr_full[mask]) # cắt theo cửa sổ thời gian
seismic_patch = np.stack(chans, axis=0) # (C, L_window), với C = (2R+1)^2
print(f" -> extracted seismic PATCH: radius={PATCH_RADIUS}, shape={seismic_patch.shape}")
else:
seismic_patch = None
print(f" -> extracted seismic trace at iline {ilines[il_idx]}, xline {xlines[xl_idx]}")
# store
saved[well_name] = {
"seismic_trace": seismic_trace, # (L_window,) hoặc None
"seismic_patch": seismic_patch, # (C, L_window) hoặc None <-- THÊM DÒNG NÀY
"seismic_times_ms": times_win,
"porosity_resampled": phi_win,
"twt_full_ms": twt_ms,
"depth": depth,
"dt_raw": dt_raw,
}
# Save outputs to .npz for later training
out_path = os.path.join(OUT_DIR, "f3_wells_dataset.npz")
np.savez_compressed(out_path, **saved)
print("\nSaved dataset to", out_path)
print("Done.")
if __name__ == "__main__":
main()

26
test 2/qc_plot.py Normal file
View File

@@ -0,0 +1,26 @@
import numpy as np
import matplotlib.pyplot as plt
D = np.load("outputs/f3_wells_dataset.npz", allow_pickle=True)
def plot_well(name):
d = D[name].item()
t = d["seismic_times_ms"]
phi = d["porosity_resampled"]
tr = d["seismic_trace"]
plt.figure(figsize=(8,4))
if tr is not None:
trn = tr / (np.nanmax(np.abs(tr)) + 1e-8)
plt.plot(trn, t, label="Seismic (norm)")
plt.plot(phi, t, label="Porosity (PHIE)")
plt.gca().invert_yaxis()
plt.xlabel("Value")
plt.ylabel("TWT (ms)")
plt.title(f"{name}: 600–1100 ms")
plt.legend()
plt.tight_layout()
plt.show()
for w in ["F03-4","F02-1","F06-1"]:
plot_well(w)

36
test 2/read_npz_output.py Normal file
View File

@@ -0,0 +1,36 @@
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from scipy.stats import pearsonr
# === Load file ===
data = np.load(r"C:\Users\PC\Documents\Thesis\outputs\open_loop_patch_preds_F06-1_v2.npz", allow_pickle=True)
print("Keys trong file:", data.files)
# === Giả định các key là ===
# y_true: porosity từ well-logging
# y_pred: porosity dự đoán
# times_ms: trục thời gian
y_true = data['y_true']
y_pred = data['y_pred']
times = data['times_ms'] if 'times_ms' in data.files else np.arange(len(y_true))
# === Tính toán ===
mse = mean_squared_error(y_true, y_pred)
pcc, _ = pearsonr(y_true, y_pred)
print(f"[🔍] MSE: {mse:.4f}")
print(f"[🔍] PCC: {pcc:.4f}")
# === Vẽ biểu đồ ===
plt.figure(figsize=(10,5))
plt.plot(times, y_true, label='True Porosity', linewidth=2)
plt.plot(times, y_pred, label='Predicted Porosity', linestyle='--')
plt.xlabel("Time (ms)")
plt.ylabel("Porosity")
plt.title(f"F06-1 Porosity Comparison\nMSE={mse:.4f} | PCC={pcc:.4f}")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
plt.savefig(r"C:\Users\PC\Documents\Thesis\outputs\porosity_comparison_F06-1.png")

View File

@@ -0,0 +1,443 @@
import os
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
# ----------------------------
# CẤU HÌNH CƠ BẢN
# ----------------------------
NPZ_PATH = "C:\\Users\\PC\\Documents\\Thesis\\outputs\\f3_wells_dataset.npz" # file đã tạo bằng prepare_f3_data.py
OUTPUT_DIR = "outputs"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# ----------------------------
# SIÊU THAM SỐ
# ----------------------------
EPOCHS = 1200
LR = 5e-3
WEIGHT_DECAY = 0.0
BATCH_TRAIN = 2
P_DROPOUT = 0.05
D_CHANNELS = 64
GRAD_CLIP = 5.0
# Trọng số loss
LAMBDA_PCC = 0.60 # (1 - PCC)
LAMBDA_GRAD = 0.05 # gradient loss
LAMBDA_SHAPE = 0.10 # shape loss (MSE giữa các chuỗi đã z-score từng batch)
LAMBDA_VAR = 0.10 # khớp độ lệch chuẩn giữa pred và true
LAMBDA_XCORR = 0.20 # cross-correlation loss (tự align lệch pha nhỏ)
# Clip porosity về [0, 0.4] trước khi scale (áp dụng trước khi z-score)
Y_CLIP_MIN = 0.0
Y_CLIP_MAX = 0.4
# Align pha: giới hạn lag tối đa (4 ms/sample)
ALIGN_MAX_LAG = 16 # ±64 ms
# Random seed
SEED = 42
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# ----------------------------
# HÀM TIỆN ÍCH
# ----------------------------
def nan_to_num_1d(a: np.ndarray) -> np.ndarray:
"""Nội suy tuyến tính thay NaN theo chỉ số; nếu toàn NaN -> vector 0."""
a = a.astype(float, copy=True)
idx = np.where(~np.isnan(a))[0]
if len(idx) == 0:
return np.zeros_like(a)
return np.interp(np.arange(len(a)), idx, a[idx])
def zscore_1d(x: np.ndarray) -> np.ndarray:
"""Z-score cho 1 trace/kênh."""
mu = np.nanmean(x)
sd = np.nanstd(x) + 1e-8
return (x - mu) / sd
def zscore_ch(X: np.ndarray) -> np.ndarray:
"""Z-score theo từng kênh (X: (C, L))."""
X = X.copy().astype(float)
for c in range(X.shape[0]):
X[c] = zscore_1d(nan_to_num_1d(X[c]))
return X
def estimate_lag_multi(X_patch: np.ndarray, y: np.ndarray, max_lag: int = 8, use_abs: bool = True) -> int:
"""
Ước lượng lag robust cho patch nhiều kênh X_patch (C,L) với y (L).
- Chuẩn hoá z-score theo từng chuỗi
- Thử cả x và -x để tránh vấn đề đảo cực
- Chọn lag tối ưu theo |PCC| (mặc định)
"""
C, L = X_patch.shape
Xm = X_patch.copy().astype(float)
for c in range(C):
mu, sd = np.nanmean(Xm[c]), np.nanstd(Xm[c]) + 1e-8
Xm[c] = (Xm[c] - mu) / sd
x0 = np.nanmean(Xm, axis=0)
y0 = (y - np.nanmean(y)) / (np.nanstd(y) + 1e-8)
best_lag, best_score = 0, -1.0
for sgn in (+1.0, -1.0): # thử đảo cực
xs = x0 * sgn
for lag in range(-max_lag, max_lag + 1):
if lag < 0:
xs_, ys_ = xs[-lag:], y0[:len(y0)+lag]
elif lag > 0:
xs_, ys_ = xs[:len(xs)-lag], y0[lag:]
else:
xs_, ys_ = xs, y0
if len(xs_) < 16:
continue
num = float((xs_ * ys_).sum())
den = float(np.sqrt((xs_**2).sum() * (ys_**2).sum()) + 1e-8)
pcc = num / den
score = abs(pcc) if use_abs else pcc
if score > best_score:
best_score, best_lag = score, lag
return best_lag
def shift_array(a: np.ndarray, lag: int) -> np.ndarray:
"""Dịch mảng a theo lag (dương = dịch xuống theo thời gian)."""
if lag == 0:
return a
if lag > 0:
return np.concatenate([np.full(lag, np.nan), a[:-lag]])
else:
lag = -lag
return np.concatenate([a[lag:], np.full(lag, np.nan)])
def best_shift_metrics(yp: np.ndarray, yt: np.ndarray, max_lag: int = 16):
"""
Tính PCC/MSE tốt nhất sau khi thử dịch yp so với yt trong khoảng [-max_lag, max_lag].
Giả định cả hai đang ở cùng thang (z-score hoặc thang thật).
"""
best = {"lag": 0, "mse": np.inf, "pcc": -1.0}
L = min(len(yp), len(yt))
yp = yp[:L]; yt = yt[:L]
for lag in range(-max_lag, max_lag + 1):
if lag < 0:
yph, yth = yp[-lag:], yt[:L+lag]
elif lag > 0:
yph, yth = yp[:L-lag], yt[lag:]
else:
yph, yth = yp, yt
if len(yph) < 16:
continue
mse = float(np.nanmean((yph - yth) ** 2))
yph0, yth0 = yph - yph.mean(), yth - yth.mean()
pcc = float((yph0 * yth0).sum() / (np.sqrt((yph0**2).sum()) * np.sqrt((yth0**2).sum()) + 1e-8))
if pcc > best["pcc"]:
best = {"lag": lag, "mse": mse, "pcc": pcc}
return best
# ----------------------------
# DATASET (toàn chuỗi)
# ----------------------------
class FullSeqDS(Dataset):
"""
X: (N, C, L) — C = số kênh (patch), L = số mẫu theo thời gian.
Y: (N, L) — porosity (z-score).
Trả về tensor X: (C, L), Y: (1, L) phù hợp Conv1d.
"""
def __init__(self, X: np.ndarray, Y: np.ndarray):
self.X = torch.tensor(X, dtype=torch.float32) # (N,C,L)
self.Y = torch.tensor(Y, dtype=torch.float32)[:, None, :] # (N,1,L)
def __len__(self):
return self.X.shape[0]
def __getitem__(self, i):
return self.X[i], self.Y[i]
# ----------------------------
# MÔ HÌNH: CNN (dilated) + GRU(2 tầng) + skip head 1x1
# ----------------------------
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):
# x: (B, C, L)
h = self.cnn(x) # (B, d, L)
h2, _ = self.gru(h.transpose(1, 2)) # (B, L, 2d)
y_main = self.head(h2.transpose(1, 2)) # (B, 1, L)
y_skip = self.head_skip(x) # (B, 1, L)
return y_main + y_skip + self.bias.view(1, 1, 1)
# ----------------------------
# LOSSES
# ----------------------------
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)
pcc = (x * y).mean(dim=1) # KHÔNG abs -> phạt anti-correlation
return 1.0 - pcc.mean()
def grad_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""Khớp hình dáng (đạo hàm bậc 1 theo thời gian)."""
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, eps: float = 1e-8) -> 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] (mềm hóa lệch pha)."""
x = pred.squeeze(1); y = target.squeeze(1)
B, L = x.shape; 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()
# ----------------------------
# LOAD & CHUẨN BỊ DỮ LIỆU
# ----------------------------
def fetch_item(D, well_name: str):
"""Lấy (time, X (C,L), y (L)). Ưu tiên seismic_patch; nếu không có thì dùng seismic_trace 1 kênh."""
d = D[well_name].item()
t = d["seismic_times_ms"] # (L,)
y = d["porosity_resampled"] # (L,)
if "seismic_patch" in d and d["seismic_patch"] is not None:
X = d["seismic_patch"] # (C, L)
else:
X = d["seismic_trace"][None, :] # (1, L)
return t, X, y
def main():
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Đọc NPZ
D = np.load(NPZ_PATH, allow_pickle=True)
# Lấy dữ liệu 3 giếng
t_F34, X_F34, y_F34 = fetch_item(D, "F03-4")
t_F21, X_F21, y_F21 = fetch_item(D, "F02-1")
t_F61, X_F61, y_F61 = fetch_item(D, "F06-1")
# Kiểm tra kích thước
assert X_F34.ndim == 2 and X_F21.ndim == 2 and X_F61.ndim == 2, "X phải có dạng (C, L)."
C = X_F34.shape[0]
assert X_F21.shape[0] == C and X_F61.shape[0] == C, "Số kênh (C) giữa các giếng phải giống nhau."
L = X_F34.shape[1]
assert X_F21.shape[1] == L and X_F61.shape[1] == L, "Độ dài thời gian (L) giữa các giếng phải giống nhau."
# Xử lý NaN và chuẩn hoá cho X (theo kênh)
X_F34 = zscore_ch(X_F34)
X_F21 = zscore_ch(X_F21)
X_F61 = zscore_ch(X_F61)
# Xử lý y: NaN -> nội suy; clip -> z-score theo TRAIN
y_F34 = nan_to_num_1d(y_F34)
y_F21 = nan_to_num_1d(y_F21)
y_F61 = nan_to_num_1d(y_F61)
y_F34 = np.clip(y_F34, Y_CLIP_MIN, Y_CLIP_MAX)
y_F21 = np.clip(y_F21, Y_CLIP_MIN, Y_CLIP_MAX)
y_F61 = np.clip(y_F61, Y_CLIP_MIN, Y_CLIP_MAX)
# Z-score label theo THỐNG KÊ TRAIN
y_train_concat = np.concatenate([y_F34, y_F21], axis=0)
y_mu = float(np.nanmean(y_train_concat))
y_std = float(np.nanstd(y_train_concat) + 1e-8)
def zscore_y(y, mu, sd): return (y - mu) / sd
y_F34_sc = zscore_y(y_F34, y_mu, y_std)
y_F21_sc = zscore_y(y_F21, y_mu, y_std)
y_F61_sc = zscore_y(y_F61, y_mu, y_std)
# Align pha CHỈ cho TRAIN
lag_F34 = estimate_lag_multi(X_F34, y_F34_sc, ALIGN_MAX_LAG)
lag_F21 = estimate_lag_multi(X_F21, y_F21_sc, ALIGN_MAX_LAG)
lag_F61 = estimate_lag_multi(X_F61, y_F61_sc, ALIGN_MAX_LAG) # chỉ để in báo cáo
y_F34_sc = nan_to_num_1d(shift_array(y_F34_sc, lag_F34))
y_F21_sc = nan_to_num_1d(shift_array(y_F21_sc, lag_F21))
# Test giữ nguyên để chẩn đoán lệch pha:
# y_F61_sc = nan_to_num_1d(shift_array(y_F61_sc, lag_F61))
print(f"Lags (samples) -> F03-4:{lag_F34} F02-1:{lag_F21} F06-1:{lag_F61}")
# Xây tập train/val/test
X_train = np.stack([X_F34, X_F21], axis=0) # (2, C, L)
Y_train = np.stack([y_F34_sc, y_F21_sc], axis=0) # (2, L)
X_val = np.expand_dims(X_F21, axis=0) # (1, C, L)
Y_val = np.expand_dims(y_F21_sc, axis=0) # (1, L)
X_test = X_F61 # (C, L)
y_test = y_F61_sc
t_test = t_F61
# Dataloaders
dl_tr = DataLoader(FullSeqDS(X_train, Y_train), batch_size=BATCH_TRAIN, shuffle=True)
dl_val = DataLoader(FullSeqDS(X_val, Y_val), batch_size=1, shuffle=False)
# Model, optimizer, scheduler
model = CNNGRU(in_ch=C, d=D_CHANNELS, pdrop=P_DROPOUT).to(DEVICE)
loss_reg = nn.SmoothL1Loss(beta=0.02)
opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode='min', factor=0.5, patience=50, verbose=True)
best_val = 1e9
best_path = os.path.join(OUTPUT_DIR, "open_loop_patch_best_v2.pt")
# ----------------------------
# TRAINING LOOP
# ----------------------------
for ep in range(1, EPOCHS + 1):
# ----- TRAIN -----
model.train()
tr_sum = 0.0
n_tr = 0
for xb, yb in dl_tr:
xb, yb = xb.to(DEVICE), yb.to(DEVICE) # xb: (B,C,L) yb: (B,1,L)
opt.zero_grad()
pred = model(xb) # (B,1,L)
# tiny noise vài epoch đầu để phá đối xứng
if ep <= 50:
pred = pred + 0.01 * torch.randn_like(pred)
loss = (
loss_reg(pred, yb)
+ LAMBDA_PCC * pcc_loss(pred, yb)
+ LAMBDA_GRAD * grad_loss(pred, yb)
+ LAMBDA_SHAPE * shape_loss(pred, yb)
+ LAMBDA_VAR * var_match_loss(pred, yb)
+ LAMBDA_XCORR * crosscorr_loss(pred, yb, max_shift=8)
)
loss.backward()
if GRAD_CLIP is not None:
nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)
opt.step()
tr_sum += loss.item() * xb.size(0)
n_tr += xb.size(0)
tr_loss = tr_sum / max(n_tr, 1)
# ----- VAL -----
model.eval()
val_sum = 0.0
n_val = 0
with torch.no_grad():
for xb, yb in dl_val:
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
pred = model(xb)
loss = (
loss_reg(pred, yb)
+ LAMBDA_PCC * pcc_loss(pred, yb)
+ LAMBDA_GRAD * grad_loss(pred, yb)
+ LAMBDA_SHAPE * shape_loss(pred, yb)
+ LAMBDA_VAR * var_match_loss(pred, yb)
+ LAMBDA_XCORR * crosscorr_loss(pred, yb, max_shift=8)
)
val_sum += loss.item() * xb.size(0)
n_val += xb.size(0)
val_loss = val_sum / max(n_val, 1)
scheduler.step(val_loss)
if val_loss < best_val:
best_val = val_loss
torch.save(model.state_dict(), best_path)
if ep % 50 == 0 or ep == 1:
with torch.no_grad():
std_pred = pred.std().item()
std_true = yb.std().item()
print(f"Epoch {ep:04d} | train {tr_loss:.4f} | val {val_loss:.4f} | best {best_val:.4f} | std_pred {std_pred:.4f} | std_true {std_true:.4f}")
# ----------------------------
# EVALUATION (F06-1)
# ----------------------------
model.load_state_dict(torch.load(best_path, map_location=DEVICE))
model.eval()
with torch.no_grad():
xt = torch.tensor(X_test, dtype=torch.float32)[None, ...].to(DEVICE) # (1,C,L)
yp = model(xt).cpu().numpy()[0, 0, :] # (L,)
# Cắt khớp
Lm = min(len(yp), len(y_test))
yp = yp[:Lm]
yt = y_test[:Lm] # Z-score
# Metrics trên Z-SCORE
mse_z = float(np.nanmean((yp - yt) ** 2))
yt0 = yt - yt.mean(); yp0 = yp - yp.mean()
pcc_z = float((yt0 * yp0).sum() / (np.sqrt((yt0**2).sum()) * np.sqrt((yp0**2).sum()) + 1e-8))
print(f"[TEST F06-1] (patch C={C}) MSE_z={mse_z:.4f} | PCC_z={pcc_z:.3f}")
# Best-shift diagnostic (Z-score)
best = best_shift_metrics(yp, yt, max_lag=ALIGN_MAX_LAG)
print(f"[TEST F06-1 best-shift Z] lag={best['lag']} | MSE_z={best['mse']:.4f} | PCC_z={best['pcc']:.3f}")
# Giải chuẩn về thang porosity thật
yp_real = yp * y_std + y_mu
yt_real = yt * y_std + y_mu
mse_real = float(np.nanmean((yp_real - yt_real) ** 2))
yt_r0 = yt_real - yt_real.mean(); yp_r0 = yp_real - yp_real.mean()
pcc_real = float((yt_r0 * yp_r0).sum() / (np.sqrt((yt_r0**2).sum()) * np.sqrt((yp_r0**2).sum()) + 1e-8))
print(f"[TEST F06-1 REAL] MSE={mse_real:.4f} | PCC={pcc_real:.3f}")
best_real = best_shift_metrics(yp_real, yt_real, max_lag=ALIGN_MAX_LAG)
print(f"[TEST F06-1 best-shift REAL] lag={best_real['lag']} | MSE={best_real['mse']:.4f} | PCC={best_real['pcc']:.3f}")
# Lưu dự đoán + meta
out_pred = os.path.join(OUTPUT_DIR, "open_loop_patch_preds_F06-1_v2.npz")
np.savez_compressed(
out_pred,
time=t_test[:Lm],
y_true_z=yt, y_pred_z=yp,
y_true=yt_real, y_pred=yp_real,
y_mu=y_mu, y_std=y_std, C=C,
lags=(lag_F34, lag_F21, lag_F61),
best_shift_z=best['lag'], best_shift_real=best_real['lag']
)
print(f"Saved predictions to {out_pred}")
if __name__ == "__main__":
main()