"""Read traces from a post-stack SEG-Y by (IL, XL) without loading the whole cube. Note on F3_entire.segy: DelayRecordingTime = 4 ms, so the first sample is at 4 ms (handled by segyio), whereas `.survey` gives a Z range starting at 0. Note on the Volve ST10010 stack: (1) 26 edge traces are missing, so segyio cannot open it in strict mode and traces must be looked up from the headers; (2) byte 215 (scalar for the time fields) = 3, which is not a power of 10, yet segyio still multiplies DelayRecordingTime = 4 by 3, placing the first sample at 12 ms instead of the 4 ms stated in the textual header. """ from __future__ import annotations from pathlib import Path import numpy as np import segyio from ml_porosity.paths import f3_segy # Valid values of the time scalar (byte 215) per SEG-Y rev 1; 0 means not applied _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("only inline-sorted SEG-Y is supported") self.ilines = np.asarray(self._f.ilines) self.xlines = np.asarray(self._f.xlines) except ValueError as e: if "inline-sorted" in str(e): raise # incomplete grid: look up trace indices from the IL/XL headers 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}) has no trace in the 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}) lies outside the cube") return int(i * len(self.xlines) + j) def coords(self, il: int, xl: int) -> tuple[float, float]: """CDP coordinates (bytes 181/185) of the bin, with the byte-71 scalar applied.""" 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: """Traces in the (2r+1)×(2r+1) window around (il, xl), ordered by IL then XL: shape (C, nt). Unlike the thesis, indices are not clamped at the edges; an error is raised if the window extends outside the 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: """Boolean mask of the samples within [t0, t1].""" return (self.times_ms >= t0_ms) & (self.times_ms <= t1_ms)