"""P4 data views (plan §5.2): private arrays of the training wells, seismic-only blind inputs of every other well. A restricted view (training_wells given) keeps, for a well outside the training set, only times_ms, main_mask, kb_msl, survey/* the well path, known without its logs or picks blind//{seismic_patch, md, il, xl, beyond} only for K ⊇ training_wells, well ∉ K so its logs, picks, TDRs, reference path and the label-centred bin (il, xl, x, y: placed at the middle of the label interval) are never loaded. Labels, the reference input and registration observations of such a well raise RuntimeError. The full view (training_wells None) is for scoring only. """ from __future__ import annotations import numpy as np from ml_porosity.data.resample import log_to_time from ml_porosity.data.tdr import 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 PUBLIC = frozenset({"times_ms", "main_mask", "kb_msl"}) PUBLIC_PREFIXES = ("survey/",) def npz_path(): return outputs_dir() / "volve" / "volve_wells.npz" def load_arrays(path=None) -> dict[str, np.ndarray]: with np.load(npz_path() if path is None else path) as z: return {k: z[k] for k in z.files} def blind_members(key: str) -> frozenset[str]: return frozenset(key.split("+")) def visible(key: str, training_wells: frozenset[str] | None) -> bool: """Whether the flat npz key "/" belongs to a view on `training_wells`.""" well, item = key.split("/", 1) if training_wells is None or well in training_wells: return True if item in PUBLIC or item.startswith(PUBLIC_PREFIXES): return True if item.startswith("blind/"): members = blind_members(item.split("/")[1]) return well not in members and training_wells <= members return False class VolveData: def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None, arrays: dict[str, np.ndarray] | None = None): self.protocol = protocol self.wells = list(protocol["data"]["wells"]) self.label = protocol["data"]["label"] 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") source = load_arrays() if arrays is None else arrays self.arrays = {k: v for k, v in source.items() if k.split("/", 1)[0] in self.wells and visible(k, self.training_wells)} 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] self.dt = float(np.diff(self.t)[0]) for w in self.wells: if not (np.array_equal(self.ext(w, "times_ms"), self.t) and np.array_equal(self.ext(w, "main_mask").astype(bool), self.main)): raise ValueError(f"Volve time axes differ: {w}") r = protocol["registration"] f = r["fine_dt_ms"] 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] + f / 2, f) self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + f / 2, f) def is_training(self, well: str) -> bool: return self.training_wells is None or well in self.training_wells def ext(self, well: str, key: str) -> np.ndarray: try: return self.arrays[f"{well}/{key}"] except KeyError: raise KeyError(f"{well}/{key} is not in this data view") from None def blind_keys(self, well: str) -> list[str]: head = f"{well}/blind/" return sorted({k[len(head):].split("/")[0] for k in self.arrays if k.startswith(head)}) def patch(self, well: str, key: str) -> np.ndarray: """(C, n_ext) seismic patch: key 'reference' (calibrated path, training wells only) or a blind key.""" if key == "reference": if not self.is_training(well): raise RuntimeError("The reference path of a held-out well uses its own picks and DT") return self.ext(well, "reference/seismic_patch") if well in blind_members(key): raise RuntimeError(f"Blind key {key!r} contains its own well {well!r}") return self.ext(well, f"blind/{key}/seismic_patch") def X(self, well: str, key: str) -> np.ndarray: """Network input (C, L) on the main window.""" return zscore_patch(self.patch(well, key), self.main) def y(self, well: str, reference: str, label: str | None = None) -> np.ndarray: """Label on the main window under TDR `reference`; NaN outside its support.""" if not self.is_training(well): raise RuntimeError("Held-out labels are unavailable in a training data view") return self.ext(well, f"{reference}/{label or self.label}")[self.main] def training_observations(self, names: tuple[str, ...]) -> list[dict]: """Registration inputs of training wells on the sonic time axis τ (vertical sonic through the first anchor in the DT range). Anchors: in the DT range and inside the ext window. `lik`: ext samples from the first to the last finite calibrated AI sample (the tie likelihood is evaluated there only).""" 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") r = self.protocol["registration"] obs = [] for name in names: sonic = TDR(self.ext(name, "tdr/sonic/md"), self.ext(name, "tdr/sonic/twt_ms"), "sonic") md = self.ext(name, "log/md") amd, att = self.ext(name, "anchors_md"), self.ext(name, "anchors_twt_ms") keep = self.ext(name, "anchors_in_dt").astype(bool) & (att >= self.t[0]) & (att <= self.t[-1]) if keep.sum() < 1: raise ValueError(f"No anchor in the DT range: {name}") resampled, valid = {}, {} for curve in ("AI", self.label): v = log_to_time(md, self.ext(name, f"log/{curve}"), sonic, self.tau, fine_dt_ms=r["log_fine_dt_ms"], cutoff_frac=r["log_cutoff_frac"]) good = np.isfinite(v) if good.sum() < 2: raise ValueError(f"No sonic-domain log: {name}/{curve}") resampled[curve] = np.interp(self.tau, self.tau[good], v[good]) valid[curve] = good ok = np.flatnonzero(np.isfinite(self.ext(name, "calibrated/AI"))) lik = np.zeros(self.t.size, bool) lik[ok[0]: ok[-1] + 1] = True seis = self.ext(name, "reference/seismic_patch") obs.append({"name": name, "tau_k": sonic.time_at(amd[keep]), "t_k": att[keep].astype(float), "ai_log": resampled["AI"], "labels": {self.label: resampled[self.label]}, "label_valid": {self.label: valid[self.label]}, "lik": lik, "seis": seis[len(seis) // 2].astype(float)}) return obs