Complete P3 F3 evaluation and Windows execution
Implement the frozen F3 protocol, nested LOWO, posterior label banks, ablations, diagnostics, checkpoint validation and full-volume inference. Record the negative G-C result: improvement at 1/4 wells, coverage80 52.38% and coverage90 60.91%, with unchanged thresholds and historical P2 results. Add native Windows logging, the RTX 3060 environment lock, detached runs, and an audited dashboard-lock recovery that preserves frozen scientific code. Update report.html, the plan and agent guidance with completed P3 status. Archive thesis sources under code_thesis with identical Git blobs and record the original-output audit without committing large data or model artifacts. Validation: 129 tests passed, 13 skipped; CUDA end-to-end smoke passed; completion audit verified 1,320 checkpoint/prediction pairs, 28 registration bundles and all 649 interior volume inlines. Scripts 04 and 09 were not rerun. Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
164
ml_porosity/f3/registration.py
Normal file
164
ml_porosity/f3/registration.py
Normal file
@@ -0,0 +1,164 @@
|
||||
"""Training-set-only F3 registration. No held-out well is passed to this module."""
|
||||
from __future__ import annotations
|
||||
|
||||
import gc
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
|
||||
from ml_porosity.f3.data import F3Data
|
||||
from ml_porosity.losses.rml import effective_lambda
|
||||
from ml_porosity.registration.labels import antialias, invert_warps, labels_for_warps
|
||||
from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper
|
||||
from ml_porosity.registration.sampler import sample_warps, temper
|
||||
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, phase_loglik, synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_mean
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
|
||||
def valid_label_warps(data, observation, warps, labels) -> np.ndarray:
|
||||
tau_at = invert_warps(warps, data.tau, data.t_main)
|
||||
valid = np.isfinite(tau_at).all(axis=1)
|
||||
for label in labels:
|
||||
support = np.interp(tau_at, data.tau, observation['label_valid'][label].astype(float), left=0, right=0)
|
||||
valid &= (support >= 1-1e-9).all(axis=1)
|
||||
return valid
|
||||
|
||||
|
||||
def register_set(data: F3Data, names: tuple[str, ...], p: dict, device: str, sigma_a: float = 7.0,
|
||||
no_anchors: bool = False) -> tuple[dict, dict]:
|
||||
import torch
|
||||
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
|
||||
|
||||
started = time.perf_counter()
|
||||
r = p['registration'] | {'sigma_a_ms': sigma_a}
|
||||
obs = data.training_observations(names)
|
||||
if set(o['name'] for o in obs) != set(names):
|
||||
raise RuntimeError('Unexpected training-well payload')
|
||||
if no_anchors:
|
||||
h = WarpHyper(0, r['hyperprior']['sigma_g'][0], r['hyperprior']['ell_ms'][0],
|
||||
r['sigma_b_ms'], sigma_a, r['kernel'])
|
||||
hinfo = {'note': 'Fixed prior medians, no training anchors used for hyperparameter fitting'}
|
||||
obs = [o | {'tau_k': np.array([]), 't_k': np.array([])} for o in obs]
|
||||
else:
|
||||
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=data.grid), obs, r, r['smc_seed'])
|
||||
f = r['fine_dt_ms']
|
||||
fac = int(round(data.dt / f))
|
||||
w0 = statistical_wavelet(np.stack([o['seis'] for o in obs]), data.dt, r['wavelet_ms'])
|
||||
samples, Ts, Zs, LL, anchor_valid = [], [], [], [], []
|
||||
B = phase_basis(w0, fac)
|
||||
for i, o in enumerate(obs):
|
||||
smp = sample_warps(data.grid, h, o['tau_k'], o['t_k'], r['particles'], r['g_max'],
|
||||
np.random.default_rng([r['smc_seed'], i, 13]))
|
||||
samples.append(smp)
|
||||
tg = data.grid.t_of_tau(smp['b'][:r['S']], smp['g'][:r['S']], data.tau)
|
||||
valid = valid_label_warps(data, o, tg, p['data']['labels'])
|
||||
if not valid.any():
|
||||
raise ValueError(f'No anchor sample covers measured labels in the complete main window: {o["name"]}')
|
||||
anchor_valid.append(valid)
|
||||
LL.append(phase_loglik(synth_for_warps(data.tau, o['ai_log'], tg, data.t_fine, data.t,
|
||||
fine_wavelet(w0, fac)), o['seis'], PHASES))
|
||||
phase0 = float(PHASES[fit_phase(LL, anchor_valid, PHASES)])
|
||||
for o, smp in zip(obs, samples):
|
||||
T = TiePosteriorTorch(TiePosterior(data.grid, h, o['tau_k'], o['t_k'], r['g_max'], data.tau,
|
||||
o['ai_log'], data.t_fine, data.t, phase_wavelet(B, phase0), o['seis'],
|
||||
(data.t_main[0], data.t_main[-1]), allow_no_anchors=no_anchors), device)
|
||||
Zs.append(T.z(smp['u']))
|
||||
Ts.append(T)
|
||||
phase_r, ph = smc_fit_phase(Ts, Zs, B, phase0, [r['smc_seed'], 19], step=r['phase_step'],
|
||||
half_width=r['phase_half_width'], max_extra=r['phase_max_extra'], n_moves=r['smc_moves'])
|
||||
wf = phase_wavelet(B, phase_r)
|
||||
post, diag = [], []
|
||||
for i, (o, T0, z0) in enumerate(zip(obs, Ts, Zs)):
|
||||
T = T0.with_wavelet(wf)
|
||||
gamma = gamma_acf(T, z0, T.parts(z0)[1])
|
||||
res = smc_tie_posterior(T, z0, [gamma], np.random.default_rng([r['smc_seed'], i, 17]), n_moves=r['smc_moves'])
|
||||
u = T.u(res['Z'][gamma])
|
||||
tg = data.grid.t_of_tau(u[:, 0], u[:, 1:], data.tau)
|
||||
valid = valid_label_warps(data, o, tg, p['data']['labels'])
|
||||
if valid.sum() < min(256, r['particles']):
|
||||
raise ValueError(f'Insufficient posterior particles covering all measured labels: {o["name"]}, {valid.sum()} valid')
|
||||
tg = tg[valid]
|
||||
post.append(tg)
|
||||
tau_at = invert_warps(tg, data.tau, data.t_main)
|
||||
sd = float(np.mean(np.diff(np.quantile(tau_at, [0.05, 0.95], axis=0), axis=0)) / 3.29)
|
||||
diag.append({'well': o['name'], 'sigma_post_ms': sd, 'gamma': gamma, 'n_stages': len(res['stages']),
|
||||
'valid_label_particles': int(valid.sum()), 'particles_before_label_support_check': len(valid)})
|
||||
bundle = {'wells': np.asarray(names), 'phase0': np.asarray(phase0), 'phase_R': np.asarray(phase_r)}
|
||||
for label in p['data']['labels']:
|
||||
banks = {m: [] for m in ('B2', 'B3a', 'B3b', 'B3c', 'B3c-R', 'B3d', 'B3d-Sa', 'B4', 'M1', 'M2-Sa', 'M2-S256', 'M2-bulk')}
|
||||
lps = {'M1': [], 'M2-Sa': [], 'M2-S256': []}
|
||||
filtered = [antialias(o['labels'][label], f, data.dt) for o in obs]
|
||||
normsel = (data.tau >= data.t_main[0]) & (data.tau <= data.t_main[-1])
|
||||
vals = np.concatenate([y[normsel & o['label_valid'][label]] for o, y in zip(obs, filtered)])
|
||||
bundle[f'{label}/norm'] = np.array([vals.mean(), max(vals.std(), 1e-8)])
|
||||
ref = []
|
||||
for i, (o, smp, tg, y) in enumerate(zip(obs, samples, post, filtered)):
|
||||
def lab(t, times=data.t_main):
|
||||
tau_at = invert_warps(t, data.tau, times)
|
||||
support = np.interp(tau_at, data.tau, o['label_valid'][label].astype(float), left=0, right=0)
|
||||
return np.where(support >= 1-1e-9, labels_for_warps(data.tau, y, np.atleast_2d(t), times), np.nan)
|
||||
anchor_t = data.grid.t_of_tau(smp['b'][:r['S']], smp['g'][:r['S']], data.tau)
|
||||
ya = lab(anchor_t)
|
||||
valid = anchor_valid[i]
|
||||
ya[~valid] = ya[valid][0]
|
||||
likelihood = LL[i][int(np.flatnonzero(PHASES == phase0)[0])][valid]
|
||||
weights = np.full(r['S'], -np.inf)
|
||||
weights[valid], _, _ = temper(likelihood, r['ess_min_frac'])
|
||||
b3b = tie_b3b(o['tau_k'], o['t_k'], data.tau)
|
||||
ref.append(lab(b3b)[0])
|
||||
bank_ties = {'B3b': b3b, 'B3d': warp_mean(anchor_t, weights), 'B3d-Sa': tg.mean(axis=0)}
|
||||
for name, phase in (('B3c', phase0), ('B3c-R', phase_r)):
|
||||
syn = synth_for_warps(data.tau, o['ai_log'], b3b, data.t_fine, data.t,
|
||||
fine_wavelet(rotate_phase(w0, phase), fac))[0]
|
||||
bank_ties[name] = tie_b3c(b3b, data.tau, syn, o['seis'], data.t, data.dt)
|
||||
for method, tie in bank_ties.items():
|
||||
banks[method].append(lab(tie))
|
||||
banks['B2'].append(lab(b3b))
|
||||
banks['B3a'].append(data.y(o['name'], 'legacy', label)[None])
|
||||
banks['M1'].append(ya)
|
||||
lps['M1'].append(np.where(valid, -np.log(valid.sum()), -np.inf))
|
||||
for method, size in (('M2-Sa', r['S']), ('M2-S256', min(256, len(tg)))):
|
||||
sub = np.random.default_rng([r['smc_seed'], i, 29]).choice(len(tg), size, replace=False)
|
||||
banks[method].append(lab(tg[sub]))
|
||||
lps[method].append(np.full(size, -np.log(size)))
|
||||
K = r['shift_K']
|
||||
times = np.arange(data.t_main[0] - K * data.dt, data.t_main[-1] + (K + 0.5) * data.dt, data.dt)
|
||||
wide = lab(b3b, times)[0]
|
||||
banks['B4'].append(np.stack([wide[K+j:K+j+len(data.t_main)] for j in range(-K, K+1)]))
|
||||
prec = 1 / h.sigma_b_ms**2 + len(o['tau_k']) / sigma_a**2
|
||||
bm = np.sum(o['t_k'] - o['tau_k']) / sigma_a**2 / prec
|
||||
b = np.random.default_rng([r['smc_seed'], i, 37]).normal(bm, 1 / np.sqrt(prec), r['particles'])
|
||||
bulk_t = data.tau[None] + b[:, None]
|
||||
good_bulk = valid_label_warps(data, o, bulk_t, p['data']['labels'])
|
||||
if not good_bulk.any():
|
||||
raise ValueError(f'No bulk-only sample covers measured labels: {o["name"]}')
|
||||
syn = synth_for_warps(data.tau, o['ai_log'], bulk_t, data.t_fine, data.t, wf)
|
||||
from ml_porosity.registration.tie_likelihood import profile_loglik
|
||||
ll = np.where(good_bulk, profile_loglik(syn, o['seis']) * diag[i]['gamma'], -np.inf)
|
||||
prob = np.exp(ll - np.logaddexp.reduce(ll))
|
||||
sub = np.random.default_rng([r['smc_seed'], i, 41]).choice(len(b), r['S'], replace=True, p=prob)
|
||||
banks['M2-bulk'].append(lab(bulk_t[sub]))
|
||||
for method, ys in banks.items():
|
||||
a = np.stack(ys).astype(np.float32)
|
||||
if not np.isfinite(a).all():
|
||||
raise ValueError(f'Non-finite label bank {label}/{method}')
|
||||
bundle[f'{label}/{method}'] = a
|
||||
for method, vals in lps.items():
|
||||
bundle[f'{label}/{method}/logpi'] = np.stack(vals).astype(np.float32)
|
||||
bundle[f'{label}/lambda'] = np.asarray(effective_lambda(ref, p['metrics']['f_c_hz'], data.dt)[0])
|
||||
from ml_porosity.eval.metrics import split_bands
|
||||
bundle[f'{label}/lfm'] = split_bands(np.mean(ref, axis=0), p['metrics']['f_c_hz'], data.dt)[0]
|
||||
for o, tg in zip(obs, post):
|
||||
bundle[f'posterior/{o["name"]}/tau_at_main'] = invert_warps(tg, data.tau, data.t_main)
|
||||
meta = {'training_wells': list(names), 'sigma_a_ms': sigma_a, 'no_anchors': no_anchors,
|
||||
'phase0': phase0, 'phase_R': phase_r, 'phase_info': ph, 'hyper': h.as_dict(),
|
||||
'hyper_info': hinfo, 'diagnostics': diag, 'wall_seconds': time.perf_counter() - started}
|
||||
del Ts, Zs, T, T0
|
||||
gc.collect()
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.empty_cache()
|
||||
return bundle, meta
|
||||
Reference in New Issue
Block a user