"""P3 invariants: well-level separation, inner-only selection, uncertainty and safe resume.""" from __future__ import annotations import copy import json from pathlib import Path import numpy as np import pandas as pd import pytest import torch from ml_porosity.f3.data import F3Data from ml_porosity.f3.evaluation import choose_budget, gate_verdict, neural_predictions from ml_porosity.f3.protocol import digest, inner_folds, load_protocol, training_sets from ml_porosity.f3.runner import job_path, reusable from ml_porosity.f3.training import ensemble, make_model, method_spec, train_trajectory from ml_porosity.f3.volume import deployment_budget, predict_batch @pytest.fixture def f3_data(tmp_path, monkeypatch): p = copy.deepcopy(load_protocol()) p['data']['labels'] = ['PHIE_DT'] p['split']['seeds'] = [0] p['methods'].update(main=['M2-Sa'], ablations=[], ablation_labels=[]) p['registration']['sigma_a_sensitivity_ms'] = [] p['training']['budgets'] = [1, 2] times = np.arange(600., 1104., 4.) a = {} for i, w in enumerate(p['data']['wells']): a[f'{w}/times_ms'] = times a[f'{w}/main_mask'] = np.ones(len(times), bool) a[f'{w}/seismic_patch'] = np.random.default_rng(i).normal(size=(9, len(times))) a[f'{w}/anchors_md'] = np.array([1., 2.]) for ref in ('calibrated', 'wlt'): a[f'{w}/{ref}/PHIE_DT'] = .2+.01*np.sin(np.arange(len(times))*.1)+i*.01 np.savez_compressed(tmp_path/'f3_wells.npz', **a) monkeypatch.setattr('ml_porosity.f3.data.outputs_dir', lambda: tmp_path) return p, a, tmp_path def test_training_view_has_no_held_out_logs_or_markers(f3_data): p, _, _ = f3_data train = tuple(p['data']['wells'][:2]) d = F3Data(p, training_wells=train) outer = p['data']['wells'][-1] assert d.X(outer).shape == (9, 126) assert f'{outer}/anchors_md' not in d.arrays assert f'{outer}/calibrated/PHIE_DT' not in d.arrays with pytest.raises(RuntimeError, match='Held-out labels'): d.y(outer, 'calibrated', 'PHIE_DT') with pytest.raises(RuntimeError, match='Held-out logs'): d.training_observations((outer,)) def test_inner_folds_keep_entire_wells_out(): wells = ['a', 'b', 'c', 'd'] for outer in wells: folds = inner_folds(wells, outer) assert len(folds) == 3 for valid, train in folds: assert len(train) == 2 and outer not in train and valid not in train assert set(train) | {valid, outer} == set(wells) assert len(training_sets(wells)) == 6 def test_changing_outer_labels_cannot_change_its_checkpoint_or_prediction(f3_data): p, arrays, root = f3_data for train in training_sets(p['data']['wells']): path = job_path(root, train, 'M2-Sa', 'PHIE_DT', 0) path.parent.mkdir(parents=True, exist_ok=True) pred = {'wells': np.asarray(p['data']['wells'])} for budget in (1, 2): pred[f'{budget}/mu'] = np.stack([arrays[f'{w}/calibrated/PHIE_DT']+budget*.001 for w in p['data']['wells']]) pred[f'{budget}/sigma'] = np.ones((4, 126))*.01 np.savez_compressed(path, **pred) target = p['data']['wells'][0] before, chosen_before = neural_predictions(F3Data(p), p, root) arrays[f'{target}/calibrated/PHIE_DT'] += 100 np.savez_compressed(root/'f3_wells.npz', **arrays) after, chosen_after = neural_predictions(F3Data(p), p, root) assert [a['budget'] for a in chosen_before if a['test_well'] == target] == [a['budget'] for a in chosen_after if a['test_well'] == target] for a, b in zip([a for a in before if a['test_well'] == target], [a for a in after if a['test_well'] == target]): np.testing.assert_array_equal(a['mu'], b['mu']) np.testing.assert_array_equal(a['sigma'], b['sigma']) def test_ensemble_uses_total_variance_not_mean_sigma(): mean, sigma = ensemble(np.array([[0., 2.], [2., 4.]]), np.array([[1., 1.], [1., 1.]])) np.testing.assert_allclose(mean, [1., 3.]) np.testing.assert_allclose(sigma, np.sqrt(2)) def test_volume_preserves_small_predictive_variance(): class ConstantModel(torch.nn.Module): def forward(self, x): mu = torch.full((len(x), 1, x.shape[-1]), 1000., device=x.device) return mu, torch.full_like(mu, 1e-6) mu, sigma = predict_batch([(ConstantModel(), 0., 1.) for _ in range(20)], np.zeros((2, 9, 126)), 'cpu') np.testing.assert_allclose(mu, 1000.) np.testing.assert_allclose(sigma, 1e-6, rtol=1e-5) def test_warp_support_rejects_unmeasured_labels_and_gaps(): from types import SimpleNamespace from ml_porosity.f3.registration import valid_label_warps tau = np.arange(0., 100., 1.) data = SimpleNamespace(tau=tau, t_main=np.arange(20., 30.)) valid = np.ones(len(tau), bool) valid[50:60] = False obs = {'label_valid': {'PHIE_DT': valid}} # Identity stays measured; the shifted map sends the same scoring times into a missing interval. warps = np.stack([tau, tau-30, tau+60]) np.testing.assert_array_equal(valid_label_warps(data, obs, warps, ['PHIE_DT']), [True, False, False]) def test_budget_ties_choose_earliest(): assert choose_budget(np.array([[3., 1., 1.], [1., 1., 1.]]), [1, 2, 3]) == 2 assert deployment_budget([125, 250], [125, 250]) == 125 def test_gc_does_not_choose_baseline_from_outer_metrics(): p = load_protocol() metrics, selection = [], [] for w in p['data']['wells']: for m, rmse in [('M2-Sa', .9), ('B3b', 1.0), ('B3c', .1), ('B3c-R', .2)]: metrics.append(dict(label='PHIE_DT', reference='calibrated', seed='ensemble', sigma_a_ms=7., test_well=w, method=m, band_rmse=rmse, coverage_80=.8, coverage_90=.9)) for m, mse in [('B3b', 1.), ('B3c', 2.), ('B3c-R', 3.)]: selection.append(dict(label='PHIE_DT', sigma_a_ms=7., test_well=w, method=m, validation_mse=mse)) frame, sel = pd.DataFrame(metrics), pd.DataFrame(selection) g = gate_verdict(frame, sel, p) assert g['pass'] and g['improved_wells'] == 4 assert all(r['competitor'] == 'B3b' for r in g['per_well']) frame.loc[frame.method == 'M2-Sa', 'coverage_90'] = .79 g = gate_verdict(frame, sel, p) assert g['direction_pass'] and not g['coverage_pass'] and not g['pass'] def test_resume_refuses_missing_or_changed_checkpoint(tmp_path): path = tmp_path/'train/job.npz' path.parent.mkdir() np.savez_compressed(path, mu=np.ones((2, 126))) checkpoint = path.with_suffix('.pt') torch.save({'example': torch.ones(1)}, checkpoint) meta = {'fingerprint': 'test', 'artifact_sha256': digest(path), 'checkpoint_sha256': digest(checkpoint)} path.with_suffix('.json').write_text(json.dumps(meta), encoding='utf-8') assert reusable(path, 'test') checkpoint.write_bytes(b'changed') with pytest.raises(RuntimeError, match='checkpoint'): reusable(path, 'test') @pytest.mark.parametrize('method', ['B2', 'B3b', 'B4a', 'B4b', 'B4c', 'B4d', 'M1', 'M2-Sa', 'M2-anchor-only', 'M2-bulk', 'M2-lambda1', 'M2-S1', 'M2-S8', 'M2-S256', 'M2-fixed-sigma', 'M2-legacy-loss', 'M2-TCN', 'B3d-Sa-TCN', 'M2-LFM']) def test_every_training_branch_and_checkpoint_replays(method, tmp_path): p = load_protocol() rng = np.random.default_rng(7) bundle = {'PHIE_DT/norm': np.array([0., 1.]), 'PHIE_DT/lambda': np.array(.37)} for m, size in [('B2', 1), ('B3b', 1), ('B3d-Sa', 1), ('B4', 17), ('M1', 64), ('M2-Sa', 64), ('M2-S256', 256), ('M2-bulk', 64)]: bundle[f'PHIE_DT/{m}'] = rng.normal(size=(2, size, 126)).astype(np.float32) spec = method_spec(bundle, 'PHIE_DT', method, p) cfg = p['training'] | {'d_channels': 8, 'fixed_sigma': 1.0} channels = 10 if method == 'M2-LFM' else 9 X = rng.normal(size=(2, channels, 126)).astype(np.float32) path = tmp_path/'model.pt' pred, meta = train_trajectory(X, X, spec, method, cfg, 0, [1, 2], 'cpu', path) assert meta['steps'] == 2 and np.isfinite(pred['2/mu']).all() saved = torch.load(path, map_location='cpu', weights_only=True) model = make_model(saved['method'], channels, saved['config']) model.load_state_dict(saved['states'][2]) from ml_porosity.models.train import predict mu, sigma = predict(model, X, 'cpu') np.testing.assert_allclose(mu, pred['2/mu'], atol=1e-6) if sigma is not None: np.testing.assert_allclose(sigma, pred['2/sigma'], atol=1e-6) @pytest.mark.parametrize('no_anchors', [False, True]) def test_registration_pipeline_on_synthetic_wells_only(no_anchors): from types import SimpleNamespace from ml_porosity.f3.registration import register_set from ml_porosity.data.wavelet import statistical_wavelet from ml_porosity.registration.tie_likelihood import fine_wavelet, synth_for_warps from ml_porosity.registration.warp_prior import WarpGrid p = copy.deepcopy(load_protocol()) p['registration'].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0, phase_max_extra=0, fine_dt_ms=2., warp_dtau_ms=40.) tau = np.arange(200., 1501., 2.) t = np.arange(400., 1301., 4.) main = t[(t >= 600) & (t <= 1100)] tf = np.arange(100., 1601., 2.) rng = np.random.default_rng(19) w0 = statistical_wavelet(rng.normal(size=(2, len(t))), 4., 128.) obs = [] for i, name in enumerate(('train_a', 'train_b')): ai = 8000+600*np.sin(tau/25+i)+200*np.cos(tau/11) phi = .25+.02*np.sin(tau/25+i) syn = synth_for_warps(tau, ai, tau, tf, t, fine_wavelet(w0, 2))[0] seis = syn+rng.normal(size=len(syn))*max(syn.std(), 1e-8)*.1 anchors = np.arange(400., 1301., 100.) obs.append(dict(name=name, ai_log=ai, labels={'PHIE_DT': phi, 'PHIE': phi}, label_valid={lab: np.ones(len(tau), bool) for lab in ('PHIE_DT', 'PHIE')}, seis=seis, tau_k=anchors, t_k=anchors+rng.normal(size=len(anchors)))) toy = SimpleNamespace(grid=WarpGrid(200., 1500., 40.), tau=tau, t=t, t_main=main, t_fine=tf, dt=4., training_observations=lambda names: obs, y=lambda name, ref, label: np.interp(main, tau, obs[0 if name == 'train_a' else 1]['labels'][label])) bundle, meta = register_set(toy, ('train_a', 'train_b'), p, 'cpu', no_anchors=no_anchors) assert meta['training_wells'] == ['train_a', 'train_b'] assert bundle['PHIE_DT/M2-Sa'].shape == (2, 8, 126) assert np.isfinite(bundle['PHIE_DT/M2-Sa']).all() assert np.isfinite(bundle['PHIE_DT/B3d-Sa']).all()