"""Đọc dữ liệu Volve: horizon xuất từ OpenWorks, well picks (cột cố định) và checkshot VSP. Quy ước: MD tính từ RKB (54.9 m trên MSL), TVDSS và TWT tính từ MSL, toạ độ ED50 / UTM 31N. Lưới horizon là lưới ST10010 (12.5 × 12.5 m). Các file ghi ST0202 cũng đánh số IL/XL theo lưới này (affine lệch < 0.11 m trong ROI giếng). """ from __future__ import annotations from dataclasses import dataclass from functools import cached_property from pathlib import Path import numpy as np import pandas as pd from ml_porosity.data.geometry import SurveyGeometry VOLVE_RKB_M = 54.9 VOLVE_EPSG = 23031 # 9 giếng có PHIF (D3) và F-15 A (không có PHIF nhưng có VSP checkshot), như ROI ở docs/research/volve-inventory.md VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1 C", "NO 15/9-F-11 A", "NO 15/9-F-11 B", "NO 15/9-F-11 T2", "NO 15/9-F-12", "NO 15/9-F-15 A", "NO 15/9-F-15 D") @dataclass(frozen=True) class Horizon: survey: str name: str domain: str # "TIME" (TWT ms) hoặc "DEPTH" (m) il: np.ndarray xl: np.ndarray x: np.ndarray y: np.ndarray z: np.ndarray def geometry(self) -> SurveyGeometry: return SurveyGeometry.from_points(self.il, self.xl, self.x, self.y, epsg=VOLVE_EPSG) @cached_property def lut(self) -> dict[tuple[int, int], float]: return {(int(i), int(j)): float(v) for i, j, v in zip(self.il, self.xl, self.z)} def at(self, il: float, xl: float, radius: int = 1) -> float: """Trung vị z của các nút trong cửa sổ (2·radius+1)² quanh bin gần nhất; NaN nếu không có nút.""" i0, j0 = int(np.rint(il)), int(np.rint(xl)) vals = [self.lut[k] for di in range(-radius, radius + 1) for dj in range(-radius, radius + 1) if (k := (i0 + di, j0 + dj)) in self.lut] return float(np.median(vals)) if vals else float("nan") def read_horizon(path: str | Path) -> Horizon: """File `*.dat` dạng: các dòng chú thích `#`, 4 dòng metadata (survey, tên, người minh giải, miền), sau đó mỗi dòng `IL,XL,X,Y,Z`. Một số file để trống dòng survey (chỉ có `=`).""" meta, rows = [], [] with open(path, errors="replace") as fh: for line in fh: if line.startswith("#") or not line.strip(): continue parts = line.strip().split(",") if len(parts) == 5: try: rows.append([float(v) for v in parts]) continue except ValueError: pass meta.append(line.strip()) a = np.asarray(rows) survey, name, _, domain = (meta + [""] * 4)[:4] return Horizon(survey=survey, name=name, domain=domain, il=a[:, 0].astype(int), xl=a[:, 1].astype(int), x=a[:, 2], y=a[:, 3], z=a[:, 4]) PICK_COLUMNS = {"Well name": "well", "Surface name": "surface", "Obs#": "obs", "Qlf": "qlf", "MD": "md", "TVD": "tvd", "TVDSS": "tvdss", "TWT": "twt_ms", "Dip": "dip", "Azi": "azi", "Easting": "x", "Northing": "y", "Intrp": "interpreter"} def read_well_picks(path: str | Path) -> pd.DataFrame: """`Well_picks_Volve_v1.dat`: mỗi giếng có một dòng tiêu đề và một dòng gạch `---` xác định độ rộng cột. Qlf: ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached.""" lines = Path(path).read_text(errors="replace").splitlines() spans, rows = None, [] for i, ln in enumerate(lines): if ln.strip().startswith("Well name") and i + 1 < len(lines) and lines[i + 1].strip().startswith("---"): dash = lines[i + 1] spans, j = [], 0 while j < len(dash): if dash[j] == "-": k = j while k < len(dash) and dash[k] == "-": k += 1 spans.append((j, k, ln[j:k + 1].strip())) j = k else: j += 1 elif spans and ln.startswith(" NO "): rows.append({PICK_COLUMNS[n]: ln[s:e + 1].strip() for s, e, n in spans}) df = pd.DataFrame(rows) for c in ("obs", "md", "tvd", "tvdss", "twt_ms", "dip", "azi", "x", "y"): df[c] = pd.to_numeric(df[c], errors="coerce") df["obs"] = df["obs"].astype(int) return df def read_checkshot(path: str | Path) -> pd.DataFrame: """`TZV_TIME_CHECKSHOT_*.ASC` (3 cột MD, TVD-MSL, TWT ms). F-11 T2 ghi MD từ RKB, F-15 A ghi MD từ MSL (`MDMSL`), nên MD được quy về RKB. Trả về cột md (RKB), tvdss (dương xuống) và twt_ms.""" text = Path(path).read_text(errors="replace") rows = [] for ln in text.splitlines(): p = ln.split() if len(p) == 3: try: rows.append([float(v) for v in p]) except ValueError: pass a = np.asarray(rows) md = a[:, 0] + (VOLVE_RKB_M if "MDMSL" in text else 0.0) return pd.DataFrame({"md": md, "tvdss": a[:, 1], "twt_ms": a[:, 2]})