"""Nested selection, scoring-only registration sensitivity, and the unchanged G-C gate.""" from __future__ import annotations import importlib.util import json from pathlib import Path from types import SimpleNamespace import numpy as np import pandas as pd from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics from ml_porosity.f3.data import F3Data from ml_porosity.f3.progress import update, write_json from ml_porosity.f3.protocol import inner_folds from ml_porosity.f3.runner import job_path, load_bundle from ml_porosity.f3.training import ensemble from ml_porosity.paths import REPO_ROOT def choose_budget(curves: np.ndarray, budgets: list[int]) -> int: """curves=(inner validation wells, budgets); equal weight per well, earliest tie.""" curves = np.asarray(curves, float) if curves.ndim != 2 or curves.shape[1] != len(budgets) or not np.isfinite(curves).all(): raise ValueError('Invalid inner-validation curves') return int(budgets[int(np.argmin(curves.mean(axis=0)))]) def neural_predictions(data: F3Data, p: dict, root: Path) -> tuple[list[dict], list[dict]]: predictions, selections = [], [] variants = [(p['registration']['sigma_a_ms'], lab, m) for lab in p['data']['labels'] for m in p['methods']['main']] variants += [(p['registration']['sigma_a_ms'], lab, m) for lab in p['methods']['ablation_labels'] for m in p['methods']['ablations']] variants += [(sa, lab, m) for sa in p['registration']['sigma_a_sensitivity_ms'] for lab in p['registration']['sensitivity_labels'] for m in p['registration']['sensitivity_methods']] budgets = p['training']['budgets'] for outer in data.wells: for sa, label, method in variants: per_seed = [] for seed in p['split']['seeds']: folds = inner_folds(data.wells, outer) curves, cache = [], [] for validation, train in folds: if outer in train or validation in train: raise RuntimeError('Held-out well entered training') z = load_bundle(job_path(root, train, method, label, seed, sa)) names = list(z['wells']) curves.append([np.mean((z[f'{b}/mu'][names.index(validation)] - data.y(validation, 'calibrated', label))**2) for b in budgets]) cache.append((validation, train, z, names)) budget = choose_budget(np.array(curves), budgets) k = budgets.index(budget) mu, sigma = ensemble(np.stack([z[f'{budget}/mu'][names.index(outer)] for _, _, z, names in cache]), np.stack([z[f'{budget}/sigma'][names.index(outer)] for _, _, z, names in cache])) entry = dict(test_well=outer, method=method, label=label, sigma_a_ms=sa, seed=seed, members=len(folds), mu=mu, sigma=sigma) predictions.append(entry) per_seed.append(entry) selections.append(dict(test_well=outer, method=method, label=label, sigma_a_ms=sa, seed=seed, budget=budget, validation_mse=float(np.mean(np.asarray(curves)[:, k])), validation_wells=';'.join(v for v, _ in folds), training_sets=';'.join(','.join(tr) for _, tr in folds))) mu, sigma = ensemble(np.stack([v['mu'] for v in per_seed]), np.stack([v['sigma'] for v in per_seed])) predictions.append(dict(test_well=outer, method=method, label=label, sigma_a_ms=sa, seed='ensemble', members=sum(v['members'] for v in per_seed), mu=mu, sigma=sigma)) return predictions, selections def gate_verdict(metrics: pd.DataFrame, selection: pd.DataFrame, p: dict) -> dict: primary = metrics[(metrics.label == p['data']['primary_label']) & (metrics.reference == 'calibrated') & (metrics.seed.astype(str) == 'ensemble') & (metrics.sigma_a_ms == p['registration']['sigma_a_ms'])] selected, per_well = {}, [] for well in p['data']['wells']: scores = selection[(selection.test_well == well) & (selection.label == p['data']['primary_label']) & (selection.sigma_a_ms == p['registration']['sigma_a_ms']) & selection.method.isin(p['gate']['point_competitors'])].groupby('method').validation_mse.mean() if len(scores) != len(p['gate']['point_competitors']): return {'evaluated': False, 'pass': None, 'reason': 'Reduced smoke run or incomplete point competitors'} selected[well] = str(scores.idxmin()) candidate = primary[(primary.test_well == well) & (primary.method == p['gate']['candidate'])] base = primary[(primary.test_well == well) & (primary.method == selected[well])] if len(candidate) != 1 or len(base) != 1: raise ValueError(f'Incomplete G-C predictions for {well}') a, b = candidate.iloc[0], base.iloc[0] per_well.append(dict(well=well, competitor=selected[well], ratio=float(a.band_rmse/b.band_rmse), improved=bool(a.band_rmse < b.band_rmse), coverage_80=float(a.coverage_80), coverage_90=float(a.coverage_90))) wins = sum(v['improved'] for v in per_well) c80 = float(np.mean([v['coverage_80'] for v in per_well])) c90 = float(np.mean([v['coverage_90'] for v in per_well])) direction, calibration = wins >= 3, abs(c80-0.8) <= 0.05+1e-12 and abs(c90-0.9) <= 0.05+1e-12 return dict(evaluated=True, direction_pass=direction, improved_wells=wins, coverage_pass=calibration, coverage_80=c80, coverage_90=c90, per_well=per_well, **{'pass': direction and calibration}) def diagnostics(p: dict, root: Path) -> None: from ml_porosity.registration.labels import antialias, labels_for_warps from ml_porosity.registration.pipeline import fit_cell_hyper from ml_porosity.registration.sampler import sample_warps from ml_porosity.registration.warp_prior import loao_zscores from ml_porosity.f3.registration import valid_label_warps smoke = root.name == 'smoke' update(status='Đánh giá độ nhạy registration', message='Log và marker giếng test chỉ được dùng trong giai đoạn chấm điểm.', tasks={} if smoke else {'p3-abl': 'doing'}) data = F3Data(p) refs, rows, metadata = {}, [], [] r = p['registration'] for idx, test in enumerate(data.wells): train_names = tuple(w for w in data.wells if w != test) train_obs = data.training_observations(train_names) h, info = fit_cell_hyper(SimpleNamespace(grid=data.grid), train_obs, r, 0) o = data.training_observations((test,))[0] anchor = {'grid': data.grid, 'tau_k': o['tau_k'], 'd_k': o['t_k']-o['tau_k']} zs = loao_zscores([anchor], h)[0] for k, z in enumerate(zs): rows.append(dict(well=test, anchor=k, twt_ms=float(o['t_k'][k]), z=float(z), inside90=bool(abs(z) <= 1.6448536269514722), approximation='linearized_anchor_GP', hyper_training_wells=';'.join(train_names))) count = p['data']['posterior_reference_samples'] smp = sample_warps(data.grid, h, o['tau_k'], o['t_k'], 4*count, r['g_max'], np.random.default_rng([idx, 53])) tg = data.grid.t_of_tau(smp['b'], smp['g'], data.tau) valid = valid_label_warps(data, o, tg, p['data']['labels']) if valid.sum() < count: raise ValueError(f'Insufficient scoring-reference samples covering measured labels: {test}') tg = tg[valid][:count] for label in p['data']['labels']: y = antialias(o['labels'][label], r['fine_dt_ms'], data.dt) ref = labels_for_warps(data.tau, y, tg, data.t_main) if not np.isfinite(ref).all(): raise ValueError(f'Non-finite posterior scoring reference: {test}/{label}') refs[f'{test}/{label}'] = ref metadata.append(dict(scoring_well=test, prior_training_wells=train_names, hyper=h.as_dict(), hyper_info=info, valid_samples_before_selection=int(valid.sum()), samples_scored=count)) dest = root/'diagnostics' dest.mkdir(parents=True, exist_ok=True) pd.DataFrame(rows).to_csv(dest/'loao.csv', index=False) np.savez_compressed(dest/'evaluation_references.npz', **refs) write_json(dest/'evaluation_references.json', {'role': 'scoring sensitivity only; never checkpoint selection', 'folds': metadata}) update(status='Đã tính độ nhạy tham chiếu', message='LOAO là xấp xỉ GP chỉ dùng anchor; trạng thái ablation chỉ hoàn tất sau khi tổng hợp đầy đủ.') def classical_predictions(data: F3Data, p: dict) -> list[dict]: spec = importlib.util.spec_from_file_location('p1_lowo', REPO_ROOT/'scripts/05_lowo.py') mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) import yaml prior = yaml.safe_load((REPO_ROOT/'configs/protocol.yaml').read_text(encoding='utf-8')) d = mod.Data(prior) d.proto = prior result = [] for label in p['data']['labels']: for test in data.wells: pred, _ = mod.run_classical(d, label, test, p['split']['seeds']) for method in sorted({m for m, *_ in pred}): mu = np.mean([a for m, _, a, _ in pred if m == method], axis=0) result.append(dict(test_well=test, method=method, label=label, sigma_a_ms=p['registration']['sigma_a_ms'], seed='ensemble', members=sum(m == method for m, *_ in pred), mu=mu, sigma=None)) return result def score(data: F3Data, pred: dict, reference: str, f_c: float) -> dict: y, mu = 100*data.y(pred['test_well'], reference, pred['label']), 100*pred['mu'] row = {k: v for k, v in pred.items() if k not in ('mu', 'sigma')} row |= dict(reference=reference, f_c_hz=f_c) | point_metrics(y, mu) | band_metrics(y, mu, f_c, data.dt) if pred['sigma'] is not None: row |= gaussian_metrics(y, mu, np.maximum(100*pred['sigma'], 1e-6)) return row def summarize(p: dict, root: Path) -> dict: data = F3Data(p) pred, sel = neural_predictions(data, p, root) smoke = root.name == 'smoke' if not smoke and p['methods']['classical']: pred += classical_predictions(data, p) rows = [score(data, a, ref, p['metrics']['f_c_hz']) for a in pred for ref in p['data']['references']] frame, selections = pd.DataFrame(rows), pd.DataFrame(sel) gate = gate_verdict(frame, selections, p) if smoke: gate = {'evaluated': False, 'pass': None, 'reason': 'Smoke run; not the registered P3 experiment'} dest = root/'summary' dest.mkdir(parents=True, exist_ok=True) frame.to_csv(dest/'metrics.csv', index=False) selections.to_csv(dest/'selection.csv', index=False) main = frame[(frame.seed.astype(str) == 'ensemble') & (frame.reference == 'calibrated') & (frame.sigma_a_ms == p['registration']['sigma_a_ms'])] cols = ['rmse', 'pcc', 'r2', 'band_rmse', 'band_pcc', 'std_ratio', 'coverage_80', 'coverage_90', 'nll', 'crps'] macro = main.groupby(['label', 'method'])[cols].mean().reset_index() macro.to_csv(dest/'macro.csv', index=False) cutoff = [score(data, a, 'calibrated', fc) for a in pred if a['seed'] == 'ensemble' for fc in p['metrics']['sensitivity_f_c_hz']] pd.DataFrame(cutoff).to_csv(dest/'band_sensitivity.csv', index=False) posterior_rows = [] reference_file = root/'diagnostics/evaluation_references.npz' if reference_file.exists(): refs = load_bundle(reference_file) for a in pred: if a['seed'] != 'ensemble': continue vals = [point_metrics(100*y, 100*a['mu']) | band_metrics(100*y, 100*a['mu'], p['metrics']['f_c_hz']) for y in refs[f'{a["test_well"]}/{a["label"]}']] item = {k: v for k, v in a.items() if k not in ('mu', 'sigma')} for metric in ('rmse', 'pcc', 'band_rmse', 'band_pcc'): item |= {f'{metric}_q05': float(np.quantile([v[metric] for v in vals], .05)), f'{metric}_q95': float(np.quantile([v[metric] for v in vals], .95))} posterior_rows.append(item) pd.DataFrame(posterior_rows).to_csv(dest/'posterior_reference_sensitivity.csv', index=False) diag_shift = [] for a in pred: if a['seed'] != 'ensemble': continue y, mu = data.y(a['test_well'], 'calibrated', a['label']), a['mu'] candidates = [] for shift in range(-16, 17): start, stop = max(0, -shift), min(len(y), len(y)-shift) candidates.append((point_metrics(y[start:stop], mu[start+shift:stop+shift])['pcc'], shift)) _, lag = max(candidates) diag_shift.append({k: v for k, v in a.items() if k not in ('mu', 'sigma')} | {'best_shift_ms': lag*data.dt}) pd.DataFrame(diag_shift).to_csv(dest/'best_shift_DIAGNOSTIC_ONLY.csv', index=False) saved = {} for i, a in enumerate(pred): saved[f'{i}/mu'] = a['mu'] if a['sigma'] is not None: saved[f'{i}/sigma'] = a['sigma'] np.savez_compressed(dest/'predictions.npz', times_ms=data.t_main, **saved) write_json(dest/'prediction_index.json', [{k: v for k, v in a.items() if k not in ('mu', 'sigma')} for a in pred]) write_json(dest/'gate_gc.json', gate) text = ['# P3 F3 — nested LOWO', '', 'Smoke only; no scientific verdict.' if smoke else 'Registered protocol_f3; outer labels are scoring-only.', '', 'G-C: ' + json.dumps(gate, ensure_ascii=False), '', '## Macro over four wells (p.u.)', '', macro.to_markdown(index=False, floatfmt='.4f'), '', 'Per-well and per-seed results: metrics.csv. Epoch selection: selection.csv.', 'Registration-reference sensitivity and best-shift diagnostics never alter the primary scores.', 'LOAO is an anchor-only linear GP approximation; maps and four wells do not establish field-wide geological validity.'] (dest/'summary.md').write_text('\n'.join(text)+'\n', encoding='utf-8') plot_results(data, p, pred, dest) if not smoke: diagnostics_done = reference_file.exists() and (root/'diagnostics/loao.csv').exists() update(status='LOWO đã hoàn tất', message=f'G-C: {"ĐẠT" if gate.get("pass") else "KHÔNG ĐẠT"}; giữ nguyên mọi ngưỡng. Volume là bước riêng.', gate=gate, completed=None, total=None, eta_seconds=None, tasks={'p3-lowo': 'done', 'p3-abl': 'done' if diagnostics_done else 'doing'}) return gate def plot_results(data: F3Data, p: dict, pred: list[dict], dest: Path) -> None: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 4, figsize=(15, 6), sharey=True, sharex=True, layout='constrained') for ax, w in zip(axes, data.wells): ax.plot(100*data.y(w, 'calibrated', p['data']['primary_label']), data.t_main, 'k', label='Reference') for method, color, style in (('B3b', '#0072B2', '--'), ('B3d-Sa', '#8F5800', ':'), ('M2-Sa', '#CC3311', '-')): rows = [a for a in pred if a['test_well'] == w and a['label'] == p['data']['primary_label'] and a['method'] == method and a['seed'] == 'ensemble' and a['sigma_a_ms'] == p['registration']['sigma_a_ms']] if rows: a = rows[0] ax.plot(100*a['mu'], data.t_main, color=color, linestyle=style, label=method) if method == 'M2-Sa': ax.fill_betweenx(data.t_main, 100*(a['mu']-1.64485*a['sigma']), 100*(a['mu']+1.64485*a['sigma']), color=color, alpha=.18) ax.set(title=w, xlabel='Sonic-derived porosity (p.u.)') ax.grid(alpha=.2) axes[0].set_ylabel('TWT (ms)') axes[0].invert_yaxis() axes[0].legend(fontsize=8) fig.savefig(dest/'wells.png', dpi=160) fig.savefig(dest/'wells.pdf') plt.close(fig) write_json(dest/'figure_manifest.json', {'source': 'predictions.npz and prediction_index.json', 'reference': 'marker-calibrated sonic', 'uncertainty': 'nominal 90% moment-matched Gaussian predictive interval; calibration is evaluated separately', 'replication_unit': 'well (n=4); network seeds are computational repeats', 'transform': 'porosity fraction multiplied by 100', 'filters': 'See protocol_f3; no plotting smoothing', 'publisher_requirements': 'not yet verified', 'description': 'Four well panels show reference and blind predictions against downward-increasing two-way time; M2-Sa carries its nominal predictive interval.'})