Complete P3 F3 evaluation and Windows execution
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>
This commit is contained in:
378
code_thesis/prepare_data.py
Normal file
378
code_thesis/prepare_data.py
Normal 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()
|
||||
Reference in New Issue
Block a user