Complete P4 Volve; pivot the manuscript to theory + benchmark

P4 (Volve field case). Add the deviated-well and Volve well builders
(ml_porosity/data/deviated.py, volve_wells.py), the ml_porosity/volve/
pipeline, scripts 23-25, the run_p4 drivers and tests. The protocol
configs/protocol_volve.yaml was locked at 2026-10-29T01:17:42Z before the
run (.sha256, .lock.json) and is committed here after the run. Gate G-D
failed: M2-Sa beats the selected B3 at 2/6 wells (lowo) and 3/6 (slot),
coverage90 is about 0.47, and no method has blind-well skill (R2 < 0).
A post hoc constant at the training-well mean beats every network, so
G-D had no power. The dropped P4x exploratory run is kept as a record
only (exploratory/, docs/research/p4-exploratory.md).

Applicability and Teapot Dome (exploratory, pre-declared). Scripts 26-29
and docs/research/applicability-*.md: F3 and Volve fail C1 and pass C2;
T3 power needs 5-18 blind wells with an exact reference; Teapot T0 and
pilot P-a failed, so Teapot is stopped. Raw Teapot data stay gitignored.

Manuscript (Pivot 1, level A). Reframe paper/ as a theory and synthetic
benchmark paper: Propositions 3-6, Corollaries 3-4, T4 coverage
(script 30) and the post hoc H2b bound check (script 31), with F3/Volve
moved to Appendix B. Correct two earlier claims: the Berkson and
classical bounds differ by 1.5-4.6x at the f^4-weighted band, and the
bank gain exceeds the registered classical bound (7/8 wide cells at
N = 16) but only 3/8 under the post hoc Berkson bound.

Docs. Sync plan, AGENTS.md, README, report.html, theory and technical
overview. The length pass for the venue is dropped by the user
(plan section 12 item 25); the length risk stays recorded as R9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 12:18:22 +00:00
parent 7da6b077b6
commit 0cfe202a8b
61 changed files with 7162 additions and 881 deletions

View File

@@ -0,0 +1,123 @@
"""Protocol locking and resume fingerprints for P4 (Volve), separate from the frozen P3 lock.
Paths in the stamp are relative to their root (repo, outputs or Volve data directory), so a lock is portable between
checkouts; it is still bound to one environment, as in P3. Before the lock exists, `current_stamp` gives the same
stamp without writing it (smoke runs only).
"""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import yaml
from ml_porosity.f3.protocol import digest, environment, fingerprint
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
__all__ = ["CONFIG", "LOCK", "current_stamp", "fingerprint", "freeze", "load_protocol", "source_config"]
CONFIG = REPO_ROOT / "configs/protocol_volve.yaml"
LOCK = REPO_ROOT / "configs/protocol_volve.lock.json"
SCRIPTS = ("scripts/23_build_volve_wells.py", "scripts/24_run_volve.py", "scripts/run_p4.ps1", "scripts/run_p4.sh")
PROTECTED = ("wavelets.npz", "p2/warp_prior_f3.json")
RESULTS = ("registration", "train", "summary")
def load_protocol() -> dict:
return yaml.safe_load(CONFIG.read_text(encoding="utf-8"))
def source_config(p: dict) -> dict:
"""configs/d3_volve.yaml, which built the dataset; its p4 section holds the slot groups of the blind folds."""
cfg = yaml.safe_load((REPO_ROOT / p["data"]["source_config"]).read_text(encoding="utf-8"))
if list(cfg["p4"]["wells"]) != list(p["data"]["wells"]) or cfg["p4"]["label"] != p["data"]["label"]:
raise RuntimeError("protocol_volve and its source configuration disagree on wells or label")
if not set(p["split"]["schemes"]) <= set(cfg["p4"]["blind_schemes"]):
raise RuntimeError("Unknown blind scheme in protocol_volve")
return cfg
def code_files() -> list[Path]:
paths = sorted((REPO_ROOT / "ml_porosity").rglob("*.py"))
paths += [REPO_ROOT / s for s in SCRIPTS if (REPO_ROOT / s).exists()]
return paths + [REPO_ROOT / "pyproject.toml"]
def source_hash() -> str:
import hashlib
h = hashlib.sha256()
for f in code_files():
h.update(f.relative_to(REPO_ROOT).as_posix().encode() + b"\0")
h.update(f.read_bytes().replace(b"\r\n", b"\n") + b"\0")
return h.hexdigest()
def input_files(p: dict) -> list[Path]:
"""Derived dataset, its configuration and every raw file the build reads, except the cube (checked against the
data manifest at the first lock)."""
cfg = source_config(p)
root, p4 = volve_root(), cfg["p4"]
files = [outputs_dir() / "volve/volve_wells.npz", outputs_dir() / "volve/volve_wells_summary.json",
root / cfg["picks"], root / cfg["horizons_twt"] / cfg["grid_horizon"]]
for spec in p4["wells"].values():
files.append(root / p4["survey_dir"] / spec["survey"])
logs = root / cfg["well_logs_dir"] / spec["logs"] / p4["log_subdir"]
files += [logs / p4["las_input"], logs / p4["las_output"]]
files += [root / cfg["well_logs_dir"] / cfg["checkshots"][spec["picks"]][kind]
for kind in spec.get("checkshots", [])]
return files
def portable_name(path: Path) -> str:
"""Portable name: 'repo:', 'outputs:' or 'volve:' plus the POSIX path relative to that root."""
path = path.resolve()
for prefix, base in (("volve", volve_root()), ("outputs", outputs_dir()), ("repo", REPO_ROOT)):
try:
return f"{prefix}:{path.relative_to(base.resolve()).as_posix()}"
except ValueError:
continue
raise ValueError(f"Input outside the repository, outputs and Volve roots: {path}")
def current_stamp(p: dict | None = None) -> dict:
p = load_protocol() if p is None else p
missing = [f for f in input_files(p) + [outputs_dir() / a for a in PROTECTED] if not f.exists()]
if missing:
raise FileNotFoundError(f"P4 inputs missing (sync data/ and outputs/ first): {[str(f) for f in missing]}")
config = REPO_ROOT / p["data"]["source_config"]
return {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(),
"protected_artifacts": {portable_name(outputs_dir() / a): digest(outputs_dir() / a) for a in PROTECTED},
"inputs": {portable_name(f): digest(f, f == config) for f in [config] + input_files(p)}}
def freeze(check: bool = False) -> dict:
"""Return the lock; create it if absent and check is False. Any difference from an existing lock is an error."""
p = load_protocol()
stamp = current_stamp(p)
if LOCK.exists():
old = json.loads(LOCK.read_text(encoding="utf-8"))
for k, v in stamp.items():
if old[k] != v:
raise RuntimeError(f"P4 lock mismatch: {k}. Preserve results and create a new protocol version.")
return old
if check:
raise RuntimeError("P4 is not locked. Run the lock stage before registration/training.")
if any((outputs_dir() / "p4" / d).exists() for d in RESULTS):
raise RuntimeError("Refusing a first lock after P4 results already exist.")
cfg = source_config(p)
manifest = json.loads((REPO_ROOT / "data_manifest/volve.json").read_text(encoding="utf-8"))
expected = manifest["files"][cfg["cube"]]["sha256"]
cube = volve_root() / cfg["cube"]
if not cube.exists() or digest(cube) != expected:
raise RuntimeError(f"Volve cube missing or different from the audited source: {cube}")
stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(), "segy_sha256": expected,
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and source configuration; "
"binary inputs exact",
"wells": p["data"]["wells"]}
LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8")
CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_volve.yaml\n",
encoding="utf-8")
return stamp