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

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)}")