Files
ML-Porosity/scripts/40_band_spectra.py
lamlvh df5cb937e8 Regenerate figures with descriptive names; add band-content table
Regenerate p2_phase, p2r_grid, p2r_h2b, bench_s1 and bench_s8 from the
existing summaries so they use the paper's descriptive names, and remove
the \figcodes notes and macro. Display fixes only: mathtext for the
-5 dB label and a shorter anchor-mean cell label.

Add a post hoc, descriptive table of the band content of the F3 labels,
the synthetic labels and the Oracle predictions (scripts/40_band_spectra.py,
Table tab:bandspectra in App. C) and rewrite the "Band of the benchmark"
limitation. No number, verdict, threshold, locked protocol or abstract
changed. Clean-room check rerun: 12/12 stages pass, nothing differs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:56:10 +00:00

138 lines
6.6 KiB
Python

"""Band content of the labels and of the Oracle predictions (post hoc, descriptive; not part of any protocol).
Written on 2026-11-09, after every verdict, to support the "Band of the benchmark" limitation of the manuscript. It
compares, in the scoring window 600-1100 ms, the spectrum above f_c = 6 Hz of
F3 marker-calibrated PHIE_DT of the four wells (outputs/f3_wells.npz)
synthetic true labels of the test wells of Experiment 2, realizations 8-15, 8 wells each (y_true of the cells)
Oracle predictions of the five Oracle seeds, N = 16, c = 1, by SNR setting (10, 0, -5 dB; R10, R0, Rm5)
Oracle coh. the part of the Oracle predictions coherent with the label, S_m = max(Re S_mu,y, 0), as in script 31
The periodogram is that of scripts/31_p2r_posthoc.py (row mean removed, reflect-padded to 512 samples, 4 ms). Labels
do not depend on the setting or on c (checked below); predictions at c = 1 are used because it is the F3-like drift.
Output (outputs/band_spectra/, outside the repro archives): table.csv (one row per source: band RMS in p.u., share of the
band power per frequency bin, power-weighted and f^4-weighted median frequency), groups.csv (the same per F3 well and per
synthetic realization, which give the ranges), meta.json. Nothing here changes a registered number and nothing is
chosen with these numbers. CPU only, a few seconds.
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/40_band_spectra.py
"""
from __future__ import annotations
import json
import numpy as np
import pandas as pd
from ml_porosity.eval.metrics import split_bands
from ml_porosity.paths import outputs_dir
OUT = outputs_dir() / "band_spectra"
TRAIN = outputs_dir() / "p2r" / "train"
DT_MS, L, F_C = 4.0, 512, 6.0
F = np.fft.rfftfreq(L, DT_MS / 1000)
BAND = F >= F_C
BINS = [(6, 15), (15, 25), (25, 40), (40, 60), (60, 125.01)]
RIDS = range(8, 16)
SETTINGS = ["R10", "R0", "Rm5"]
F3_WELLS = ["F02-1", "F03-2", "F03-4", "F06-1"]
def fft_rows(P: np.ndarray) -> np.ndarray:
"""rfft of each row with its mean removed, reflect-padded to L (scripts/31_p2r_posthoc.py)."""
n = P.shape[1]
a = L // 2 - n // 2
return np.fft.rfft(np.pad(P - P.mean(1, keepdims=True), ((0, 0), (a, L - n - a)), mode="reflect"))
def weighted_median(S: np.ndarray, power: int = 0) -> float:
w = F ** power * S * BAND
return float(F[np.searchsorted(np.cumsum(w) / w.sum(), 0.5)])
def describe(S: np.ndarray, band_rms: float | None) -> dict:
total = S[BAND].sum()
row = {"band_rms_pu": band_rms, "median_hz": weighted_median(S), "f4_median_hz": weighted_median(S, 4)}
row |= {f"share_{lo:g}_{min(hi, 125):g}": float(S[(F >= lo) & (F < hi)].sum() / total) for lo, hi in BINS}
return row
def rms_band(P: np.ndarray) -> float:
return float(np.sqrt(np.mean(split_bands(P, F_C)[1] ** 2)))
def cell(setting: str, rid: int):
return np.load(TRAIN / setting / "cells" / f"r{rid}_c1_n16.npz")
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
rows, groups = [], []
# F3 labels, in porosity units as the synthetic ones
wells = np.load(outputs_dir() / "f3_wells.npz")
Y = np.stack([100 * wells[f"{w}/calibrated/PHIE_DT"][wells[f"{w}/main_mask"]].astype(float) for w in F3_WELLS])
assert np.isfinite(Y).all() and Y.shape[1] == 126
S = np.abs(fft_rows(Y)) ** 2
rows.append({"source": "F3 PHIE_DT label", "n_traces": len(Y)} | describe(S.mean(0), rms_band(Y)))
for w, y, s in zip(F3_WELLS, Y, S):
groups.append({"source": "F3 PHIE_DT label", "group": w} | describe(s, rms_band(y[None])))
# synthetic labels and Oracle predictions
label_check = []
ys, per_rid = [], {}
for rid in RIDS:
z = cell("R10", rid)
y = z["y_true"].astype(float)
ys.append(y)
for s in SETTINGS[1:]:
label_check.append(np.array_equal(y, cell(s, rid)["y_true"].astype(float)))
for c in (0, 2):
label_check.append(np.array_equal(y, np.load(TRAIN / "R10" / "cells" / f"r{rid}_c{c}_n16.npz")["y_true"].astype(float)))
Sy = (np.abs(fft_rows(y)) ** 2).mean(0)
groups.append({"source": "Synthetic label", "group": f"r{rid}"} | describe(Sy, rms_band(y)))
assert all(label_check)
Y = np.concatenate(ys)
rows.append({"source": "Synthetic label", "n_traces": len(Y)} | describe((np.abs(fft_rows(Y)) ** 2).mean(0), rms_band(Y)))
for setting in SETTINGS:
acc_mu, acc_cross, rms = [], [], []
for rid in RIDS:
z = cell(setting, rid)
y = z["y_true"].astype(float)
FY = fft_rows(y)
keys = [k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")]
assert len(keys) == 5, keys
mu_r, cr_r, rms_r = [], [], []
for k in keys:
P = z[k].astype(float)
assert np.isfinite(P).all()
FM = fft_rows(P)
mu_r.append((np.abs(FM) ** 2).mean(0))
cr_r.append((FM * FY.conj()).real.mean(0))
rms_r.append(rms_band(P))
acc_mu.append(np.mean(mu_r, 0)); acc_cross.append(np.mean(cr_r, 0)); rms.append(np.mean(rms_r))
groups.append({"source": f"Oracle prediction {setting}", "group": f"r{rid}"} | describe(acc_mu[-1], rms[-1]))
groups.append({"source": f"Oracle coherent {setting}", "group": f"r{rid}"} | describe(np.clip(acc_cross[-1], 0, None), None))
rows.append({"source": f"Oracle prediction {setting}", "n_traces": 8 * 8 * 5} | describe(np.mean(acc_mu, 0), float(np.mean(rms))))
rows.append({"source": f"Oracle coherent {setting}", "n_traces": 8 * 8 * 5} | describe(np.clip(np.mean(acc_cross, 0), 0, None), None))
t, g = pd.DataFrame(rows), pd.DataFrame(groups)
t.to_csv(OUT / "table.csv", index=False)
g.to_csv(OUT / "groups.csv", index=False)
ranges = {s: {k: [float(d[k].min()), float(d[k].max())] for k in ("median_hz", "f4_median_hz", "share_25_40", "share_40_60", "share_60_125")}
for s, d in g.groupby("source")}
(OUT / "meta.json").write_text(json.dumps({
"status": "post hoc, descriptive; written 2026-11-09 after all verdicts; not part of any protocol",
"window_ms": [600, 1100], "dt_ms": DT_MS, "nfft": L, "f_c_hz": F_C, "bins_hz": BINS,
"labels_independent_of_setting_and_c": True, "ranges_over_groups": ranges}, indent=1), encoding="utf-8")
pd.set_option("display.width", 220, "display.max_columns", 20)
print(t.round(3).to_string(index=False))
print(json.dumps(ranges["F3 PHIE_DT label"], indent=0))
print(json.dumps(ranges["Synthetic label"], indent=0))
print("wrote", OUT)
if __name__ == "__main__":
main()