"""Explicit separation between training logs, seismic-only targets, and scoring references.""" from __future__ import annotations import numpy as np from ml_porosity.data.las_io import load_well from ml_porosity.data.resample import log_to_time from ml_porosity.data.tdr import sonic_tdr from ml_porosity.models.bank_train import zscore_patch from ml_porosity.paths import outputs_dir from ml_porosity.registration.warp_prior import WarpGrid class F3Data: def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None): self.protocol = protocol self.wells = protocol['data']['wells'] self.training_wells = None if training_wells is None else frozenset(training_wells) if self.training_wells is not None and not self.training_wells <= set(self.wells): raise ValueError('Unknown training well') public = {'seismic_patch', 'times_ms', 'main_mask', 'il', 'xl', 'x', 'y'} with np.load(outputs_dir() / 'f3_wells.npz') as z: self.arrays = {k: z[k] for k in z.files if self.training_wells is None or k.split('/', 1)[0] in self.training_wells or k.split('/', 1)[1] in public} self.t = self.ext(self.wells[0], 'times_ms') self.main = self.ext(self.wells[0], 'main_mask').astype(bool) self.t_main = self.t[self.main] r = protocol['registration'] self.dt = float(np.diff(self.t)[0]) self.grid = WarpGrid(*r['tau_range_ms'], r['warp_dtau_ms']) self.tau = np.arange(*[r['tau_range_ms'][0], r['tau_range_ms'][1] + r['fine_dt_ms'] / 2, r['fine_dt_ms']]) self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + r['fine_dt_ms'] / 2, r['fine_dt_ms']) for w in self.wells: if not np.array_equal(self.ext(w, 'times_ms'), self.t): raise ValueError('F3 well time axes differ') if self.training_wells is not None and w not in self.training_wells: continue for label in protocol['data']['labels']: for ref in protocol['data']['references']: if not np.isfinite(self.y(w, ref, label)).all(): raise ValueError(f'Non-finite scoring labels: {w}/{ref}/{label}') def ext(self, well: str, key: str): return self.arrays[f'{well}/{key}'] def X(self, well: str) -> np.ndarray: return zscore_patch(self.ext(well, 'seismic_patch'), self.main) def y(self, well: str, reference: str, label: str) -> np.ndarray: if self.training_wells is not None and well not in self.training_wells: raise RuntimeError('Held-out labels are unavailable in a training data view') return self.ext(well, f'{reference}/{label}')[self.main] def training_observations(self, names: tuple[str, ...], omit_anchor: tuple[str, int] | None = None) -> list[dict]: """Only named wells are loaded here; callers pass the exact inner training set.""" if self.training_wells is not None and not set(names) <= self.training_wells: raise RuntimeError('Held-out logs and anchors are unavailable in a training data view') obs = [] for name in names: w = load_well(name) cs = w.checkshot base = sonic_tdr(w.md, w.curve('DT'), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0]) tk = cs.twt_ms.to_numpy() tau_k = base.time_at(cs.md.to_numpy()) mask = (tk >= self.t[0]) & (tk <= self.t[-1]) tau_k, tk = tau_k[mask], tk[mask] if omit_anchor is not None and omit_anchor[0] == name: keep = np.arange(len(tk)) != omit_anchor[1] tau_k, tk = tau_k[keep], tk[keep] kwargs = dict(fine_dt_ms=0.25, cutoff_frac=0.8) curves = {'AI': w.curve('AI'), 'PHIE_DT': -0.2018 + 0.0011 * w.curve('DT'), 'PHIE': w.curve('PHIE')} resampled = {} valid_labels = {} for label, values in curves.items(): v = log_to_time(w.md, values, base, self.tau, **kwargs) good = np.isfinite(v) if good.sum() < 2: raise ValueError(f'No sonic-domain log: {name}/{label}') resampled[label] = np.interp(self.tau, self.tau[good], v[good]) if label != 'AI': valid_labels[label] = good obs.append({'name': name, 'tau_k': tau_k, 't_k': tk, 'ai_log': resampled.pop('AI'), 'labels': resampled, 'label_valid': valid_labels, 'seis': self.ext(name, 'seismic_patch')[4].astype(float)}) return obs