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()