Files
ML-Porosity/ml_porosity/data/seismic_io.py
lamlvh cee2ff0859 P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00

94 lines
4.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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)