"""T0 inventory of the Teapot Dome (NPR-3, RMOTC) archive (docs/research/applicability-teapot.md ยง4). Reads headers and curve support only: which wells have density / neutron / sonic, over which depths, where they are, whether they fall inside the 3D footprint, and which files look like checkshots, VSP, time-depth tables, tops or deviation surveys. Computes no porosity-versus-seismic relation and trains nothing, so it is not a look at test labels. Self-contained (no ml_porosity import); run with `python -P` from the repo root so nothing inside the untrusted archive can land on sys.path (`-I` would also hide segyio, which is in the user site-packages here). python -P scripts/28_teapot_inventory.py --root data/Teapot/raw/rmotc --out outputs/teapot/inventory """ from __future__ import annotations import argparse import json import re from pathlib import Path import numpy as np import pandas as pd GROUPS = { "density": ("RHOB", "RHOZ", "ZDEN", "DEN", "RHO", "DENS", "ZDNC"), "neutron": ("NPHI", "NPOR", "CNL", "TNPH", "NPHS", "CNC", "NEU", "NPHIL"), "sonic": ("DT", "DTC", "AC", "DT4P", "DTCO", "SON", "DELT"), "dens_porosity": ("DPHI", "DPHZ", "PHID", "DPOR", "DPHS"), "porosity": ("PHIE", "PHIT", "POR"), "gamma": ("GR", "GRD", "GRR", "SGR", "CGR"), } SPECIAL = re.compile(r"check.?shot|checkshot|\bcs\b|vsp|velocity|vel_|t-?d|time.?depth|tdr|tops?|marker|" r"formation|deviat|direction|survey|header|location|coord", re.I) SEGY_EXT = {".sgy", ".segy", ".sgy.gz"} def group_of(mnemonic: str) -> str | None: m = re.sub(r"[^A-Z0-9]", "", mnemonic.upper()) for g, names in GROUPS.items(): if any(m == n or (m.startswith(n) and len(m) <= len(n) + 2) for n in names): return g return None def header_value(las, *keys): for section in (las.well, las.params): for k in keys: if k in section and str(section[k].value).strip() not in ("", "nan"): return section[k].value return None def scan_las(path: Path) -> dict: import lasio las = lasio.read(path, ignore_header_errors=True, engine="normal") depth = las.index.astype(float) row = dict(file=str(path), well=str(header_value(las, "WELL") or path.stem), uwi=header_value(las, "UWI", "API"), x=header_value(las, "X", "XCOORD", "XWELL", "EAST"), y=header_value(las, "Y", "YCOORD", "YWELL", "NORTH"), lat=header_value(las, "LAT", "LATI"), lon=header_value(las, "LON", "LONG"), loc=header_value(las, "LOC"), kb=header_value(las, "EKB", "KB", "ELZ", "EREF", "EDF"), gl=header_value(las, "EGL", "GL", "ELEV"), depth_unit=str(las.index_unit), strt=float(np.nanmin(depth)) if depth.size else np.nan, stop=float(np.nanmax(depth)) if depth.size else np.nan, curves=";".join(c.mnemonic for c in las.curves)) for g in GROUPS: row[f"{g}_curve"], row[f"{g}_top"], row[f"{g}_base"], row[f"{g}_n"] = None, np.nan, np.nan, 0 for c in las.curves[1:]: g = group_of(c.mnemonic) if g is None: continue ok = np.isfinite(c.data.astype(float)) if ok.sum() > row[f"{g}_n"]: row[f"{g}_curve"], row[f"{g}_n"] = c.mnemonic, int(ok.sum()) row[f"{g}_top"], row[f"{g}_base"] = float(depth[ok].min()), float(depth[ok].max()) return row def scan_segy(path: Path) -> tuple[dict, np.ndarray]: import segyio with segyio.open(path, ignore_geometry=True) as f: n = f.tracecount h = f.attributes sc = np.asarray(h(segyio.TraceField.SourceGroupScalar)[:], float) scale = np.where(sc < 0, -1 / np.where(sc == 0, 1, sc), np.where(sc == 0, 1, sc)) out = dict(file=str(path), traces=int(n), samples=int(len(f.samples)), dt_ms=float(segyio.tools.dt(f) / 1000), t0_ms=float(f.samples[0]), t1_ms=float(f.samples[-1])) for name, field in (("cdp_x", segyio.TraceField.CDP_X), ("cdp_y", segyio.TraceField.CDP_Y), ("src_x", segyio.TraceField.SourceX), ("src_y", segyio.TraceField.SourceY)): v = np.asarray(h(field)[:], float) * scale out[f"{name}_min"], out[f"{name}_max"] = float(v.min()), float(v.max()) for name, byte in (("il189", 189), ("xl193", 193), ("il9", 9), ("xl21", 21), ("il181", 181), ("xl185", 185)): v = np.asarray(h(byte)[:], float) out[f"{name}_min"], out[f"{name}_max"], out[f"{name}_unique"] = float(v.min()), float(v.max()), int(np.unique(v).size) xs = np.asarray(h(segyio.TraceField.CDP_X)[:], float) * scale ys = np.asarray(h(segyio.TraceField.CDP_Y)[:], float) * scale return out, np.column_stack([xs, ys]) def inside_hull(points: np.ndarray, hull_xy: np.ndarray) -> np.ndarray: from matplotlib.path import Path as MPath from scipy.spatial import ConvexHull hull = hull_xy[ConvexHull(hull_xy).vertices] return MPath(hull).contains_points(points) def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--root", type=Path, required=True) ap.add_argument("--out", type=Path, required=True) args = ap.parse_args() args.out.mkdir(parents=True, exist_ok=True) files = sorted(p for p in args.root.rglob("*") if p.is_file()) pd.DataFrame(dict(file=[str(p.relative_to(args.root)) for p in files], suffix=[p.suffix.lower() for p in files], bytes=[p.stat().st_size for p in files])).to_csv(args.out / "files.csv", index=False) special = [str(p.relative_to(args.root)) for p in files if SPECIAL.search(p.name) or SPECIAL.search(p.parent.name)] (args.out / "special_files.txt").write_text("\n".join(special)) las_rows, errors = [], [] for p in files: if p.suffix.lower() == ".las": try: las_rows.append(scan_las(p)) except Exception as exc: # malformed legacy LAS: record and continue errors.append(dict(file=str(p), error=repr(exc)[:300])) las = pd.DataFrame(las_rows) pd.DataFrame(errors).to_csv(args.out / "las_errors.csv", index=False) segy, hull = [], None for p in files: if "".join(p.suffixes).lower() in SEGY_EXT or p.suffix.lower() in SEGY_EXT: try: info, xy = scan_segy(p) segy.append(info) if hull is None or len(xy) > len(hull): hull = xy[np.isfinite(xy).all(axis=1) & (np.abs(xy).sum(1) > 0)] except Exception as exc: segy.append(dict(file=str(p), error=repr(exc)[:300])) pd.DataFrame(segy).to_csv(args.out / "segy.csv", index=False) if len(las): for c in ("x", "y"): las[c] = pd.to_numeric(las[c], errors="coerce") las["inside_3d"] = pd.Series(pd.NA, index=las.index, dtype="boolean") ok = las[["x", "y"]].notna().all(axis=1) if hull is not None and len(hull) >= 3 and ok.any(): las.loc[ok, "inside_3d"] = inside_hull(las.loc[ok, ["x", "y"]].to_numpy(), hull) las.to_csv(args.out / "las_wells.csv", index=False) has = lambda g: las[f"{g}_n"] > 0 if len(las) else pd.Series(dtype=bool) summary = dict( files=len(files), las_files=int(len(las)), las_errors=len(errors), segy_files=len(segy), segy_errors=sum("error" in r for r in segy), unique_wells=int(las.well.nunique()) if len(las) else 0, with_density=int(has("density").sum()) if len(las) else 0, with_density_or_dphi=int((has("density") | has("dens_porosity")).sum()) if len(las) else 0, with_neutron=int(has("neutron").sum()) if len(las) else 0, with_sonic=int(has("sonic").sum()) if len(las) else 0, with_density_and_sonic=int((has("density") & has("sonic")).sum()) if len(las) else 0, with_coordinates=int(las[["x", "y"]].notna().all(axis=1).sum()) if len(las) else 0, inside_3d=int(las.inside_3d.fillna(False).sum()) if len(las) and "inside_3d" in las else None, inside_3d_density_and_sonic=int((las.inside_3d.fillna(False) & has("density") & has("sonic")).sum()) if len(las) and "inside_3d" in las else None, special_files=len(special), note="Counts are per LAS file; several files can belong to one well. Checkshot/VSP presence must be confirmed " "by reading special_files.txt, not by these counts.") (args.out / "summary.json").write_text(json.dumps(summary, indent=2)) print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()