"""Đọc trace từ SEG-Y post-stack theo (IL, XL) mà không nạp cả cube. Lưu ý F3_entire.segy: DelayRecordingTime = 4 ms nên mẫu đầu ở 4 ms (segyio đã tính), trong khi `.survey` ghi Z range bắt đầu từ 0. Lưu ý stack ST10010 của Volve: (1) thiếu 26 trace ở rìa nên segyio không mở được ở chế độ strict, phải tra trace theo header; (2) byte 215 (scalar cho các trường thời gian) = 3, không phải luỹ thừa của 10, nhưng segyio vẫn nhân DelayRecordingTime = 4 với 3, khiến mẫu đầu thành 12 ms thay vì 4 ms như textual header ghi. """ from __future__ import annotations from pathlib import Path import numpy as np import segyio from ml_porosity.paths import f3_segy # Giá trị hợp lệ của scalar thời gian (byte 215) theo SEG-Y rev 1; 0 nghĩa là không áp dụng _TIME_SCALARS = {0, 1, -1, 10, -10, 100, -100, 1000, -1000, 10000, -10000} class SeismicCube: def __init__(self, path: str | Path | None = None): self.path = Path(path) if path else f3_segy() self._lut: dict[tuple[int, int], int] | None = None try: self._f = segyio.open(str(self.path), "r") if self._f.sorting != segyio.TraceSortingFormat.INLINE_SORTING: raise ValueError("chỉ hỗ trợ SEG-Y sắp xếp theo inline") self.ilines = np.asarray(self._f.ilines) self.xlines = np.asarray(self._f.xlines) except ValueError as e: if "sắp xếp" in str(e): raise # lưới không đủ trace: tra chỉ số trace theo header IL/XL self._f = segyio.open(str(self.path), "r", ignore_geometry=True) il = self._f.attributes(segyio.TraceField.INLINE_3D)[:] xl = self._f.attributes(segyio.TraceField.CROSSLINE_3D)[:] self._lut = {(int(i), int(j)): k for k, (i, j) in enumerate(zip(il, xl))} self.ilines, self.xlines = np.unique(il), np.unique(xl) self.times_ms = np.asarray(self._f.samples, dtype=float) h = self._f.header[0] if h[segyio.TraceField.ScalarTraceHeader] not in _TIME_SCALARS: self.times_ms += h[segyio.TraceField.DelayRecordingTime] - self.times_ms[0] self.dt_ms = float(self.times_ms[1] - self.times_ms[0]) def __enter__(self) -> SeismicCube: return self def __exit__(self, *exc) -> None: self.close() def close(self) -> None: self._f.close() def _index(self, il: int, xl: int) -> int: if self._lut is not None: if (il, xl) not in self._lut: raise KeyError(f"bin ({il}, {xl}) không có trace trong cube") return self._lut[(il, xl)] i = np.searchsorted(self.ilines, il) j = np.searchsorted(self.xlines, xl) if i >= len(self.ilines) or self.ilines[i] != il or j >= len(self.xlines) or self.xlines[j] != xl: raise KeyError(f"bin ({il}, {xl}) nằm ngoài cube") return int(i * len(self.xlines) + j) def coords(self, il: int, xl: int) -> tuple[float, float]: """Toạ độ CDP (byte 181/185) của bin, đã áp scalar ở byte 71.""" h = self._f.header[self._index(il, xl)] sc = h[segyio.TraceField.SourceGroupScalar] mul = 1 / abs(sc) if sc < 0 else (sc or 1) return h[segyio.TraceField.CDP_X] * mul, h[segyio.TraceField.CDP_Y] * mul def trace(self, il: int, xl: int) -> np.ndarray: return np.asarray(self._f.trace[self._index(il, xl)], dtype=np.float32) def patch(self, il: int, xl: int, radius: int) -> np.ndarray: """Các trace trong ô (2r+1)×(2r+1) quanh (il, xl), thứ tự IL rồi XL: shape (C, nt). Khác luận văn: không kẹp chỉ số ở biên mà báo lỗi nếu ô vượt ra ngoài cube.""" return np.stack( [ self.trace(il + di, xl + dx) for di in range(-radius, radius + 1) for dx in range(-radius, radius + 1) ] ) def window(self, t0_ms: float, t1_ms: float) -> np.ndarray: """Mặt nạ boolean cho các mẫu trong [t0, t1].""" return (self.times_ms >= t0_ms) & (self.times_ms <= t1_ms)