"""Biến đổi bin (inline/crossline) ↔ XY theo file `.survey` của OpendTect. `.survey` lưu phép biến đổi affine X = x0 + a_x·IL + b_x·XL Y = y0 + a_y·IL + b_y·XL trong các dòng `Coord-X-BinID: x0`a_x`b_x` và `Coord-Y-BinID: y0`a_y`b_y`. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path import numpy as np @dataclass(frozen=True) class SurveyGeometry: x_coef: tuple[float, float, float] y_coef: tuple[float, float, float] il_range: tuple[int, int, int] xl_range: tuple[int, int, int] z_range: tuple[float, float, float] set_points: tuple[tuple[int, int, float, float], ...] = () epsg: int | None = None @classmethod def from_survey(cls, path: str | Path) -> SurveyGeometry: path = Path(path) if path.is_dir(): path = path / ".survey" kv: dict[str, str] = {} for line in path.read_text(errors="replace").splitlines(): if ":" in line: k, v = line.split(":", 1) kv[k.strip()] = v.strip() def nums(key: str) -> list[float]: return [float(s) for s in kv[key].split("`")[:3]] set_points = [] for k, v in kv.items(): if k.startswith("Set Point."): binid, xy = v.split("`") il, xl = (int(s) for s in binid.split("/")) x, y = (float(s) for s in xy.strip("()").split(",")) set_points.append((il, xl, x, y)) epsg = None if "Coordinate System.Projection.ID" in kv: epsg = int(kv["Coordinate System.Projection.ID"].split("`")[-1]) return cls( x_coef=tuple(nums("Coord-X-BinID")), y_coef=tuple(nums("Coord-Y-BinID")), il_range=tuple(int(v) for v in nums("In-line range")), xl_range=tuple(int(v) for v in nums("Cross-line range")), z_range=tuple(nums("Z range")), set_points=tuple(set_points), epsg=epsg, ) @classmethod def from_points(cls, il, xl, x, y, z_range=(np.nan, np.nan, np.nan), epsg: int | None = None) -> SurveyGeometry: """Khớp affine bình phương tối thiểu từ các điểm (IL, XL, X, Y), ví dụ các nút của một horizon.""" il, xl, x, y = (np.asarray(v, dtype=float).ravel() for v in (il, xl, x, y)) A = np.c_[np.ones_like(il), il, xl] cx, *_ = np.linalg.lstsq(A, x, rcond=None) cy, *_ = np.linalg.lstsq(A, y, rcond=None) def rng(v): u = np.unique(v) step = int(np.diff(u).min()) if len(u) > 1 else 1 return int(u[0]), int(u[-1]), step return cls(x_coef=tuple(float(c) for c in cx), y_coef=tuple(float(c) for c in cy), il_range=rng(il), xl_range=rng(xl), z_range=tuple(z_range), epsg=epsg) def _matrix(self) -> np.ndarray: return np.array([[self.x_coef[1], self.x_coef[2]], [self.y_coef[1], self.y_coef[2]]]) def bin_to_xy(self, il, xl): il = np.asarray(il, dtype=float) xl = np.asarray(xl, dtype=float) x = self.x_coef[0] + self.x_coef[1] * il + self.x_coef[2] * xl y = self.y_coef[0] + self.y_coef[1] * il + self.y_coef[2] * xl return x, y def xy_to_bin(self, x, y): """Bin (thực, chưa làm tròn) tương ứng với XY.""" x = np.asarray(x, dtype=float) y = np.asarray(y, dtype=float) rhs = np.stack([x - self.x_coef[0], y - self.y_coef[0]]) il, xl = np.tensordot(np.linalg.inv(self._matrix()), rhs, axes=1) return il, xl def nearest_bin(self, x: float, y: float) -> tuple[int, int]: il, xl = self.xy_to_bin(x, y) return int(np.rint(il)), int(np.rint(xl)) def bin_spacing(self) -> tuple[float, float]: """Khoảng cách (m) giữa hai inline liên tiếp và hai crossline liên tiếp.""" m = self._matrix() return float(np.hypot(*m[:, 0])), float(np.hypot(*m[:, 1])) def in_survey(self, il: int, xl: int) -> bool: return ( self.il_range[0] <= il <= self.il_range[1] and self.xl_range[0] <= xl <= self.xl_range[1] )