Implement the frozen F3 protocol, nested LOWO, posterior label banks, ablations, diagnostics, checkpoint validation and full-volume inference. Record the negative G-C result: improvement at 1/4 wells, coverage80 52.38% and coverage90 60.91%, with unchanged thresholds and historical P2 results. Add native Windows logging, the RTX 3060 environment lock, detached runs, and an audited dashboard-lock recovery that preserves frozen scientific code. Update report.html, the plan and agent guidance with completed P3 status. Archive thesis sources under code_thesis with identical Git blobs and record the original-output audit without committing large data or model artifacts. Validation: 129 tests passed, 13 skipped; CUDA end-to-end smoke passed; completion audit verified 1,320 checkpoint/prediction pairs, 28 registration bundles and all 649 interior volume inlines. Scripts 04 and 09 were not rerun. Co-authored-by: Codex <codex@openai.com>
164 lines
6.4 KiB
Python
164 lines
6.4 KiB
Python
# 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()
|
||
|