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:
2026-10-28 07:01:08 +07:00
parent a22f9d951f
commit 9976abc96b
50 changed files with 2738 additions and 219 deletions

View File

@@ -0,0 +1 @@
"""P3: blind-well F3 experiments, separate from the frozen P1/P2 protocols."""

85
ml_porosity/f3/data.py Normal file
View File

@@ -0,0 +1,85 @@
"""Explicit separation between training logs, seismic-only targets, and scoring references."""
from __future__ import annotations
import numpy as np
from ml_porosity.data.las_io import load_well
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import sonic_tdr
from ml_porosity.models.bank_train import zscore_patch
from ml_porosity.paths import outputs_dir
from ml_porosity.registration.warp_prior import WarpGrid
class F3Data:
def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None):
self.protocol = protocol
self.wells = protocol['data']['wells']
self.training_wells = None if training_wells is None else frozenset(training_wells)
if self.training_wells is not None and not self.training_wells <= set(self.wells):
raise ValueError('Unknown training well')
public = {'seismic_patch', 'times_ms', 'main_mask', 'il', 'xl', 'x', 'y'}
with np.load(outputs_dir() / 'f3_wells.npz') as z:
self.arrays = {k: z[k] for k in z.files if self.training_wells is None
or k.split('/', 1)[0] in self.training_wells or k.split('/', 1)[1] in public}
self.t = self.ext(self.wells[0], 'times_ms')
self.main = self.ext(self.wells[0], 'main_mask').astype(bool)
self.t_main = self.t[self.main]
r = protocol['registration']
self.dt = float(np.diff(self.t)[0])
self.grid = WarpGrid(*r['tau_range_ms'], r['warp_dtau_ms'])
self.tau = np.arange(*[r['tau_range_ms'][0], r['tau_range_ms'][1] + r['fine_dt_ms'] / 2, r['fine_dt_ms']])
self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + r['fine_dt_ms'] / 2, r['fine_dt_ms'])
for w in self.wells:
if not np.array_equal(self.ext(w, 'times_ms'), self.t):
raise ValueError('F3 well time axes differ')
if self.training_wells is not None and w not in self.training_wells:
continue
for label in protocol['data']['labels']:
for ref in protocol['data']['references']:
if not np.isfinite(self.y(w, ref, label)).all():
raise ValueError(f'Non-finite scoring labels: {w}/{ref}/{label}')
def ext(self, well: str, key: str):
return self.arrays[f'{well}/{key}']
def X(self, well: str) -> np.ndarray:
return zscore_patch(self.ext(well, 'seismic_patch'), self.main)
def y(self, well: str, reference: str, label: str) -> np.ndarray:
if self.training_wells is not None and well not in self.training_wells:
raise RuntimeError('Held-out labels are unavailable in a training data view')
return self.ext(well, f'{reference}/{label}')[self.main]
def training_observations(self, names: tuple[str, ...], omit_anchor: tuple[str, int] | None = None) -> list[dict]:
"""Only named wells are loaded here; callers pass the exact inner training set."""
if self.training_wells is not None and not set(names) <= self.training_wells:
raise RuntimeError('Held-out logs and anchors are unavailable in a training data view')
obs = []
for name in names:
w = load_well(name)
cs = w.checkshot
base = sonic_tdr(w.md, w.curve('DT'), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
tk = cs.twt_ms.to_numpy()
tau_k = base.time_at(cs.md.to_numpy())
mask = (tk >= self.t[0]) & (tk <= self.t[-1])
tau_k, tk = tau_k[mask], tk[mask]
if omit_anchor is not None and omit_anchor[0] == name:
keep = np.arange(len(tk)) != omit_anchor[1]
tau_k, tk = tau_k[keep], tk[keep]
kwargs = dict(fine_dt_ms=0.25, cutoff_frac=0.8)
curves = {'AI': w.curve('AI'), 'PHIE_DT': -0.2018 + 0.0011 * w.curve('DT'), 'PHIE': w.curve('PHIE')}
resampled = {}
valid_labels = {}
for label, values in curves.items():
v = log_to_time(w.md, values, base, self.tau, **kwargs)
good = np.isfinite(v)
if good.sum() < 2:
raise ValueError(f'No sonic-domain log: {name}/{label}')
resampled[label] = np.interp(self.tau, self.tau[good], v[good])
if label != 'AI':
valid_labels[label] = good
obs.append({'name': name, 'tau_k': tau_k, 't_k': tk, 'ai_log': resampled.pop('AI'),
'labels': resampled, 'label_valid': valid_labels,
'seis': self.ext(name, 'seismic_patch')[4].astype(float)})
return obs

View File

@@ -0,0 +1,269 @@
"""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.'})

View File

@@ -0,0 +1,31 @@
"""One parent writer publishes JSON and a local-file-compatible report.html sidecar."""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from ml_porosity.paths import outputs_dir
def write_json(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + f'.{os.getpid()}.tmp')
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False, default=str), encoding='utf-8')
tmp.replace(path)
def update(**values) -> dict:
root = outputs_dir() / 'p3'
path = root / 'progress.json'
old = json.loads(path.read_text(encoding='utf-8')) if path.exists() else {}
if 'tasks' in values:
values['tasks'] = old.get('tasks', {}) | values['tasks']
state = old | values | {'updated': datetime.now().astimezone().isoformat(timespec='seconds')}
write_json(path, state)
js = root / 'progress.js'
tmp = js.with_suffix('.js.tmp')
tmp.write_text('window.ML_POROSITY_P3 = ' + json.dumps(state, ensure_ascii=False, default=str) + ';\n', encoding='utf-8')
tmp.replace(js)
return state

View File

@@ -0,0 +1,99 @@
"""Portable protocol locking and resume fingerprints for P3."""
from __future__ import annotations
import hashlib
import importlib.metadata
import itertools
import json
import platform
from datetime import datetime, timezone
from pathlib import Path
import yaml
from ml_porosity.paths import REPO_ROOT, f3_root, f3_segy, outputs_dir
CONFIG = REPO_ROOT / 'configs/protocol_f3.yaml'
LOCK = REPO_ROOT / 'configs/protocol_f3.lock.json'
def digest(path: Path, text: bool = False) -> str:
h = hashlib.sha256()
if text:
h.update(path.read_bytes().replace(b'\r\n', b'\n'))
else:
with path.open('rb') as f:
for chunk in iter(lambda: f.read(8 * 1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def source_hash() -> str:
h = hashlib.sha256()
paths = sorted((REPO_ROOT / 'ml_porosity').rglob('*.py'))
paths += sorted((REPO_ROOT / 'scripts').glob('*.py'))
paths += [REPO_ROOT/'scripts/run_p3.ps1']
paths += [REPO_ROOT / 'pyproject.toml']
for p in paths:
h.update(p.relative_to(REPO_ROOT).as_posix().encode() + b'\0')
h.update(p.read_bytes().replace(b'\r\n', b'\n') + b'\0')
return h.hexdigest()
def environment() -> dict:
packages = ('torch', 'numpy', 'scipy', 'pandas', 'matplotlib', 'segyio', 'lasio', 'pylops',
'numba', 'scikit-learn', 'PyYAML', 'tabulate', 'psutil')
return {'python': platform.python_version(), 'platform': platform.system(),
'packages': {name: importlib.metadata.version(name) for name in packages}}
def load_protocol() -> dict:
return yaml.safe_load(CONFIG.read_text(encoding='utf-8'))
def training_sets(wells: list[str], size: int = 2) -> list[tuple[str, ...]]:
return list(itertools.combinations(sorted(wells), size))
def inner_folds(wells: list[str], outer: str) -> list[tuple[str, tuple[str, ...]]]:
if outer not in wells:
raise ValueError(outer)
train = [w for w in wells if w != outer]
return [(v, tuple(sorted(w for w in train if w != v))) for v in train]
def freeze(check: bool = False) -> dict:
p = load_protocol()
data = outputs_dir() / 'f3_wells.npz'
files = [data, REPO_ROOT/'configs/d1_f3.yaml', REPO_ROOT/'configs/protocol.yaml', f3_root()/'.survey']
files += sorted(f3_root().glob('WellInfo/*.wlt'))
files += sorted((f3_root() / 'Rawdata/Well_data').rglob('*.las'))
files += sorted((f3_root() / 'Rawdata/Well_data').rglob('*_TD.txt'))
protected = [outputs_dir()/'wavelets.npz', outputs_dir()/'p2/warp_prior_f3.json']
stamp = {'protocol_sha256': digest(CONFIG, True), 'code_sha256': source_hash(), 'environment': environment(),
'protected_artifacts': {str(f.relative_to(REPO_ROOT)): digest(f) for f in protected},
'inputs': {str(f.relative_to(REPO_ROOT)): digest(f) for f in files}}
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'P3 lock mismatch: {k}. Preserve results and create a new protocol version.')
return old
if check:
raise RuntimeError('P3 is not locked. Run the lock stage before registration/training.')
if any((outputs_dir() / 'p3' / d).exists() for d in ('registration', 'train', 'summary')):
raise RuntimeError('Refusing a first lock after P3 results already exist.')
manifest = json.loads((REPO_ROOT / 'data_manifest/f3_demo_2023.json').read_text(encoding='utf-8'))
expected = manifest['files']['Rawdata/F3_entire.segy']['sha256']
if digest(f3_segy()) != expected:
raise RuntimeError('F3 cube differs from the audited source.')
stamp |= {'locked_utc': datetime.now(timezone.utc).isoformat(), 'segy_sha256': expected,
'canonical_text': 'UTF-8, CRLF normalized to LF for code and protocol; 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_f3.yaml\n', encoding='utf-8')
return stamp
def fingerprint(stamp: dict, **settings) -> str:
return hashlib.sha256(json.dumps({'lock': stamp, **settings}, sort_keys=True).encode()).hexdigest()

View 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

336
ml_porosity/f3/runner.py Normal file
View File

@@ -0,0 +1,336 @@
"""Resumable P3 stages. Worker processes never write report.html or select checkpoints."""
from __future__ import annotations
import copy
import itertools
import json
import os
import subprocess
import sys
import time
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from multiprocessing import get_context
from pathlib import Path
import numpy as np
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.progress import update, write_json
from ml_porosity.f3.protocol import digest, fingerprint, freeze, training_sets
from ml_porosity.paths import REPO_ROOT, outputs_dir
def set_name(names) -> str:
return '__'.join(sorted(names))
def reg_path(root: Path, names, sigma_a: float = 7, no_anchors: bool = False) -> Path:
return root / 'registration' / f'{set_name(names)}_sa{sigma_a:g}{"_noanchors" if no_anchors else ""}.npz'
def job_path(root: Path, names, method: str, label: str, seed: int, sigma_a: float = 7) -> Path:
return root / 'train' / f'{set_name(names)}__{method}__{label}__s{seed}__sa{sigma_a:g}.npz'
def load_bundle(path: Path) -> dict:
with np.load(path) as z:
return {k: z[k] for k in z.files}
def reusable(path: Path, key: str) -> bool:
meta = path.with_suffix('.json')
if not path.exists() or not meta.exists():
return False
stored = json.loads(meta.read_text(encoding='utf-8'))
if stored.get('fingerprint') != key:
raise RuntimeError(f'Resume fingerprint mismatch: {path}. Use a new output directory.')
expected = stored.get('artifact_sha256')
if expected is None or digest(path) != expected:
raise RuntimeError(f'Missing or mismatched completed-artifact checksum: {path}')
if path.parent.name == 'train':
checkpoint = path.with_suffix('.pt')
if not checkpoint.exists() or digest(checkpoint) != stored.get('checkpoint_sha256'):
raise RuntimeError(f'Missing or mismatched model checkpoint: {checkpoint}')
with np.load(path) as z:
if not z.files:
raise RuntimeError(f'Empty completed artifact: {path}')
for k in z.files:
a = z[k]
if np.issubdtype(a.dtype, np.number):
valid = (not np.isnan(a).any() and not np.isposinf(a).any() and np.isfinite(a).any(axis=-1).all()) if k.endswith('/logpi') else np.isfinite(a).all()
if not valid:
raise RuntimeError(f'Corrupt/non-finite artifact: {path}/{k}')
return True
def registration_worker(job: dict) -> dict:
import torch
from ml_porosity.f3.registration import register_set
torch.set_num_threads(job['p']['runtime']['cpu_threads_per_worker'])
data = F3Data(job['p'], training_wells=tuple(job['names']))
path = reg_path(Path(job['root']), job['names'], job['sa'], job['no_anchors'])
if reusable(path, job['key']):
return {'cached': True, 'path': str(path)}
bundle, meta = register_set(data, tuple(job['names']), job['p'], job['device'], job['sa'], job['no_anchors'])
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix('.tmp.npz')
np.savez_compressed(tmp, **bundle)
tmp.replace(path)
write_json(path.with_suffix('.json'), meta | {'fingerprint': job['key'], 'artifact_sha256': digest(path)})
return {'cached': False, 'path': str(path), **meta}
def training_worker(job: dict) -> dict:
from ml_porosity.f3.training import method_spec, train_trajectory
root, p = Path(job['root']), job['p']
path = job_path(root, job['names'], job['method'], job['label'], job['seed'], job['sa'])
if reusable(path, job['key']):
return {'cached': True, 'path': str(path)}
data = F3Data(p, training_wells=tuple(job['names']))
bundle = load_bundle(reg_path(root, job['names'], job['sa'], job['method'] == 'M2-no-anchors'))
if tuple(bundle['wells']) != tuple(sorted(job['names'])):
raise RuntimeError('Training cache contains different wells')
all_names = list(p['data']['wells'])
Xall = np.stack([data.X(w) for w in all_names])
if job['method'] == 'M2-LFM':
m, s = bundle[f'{job["label"]}/norm']
lfm = (bundle[f'{job["label"]}/lfm'] - m) / s
Xall = np.concatenate([Xall, np.broadcast_to(lfm, (len(Xall), 1, len(lfm)))], axis=1)
X = Xall[[all_names.index(w) for w in job['names']]]
spec = method_spec(bundle, job['label'], job['method'], p)
path.parent.mkdir(parents=True, exist_ok=True)
ckpt = path.with_suffix('.pt')
pred, meta = train_trajectory(X, Xall, spec, job['method'], p['training'] | {'fixed_sigma': p['methods']['fixed_sigma']},
job['seed'], p['training']['budgets'], job['device'], ckpt)
mean, sd = bundle[f'{job["label"]}/norm']
for k in pred:
pred[k] = pred[k] * sd + (mean if k.endswith('/mu') else 0)
pred['wells'] = np.asarray(all_names)
pred['norm'] = bundle[f'{job["label"]}/norm']
tmp = path.with_suffix('.tmp.npz')
np.savez_compressed(tmp, **pred)
tmp.replace(path)
write_json(path.with_suffix('.json'), meta | {'fingerprint': job['key'], 'artifact_sha256': digest(path),
'checkpoint_sha256': digest(ckpt), 'training_wells': job['names'],
'label': job['label'], 'method': job['method'], 'seed': job['seed'], 'sigma_a_ms': job['sa']})
return {'cached': False, 'path': str(path), **meta}
def run_jobs(jobs: list[dict], fn, workers: int, stage: str) -> list[dict]:
started = time.perf_counter()
results = []
smoke = bool(jobs and Path(jobs[0]['root']).name == 'smoke')
task = 'p3-review' if smoke else 'p3-vol' if stage.startswith('volume-') else 'p3-lowo'
update(status=f'{"Smoke test — " if smoke else ""}Đang chạy {stage}', message='Mỗi job chỉ nhận đúng tập giếng train; smoke không phải kết quả chính.',
completed=0, total=len(jobs), eta_seconds=None, error=None, tasks={task: 'doing'})
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context('spawn')) as pool:
futures = {pool.submit(fn, job): job for job in jobs}
pending = set(futures)
while pending:
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
if not done:
update(elapsed_seconds=time.perf_counter()-started,
message=f'{stage}: {len(results)}/{len(jobs)} job; scheduler đang chờ {min(workers, len(pending))} worker. Chưa có job mới hoàn tất.')
continue
for fut in done:
try:
result = fut.result()
except Exception as exc:
for future in pending:
future.cancel()
update(status='Job failed; pending jobs cancelled', error=str(exc),
message='Completed artifacts are preserved. Running workers finish before the scheduler exits.')
raise
results.append(result)
fresh = sum(not r.get('cached') for r in results)
elapsed = time.perf_counter() - started
remain = len(jobs) - len(results)
eta = elapsed/fresh*remain if fresh else None
update(completed=len(results), total=len(jobs), eta_seconds=eta, elapsed_seconds=elapsed,
message=f'{stage}: xong {len(results)}/{len(jobs)} job; cache {len(results)-fresh}. Các job được kiểm tra fingerprint khi chạy lại.')
print(f'{stage} {len(results)}/{len(jobs)} {result["path"]}', flush=True)
return results
def registration_jobs(p: dict, stamp: dict, root: Path, device: str, deployment: bool = False) -> list[dict]:
jobs = []
sets = training_sets(p['data']['wells'], 3 if deployment else 2)
for names in sets:
arms = [(p['registration']['sigma_a_ms'], False)]
if not deployment:
arms += [(s, False) for s in p['registration']['sigma_a_sensitivity_ms']]
if 'M2-no-anchors' in p['methods']['ablations']:
arms += [(p['registration']['sigma_a_ms'], True)]
for sa, no in arms:
settings = dict(names=list(names), sa=sa, no_anchors=no)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage='registration', **settings)))
return jobs
def training_jobs(p: dict, stamp: dict, root: Path, device: str) -> list[dict]:
jobs = []
for names in training_sets(p['data']['wells']):
arms = [(p['registration']['sigma_a_ms'], lab, m) for lab in p['data']['labels'] for m in p['methods']['main']]
arms += [(p['registration']['sigma_a_ms'], lab, m) for lab in p['methods']['ablation_labels'] for m in p['methods']['ablations']]
arms += [(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']]
for (sa, label, method), seed in itertools.product(arms, p['split']['seeds']):
settings = dict(names=list(names), method=method, label=label, seed=seed, sa=sa)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage='train', **settings)))
return jobs
def prepare() -> None:
update(status='Chuẩn bị dữ liệu', message='Dựng patch đúng vị trí giếng và nhãn chống alias; chưa huấn luyện.', tasks={'p3-env': 'doing'})
subprocess.run([sys.executable, str(REPO_ROOT / 'scripts/01_build_wells.py')], cwd=REPO_ROOT, check=True)
import torch
if not torch.cuda.is_available():
raise RuntimeError('CUDA is unavailable; CPU execution must be requested explicitly for tests.')
update(status='Dữ liệu và CUDA sẵn sàng', message=f'{torch.cuda.get_device_name(0)}; đã dựng f3_wells.npz.', tasks={'p3-env': 'done'})
def benchmark_worker(job: dict) -> dict:
from ml_porosity.f3.training import train_trajectory
rng = np.random.default_rng(job['seed'])
X = rng.normal(size=(2, 9, 126))
Y = rng.normal(size=(2, 64, 126))
if job['method'] == 'M2-S256':
Y = rng.normal(size=(2, 256, 126))
if job['method'] == 'B3b':
Y = Y[:, :1]
if job['method'] in ('B4c', 'B4d'):
spec = dict(kind='softdtw' if job['method'] == 'B4c' else 'dilate', Y=Y[:, 0], gamma=0.1, band=8)
if job['method'] == 'B4d':
spec['alpha'] = 0.5
else:
spec = dict(kind='bank', Y=Y, logpi=np.full(Y.shape[:2], -np.log(Y.shape[1])), lam=0.37)
train_trajectory(X, X, spec, job['method'], job['p']['training'], job['seed'], [10], job['device'])
measurement_start = time.time()
_, meta = train_trajectory(X, X, spec, job['method'], job['p']['training'], job['seed'],
[job['steps']], job['device'])
return meta | {'method': job['method'], 'measurement_start': measurement_start, 'measurement_end': time.time()}
def benchmark(p: dict, device: str, steps: int, worker_counts: list[int]) -> dict:
import torch
update(status='Đo tốc độ RTX 3060', message='Dùng dữ liệu giả cùng kích thước; không xem nhãn test F3.', tasks={'p3-bench': 'doing'})
previous_file = outputs_dir()/'p3/benchmark.json'
previous = json.loads(previous_file.read_text(encoding='utf-8')) if previous_file.exists() else {}
same = previous.get('torch') == torch.__version__ and previous.get('device') == device
trials = [t for t in previous.get('trials', []) if same and t.get('jobs')
and all(j['steps'] == steps for j in t['jobs']) and t['workers'] not in worker_counts]
for workers in worker_counts:
start = time.perf_counter()
jobs = [dict(p=p, device=device, steps=steps, method=m, seed=i) for i, m in
enumerate(['B3b', 'M2-Sa', 'B4c', 'B4d', 'B2', 'M2-S256', 'M2-TCN'] * 2)]
try:
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context('spawn')) as pool:
result = list(pool.map(benchmark_worker, jobs))
elapsed = time.perf_counter()-start
steady = max(j['measurement_end'] for j in result)-min(j['measurement_start'] for j in result)
trials.append({'workers': workers, 'wall_seconds': elapsed, 'steady_wall_seconds': steady, 'steps_total': len(jobs)*steps,
'throughput_steps_per_second': len(jobs)*steps/steady, 'jobs': result})
except Exception as exc:
trials.append({'workers': workers, 'error': str(exc)})
valid = [v for v in trials if 'error' not in v]
if not valid:
raise RuntimeError(f'All benchmark configurations failed: {trials}')
best = max(valid, key=lambda v: v['throughput_steps_per_second'])
planned = training_jobs(p, {}, Path('.'), device)
n_jobs = len(planned)
timing = {method: float(np.mean([j['seconds_per_step'] for j in best['jobs'] if j['method'] == method]))
for method in {j['method'] for j in best['jobs']}}
def category(method):
if method.endswith('-TCN'):
return 'M2-TCN'
if method in timing:
return method
if method.startswith('B3'):
return 'B3b'
return 'M2-Sa'
# Individual timings include contention. Calibrate their sum to measured wall time.
scheduling_factor = min(1.0, best['steady_wall_seconds']/sum(j['wall_seconds'] for j in best['jobs']))
nominal = sum(timing[category(j['method'])]*max(p['training']['budgets']) for j in planned)*scheduling_factor
out = {'device': device, 'gpu': torch.cuda.get_device_name(0) if device.startswith('cuda') else 'CPU',
'torch': torch.__version__, 'python': sys.version, 'trials': trials, 'recommended_workers': best['workers'],
'training_jobs': n_jobs, 'max_steps_per_job': max(p['training']['budgets']),
'training_seconds': nominal, 'training_range_seconds': [nominal*0.8, nominal*1.6],
'posterior_seconds': None, 'volume_seconds': None,
'note': 'Measured synthetic-input training benchmark. Registration and full-volume ETA require their own pilot; not included in training_seconds.'}
from ml_porosity.f3.volume import volume_benchmark
out['volume'] = volume_benchmark(p, device)
out['volume_seconds'] = out['volume']['inference_seconds']
write_json(outputs_dir()/'p3/benchmark.json', out)
update(status='Đã đo tốc độ huấn luyện', message=f'{n_jobs} trajectory; ước lượng train {nominal/3600:.1f} giờ, chưa gồm posterior và volume.',
benchmark=out, eta_seconds=None, tasks={'p3-bench': 'doing'})
return out
def benchmark_registration(p: dict, device: str) -> dict:
"""One training-only registration pilot, isolated from the scientific output tree."""
from ml_porosity.f3.protocol import CONFIG, source_hash
root = outputs_dir()/'p3/benchmark_registration'
names = training_sets(p['data']['wells'])[0]
stamp = {'protocol_sha256': digest(CONFIG, True), 'code_sha256': source_hash(), 'benchmark_only': True}
jobs = registration_jobs(p, stamp, root, device)
pilots = [jobs[0]]
no_anchor_jobs = [job for job in jobs if tuple(job['names']) == names and job['no_anchors']]
if no_anchor_jobs:
pilots.append(no_anchor_jobs[0])
update(status='Đo thời gian registration', message=f'Pilot chỉ dùng hai giếng train {names}; không huấn luyện hoặc xem nhãn test P3.')
timings = []
for job in pilots:
result = registration_worker(job)
if result.get('cached'):
result = json.loads(reg_path(root, names, job['sa'], job['no_anchors']).with_suffix('.json').read_text(encoding='utf-8'))
timings.append({'no_anchors': job['no_anchors'], 'seconds': result['wall_seconds']})
seconds = timings[0]['seconds']
# Four 3-well deployment sets cost roughly six 2-well sets; sharing one GPU limits parallel speedup.
pair_equivalents = len(registration_jobs(p, stamp, root, device)) + 6
no_anchor_count = sum(job['no_anchors'] for job in jobs)
anchor_equivalents = len(jobs)-no_anchor_count+6
workload = seconds*anchor_equivalents+timings[-1]['seconds']*no_anchor_count
out = {'training_wells': names, 'seconds_per_two_well_set': seconds, 'pair_equivalents': pair_equivalents,
'pilots': timings, 'range_seconds': [workload/2, workload*2],
'note': 'One real-data training pair measured with and without anchors. Range is an extrapolation, not a confidence interval; other sigma arms and shared-GPU scheduling can differ.'}
write_json(outputs_dir()/'p3/registration_benchmark.json', out)
benchfile = outputs_dir()/'p3/benchmark.json'
values = {'registration_benchmark': out}
if benchfile.exists():
bench = json.loads(benchfile.read_text(encoding='utf-8'))
train_range = bench['training_range_seconds']
vol_range = bench['volume']['range_seconds_with_io']
# Extra deployment training and scoring are allowed 15% of the measured training budget.
values['full_runtime_range_seconds'] = [train_range[i]*1.15+out['range_seconds'][i]+vol_range[i] for i in (0, 1)]
update(status='Đã đo và ước lượng P3', message='Đã có benchmark train, registration và volume. Chưa chạy lưới P3 chính.',
**values, tasks={'p3-bench': 'done'})
return out
def run(stage: str, p: dict, device: str, workers: int, smoke: bool = False) -> None:
stamp = freeze(check=True)
root = outputs_dir()/'p3'
if smoke:
p = copy.deepcopy(p)
p['split']['seeds'] = [0]
p['data']['labels'] = [p['data']['primary_label']]
p['methods']['main'] = ['B3b', 'B3d-Sa', 'M2-Sa']
p['methods']['ablations'] = []
p['registration'].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0, phase_max_extra=0,
sigma_a_sensitivity_ms=[])
p['training']['budgets'] = [2, 4]
root = root/'smoke'
stamp = stamp | {'smoke': p}
if stage == 'register':
run_jobs(registration_jobs(p, stamp, root, device), registration_worker, workers, stage)
elif stage == 'train':
run_jobs(training_jobs(p, stamp, root, device), training_worker, workers, stage)
elif stage in ('diagnostics', 'summarize'):
from ml_porosity.f3.evaluation import diagnostics, summarize
(diagnostics if stage == 'diagnostics' else summarize)(p, root)
else:
raise ValueError(stage)

152
ml_porosity/f3/training.py Normal file
View File

@@ -0,0 +1,152 @@
"""P3 trajectories: checkpoint all registered budgets without looking at target labels."""
from __future__ import annotations
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
from ml_porosity.losses.rml import bank_loss, gather_windows
from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast
from ml_porosity.models.bank_train import window_starts_fixed
from ml_porosity.models.cnn_gru import CNNGRU
from ml_porosity.models.train import CNNGRUHetero, predict
class TCNHetero(nn.Module):
def __init__(self, channels: int, d: int, dropout: float):
super().__init__()
layers = []
for dilation in (1, 2, 4, 8):
layers.extend([nn.Conv1d(channels, d, 5, padding=2*dilation, dilation=dilation), nn.ReLU(), nn.Dropout(dropout)])
channels = d
self.net = nn.Sequential(*layers, nn.Conv1d(d, 2, 1))
def forward(self, x):
out = self.net(x)
return out[:, :1], torch.nn.functional.softplus(out[:, 1:]) + 1e-3
class FixedSigmaHetero(CNNGRUHetero):
def __init__(self, channels: int, d: int, dropout: float, fixed_sigma: float):
super().__init__(channels, d, dropout)
self.fixed_sigma = fixed_sigma
def forward(self, x):
mean, _ = super().forward(x)
return mean, torch.full_like(mean, self.fixed_sigma)
def make_model(method: str, channels: int, cfg: dict):
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
if method == 'M2-fixed-sigma':
return FixedSigmaHetero(channels, cfg['d_channels'], cfg['p_dropout'], cfg.get('fixed_sigma', 1.0))
cls = TCNHetero if method.endswith('-TCN') else CNNGRU if method == 'B2' else CNNGRUHetero
return cls(channels, cfg['d_channels'], cfg['p_dropout'])
def method_spec(bundle: dict, label: str, method: str, p: dict) -> dict:
m0, s0 = bundle[f'{label}/norm']
lam = float(bundle[f'{label}/lambda'])
base = method
if base in ('M2-anchor-only',):
base = 'M1'
elif base.startswith('M2-') and base not in ('M2-S256', 'M2-bulk'):
base = 'M2-Sa'
elif base == 'B3d-Sa-TCN':
base = 'B3d-Sa'
if method in ('B4a', 'B4b'):
Y = bundle[f'{label}/B4']
lp = np.full(Y.shape[:2], -np.log(Y.shape[1]))
return dict(kind='bank', Y=(Y-m0)/s0, logpi=lp, lam=None if method == 'B4a' else lam)
if method in ('B4c', 'B4d'):
return dict(kind='softdtw' if method == 'B4c' else 'dilate', Y=(bundle[f'{label}/B3b'][:, 0]-m0)/s0,
**p['training']['softdtw' if method == 'B4c' else 'dilate'])
Y = bundle[f'{label}/{base}']
if method in ('M2-S1', 'M2-S8'):
Y = Y[:, :int(method[4:])]
lp = bundle.get(f'{label}/{base}/logpi', np.full(Y.shape[:2], -np.log(Y.shape[1])))
if lp.shape != Y.shape[:2]:
lp = np.full(Y.shape[:2], -np.log(Y.shape[1]))
return dict(kind='legacy' if method == 'B2' else 'bank', Y=(Y-m0)/s0, logpi=lp,
lam=1.0 if method == 'M2-lambda1' else lam)
def ensemble(means: np.ndarray, sigmas: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]:
means = np.asarray(means, float)
within = 0.0 if sigmas is None else np.mean(np.asarray(sigmas, float)**2, axis=0)
return means.mean(axis=0), np.sqrt(np.maximum(within + means.var(axis=0), 0))
def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int],
device: str, checkpoint: Path | None = None) -> tuple[dict, dict]:
torch.set_num_threads(2)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.default_generator.manual_seed(seed)
if torch.device(device).type == 'cuda':
torch.cuda.set_device(device)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
tensor = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
x, y = tensor(X), tensor(spec['Y'])
N, _, L = X.shape
starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device)
logpi = tensor(spec.get('logpi', np.zeros(y.shape[:2])))
model = make_model(method, X.shape[1], cfg).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg['lr'])
legacy = LegacyV2Loss()
outputs, states = {}, {}
if torch.device(device).type == 'cuda':
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
begin = time.perf_counter()
for step in range(1, max(budgets)+1):
model.train()
opt.zero_grad(set_to_none=True)
if method == 'B2':
mu = model(x)
if step <= 50:
mu = mu + 0.01 * torch.randn_like(mu)
loss = legacy(mu, y[:, 0, None])
else:
mu, sigma = model(x)
if method == 'M2-fixed-sigma':
sigma = torch.full_like(sigma, cfg.get('fixed_sigma', 1.0))
if spec['kind'] == 'bank':
loss = bank_loss(mu[:, 0], sigma[:, 0], y, logpi, starts, 64, spec['lam'])
else:
f = softdtw_loss_fast if spec['kind'] == 'softdtw' else dilate_loss_fast
kw = {k: spec[k] for k in ('gamma', 'band', 'alpha') if k in spec}
loss = f(gather_windows(mu[:, 0], starts, 64).reshape(-1, 64),
gather_windows(sigma[:, 0], starts, 64).reshape(-1, 64),
gather_windows(y, starts, 64).reshape(-1, 64), **kw)
if method == 'M2-legacy-loss':
loss = loss + legacy(mu, y.mean(axis=1)[:, None])
if not torch.isfinite(loss):
raise FloatingPointError(f'Non-finite loss in {method}, step {step}')
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg['grad_clip'])
opt.step()
if step in budgets:
m, s = predict(model, X_targets, device)
if method == 'M2-fixed-sigma':
s = np.full_like(m, cfg.get('fixed_sigma', 1.0))
outputs[f'{step}/mu'] = m
outputs[f'{step}/sigma'] = np.zeros_like(m) if s is None else s
if checkpoint is not None:
states[step] = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if torch.device(device).type == 'cuda':
torch.cuda.synchronize()
elapsed = time.perf_counter() - begin
if checkpoint is not None:
tmp = checkpoint.with_suffix('.pt.tmp')
torch.save({'states': states, 'method': method, 'channels': X.shape[1], 'config': cfg}, tmp)
tmp.replace(checkpoint)
return outputs, {'wall_seconds': elapsed, 'steps': max(budgets), 'seconds_per_step': elapsed/max(budgets),
'parameters': sum(v.numel() for v in model.parameters()),
'peak_vram_bytes': torch.cuda.max_memory_allocated() if torch.device(device).type == 'cuda' else 0}

237
ml_porosity/f3/volume.py Normal file
View File

@@ -0,0 +1,237 @@
"""Descriptive F3 volume from a frozen 20-member deployment ensemble, streamed by inline."""
from __future__ import annotations
import json
import time
from pathlib import Path
import numpy as np
from ml_porosity.f3.progress import update, write_json
from ml_porosity.f3.protocol import digest, fingerprint, freeze, training_sets
from ml_porosity.f3.runner import job_path, load_bundle, registration_jobs, registration_worker, reusable, run_jobs, training_worker
from ml_porosity.paths import outputs_dir
def deployment_budget(values, candidates) -> int:
median = float(np.median(values))
return min(candidates, key=lambda x: (abs(x-median), x))
def fit_deployment(p: dict, device: str, workers: int) -> dict:
import pandas as pd
root, stamp = outputs_dir()/'p3', freeze(check=True)
selection = pd.read_csv(root/'summary/selection.csv')
cfg = p['volume']
method, label = cfg['method'], cfg['label']
run_jobs(registration_jobs(p, stamp, root, device, deployment=True), registration_worker, workers, 'volume-register')
jobs, members = [], []
for names in training_sets(p['data']['wells'], 3):
for seed in p['split']['seeds']:
scores = selection[(selection.method == method) & (selection.label == label) & (selection.seed == seed)
& (selection.sigma_a_ms == p['registration']['sigma_a_ms'])]
if len(scores) != 4:
raise RuntimeError('Need all four outer selections before deployment fitting')
budget = deployment_budget(scores.budget.to_numpy(), p['training']['budgets'])
import copy
q = copy.deepcopy(p)
q['training']['budgets'] = [budget]
settings = dict(names=list(names), method=method, label=label, seed=seed, sa=p['registration']['sigma_a_ms'])
jobs.append(dict(p=q, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage='deployment-train', budget=budget, **settings)))
path = job_path(root, names, method, label, seed, p['registration']['sigma_a_ms'])
members.append({'checkpoint': str(path.with_suffix('.pt').relative_to(root)), 'prediction': str(path.relative_to(root)),
'budget': budget, 'training_wells': names, 'seed': seed})
run_jobs(jobs, training_worker, workers, 'volume-fit')
meta = {'members': members, 'method': method, 'label': label, 'protocol_sha256': stamp['protocol_sha256'],
'note': '20-member ensemble for descriptive volume only; LOWO scores use separate 15-member blind ensembles.'}
write_json(root/'deployment.json', meta)
return meta
def load_models(p: dict, device: str):
import torch
from ml_porosity.f3.training import make_model
root = outputs_dir()/'p3'
stamp = freeze(check=True)
meta = json.loads((root/'deployment.json').read_text(encoding='utf-8'))
if len(meta['members']) != 4*len(p['split']['seeds']) or meta['protocol_sha256'] != stamp['protocol_sha256']:
raise RuntimeError('Incomplete or mismatched deployment ensemble')
models = []
for item in meta['members']:
key = fingerprint(stamp, stage='deployment-train', budget=item['budget'], names=list(item['training_wells']),
method=meta['method'], label=meta['label'], seed=item['seed'], sa=p['registration']['sigma_a_ms'])
if not reusable(root/item['prediction'], key):
raise RuntimeError('Deployment prediction/checkpoint pair is incomplete')
saved = torch.load(root/item['checkpoint'], map_location='cpu', weights_only=True)
model = make_model(saved['method'], saved['channels'], saved['config'])
model.load_state_dict(saved['states'][item['budget']])
model.to(device).eval()
norm = load_bundle(root/item['prediction'])['norm']
models.append((model, float(norm[0]), float(norm[1])))
return models
def predict_batch(models, patches: np.ndarray, device: str) -> tuple[np.ndarray, np.ndarray]:
import torch
x = torch.as_tensor(patches, dtype=torch.float32, device=device)
running_mean, m2, sum_aleatoric = None, None, None
with torch.inference_mode():
for n, (model, mean, sd) in enumerate(models, 1):
mu, sigma = model(x)
mu, sigma = mu[:, 0]*sd+mean, sigma[:, 0]*sd
if running_mean is None:
running_mean, m2, sum_aleatoric = mu.clone(), torch.zeros_like(mu), sigma**2
else:
delta = mu-running_mean
running_mean = running_mean+delta/n
m2 = m2+delta*(mu-running_mean)
sum_aleatoric = sum_aleatoric+sigma**2
std = torch.sqrt(torch.clamp((sum_aleatoric+m2)/len(models), min=0))
return running_mean.cpu().numpy(), std.cpu().numpy()
def volume_benchmark(p: dict, device: str, batches: int = 4) -> dict:
"""Architecture-only pilot; no production checkpoint or F3 labels are required."""
import torch
from ml_porosity.f3.training import make_model
n = 4*len(p['split']['seeds'])
models = [(make_model(p['volume']['method'], 9, p['training']).to(device).eval(), 0.25, 0.03) for _ in range(n)]
rng = np.random.default_rng(73)
x = rng.normal(size=(p['volume']['batch_size'], 9, 126)).astype(np.float32)
predict_batch(models, x, device)
if device.startswith('cuda'):
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(batches):
predict_batch(models, x, device)
if device.startswith('cuda'):
torch.cuda.synchronize()
elapsed = time.perf_counter()-start
from ml_porosity.data.seismic_io import SeismicCube
with SeismicCube() as cube:
traces = (len(cube.ilines)-2)*(len(cube.xlines)-2)
estimate = traces/(batches*len(x)/elapsed)
del models
if device.startswith('cuda'):
torch.cuda.empty_cache()
return {'members': n, 'batch_size': len(x), 'measured_batches': batches, 'seconds': elapsed,
'traces_per_second': batches*len(x)/elapsed, 'full_interior_traces': traces,
'inference_seconds': estimate, 'range_seconds_with_io': [estimate*1.1, estimate*1.8],
'note': 'Measured with 20 random-weight models of the deployment architecture; range adds SEG-Y reading, normalization and disk writing. Not a production prediction.'}
def predict_volume(p: dict, device: str, sections: bool = False, limit_inlines: int | None = None) -> dict:
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.f3.data import F3Data
stamp = freeze(check=True)
from ml_porosity.paths import f3_segy
if digest(f3_segy()) != stamp['segy_sha256']:
raise RuntimeError('F3 cube changed after protocol locking; refusing volume prediction')
root = outputs_dir()/'p3'
models = load_models(p, device)
data = F3Data(p)
dest = root/('volume_sections' if sections else 'volume_pilot' if limit_inlines else 'volume')
dest.mkdir(parents=True, exist_ok=True)
state_file = dest/'state.json'
key = fingerprint(stamp, stage='volume', deployment=json.loads((root/'deployment.json').read_text(encoding='utf-8')),
sections=sections, limit_inlines=limit_inlines)
state = json.loads(state_file.read_text(encoding='utf-8')) if state_file.exists() else {'fingerprint': key, 'completed_ilines': []}
if state['fingerprint'] != key:
raise RuntimeError('Volume resume fingerprint mismatch')
if state['completed_ilines'] and any(not (dest/n).exists() for n in ('mean.npy', 'sigma.npy')):
raise RuntimeError('Volume state lists completed rows but an output file is missing; refusing to skip missing predictions')
start = time.perf_counter()
with SeismicCube() as cube:
time_mask = cube.window(*p['data']['window_ms'])
times = cube.times_ms[time_mask]
if not np.array_equal(times, data.t_main):
raise ValueError('Cube and training time axes differ')
shape = (len(cube.ilines), len(cube.xlines), len(times))
outputs = []
for name in ('mean.npy', 'sigma.npy'):
path = dest/name
new = not path.exists()
arr = np.lib.format.open_memmap(path, mode='w+' if new else 'r+', dtype='float32', shape=shape)
if new:
arr[:] = np.nan
arr.flush()
elif arr.shape != shape:
raise ValueError('Existing volume shape differs')
outputs.append(arr)
selected_i = {int(data.ext(w, 'il')) for w in data.wells}
selected_j = {int(np.flatnonzero(cube.xlines == int(data.ext(w, 'xl')))[0]) for w in data.wells}
line_cache = {}
def line(i):
if i not in line_cache:
il = int(cube.ilines[i])
a = np.asarray(cube._f.iline[il], dtype=np.float32)[:, time_mask]
line_cache[i] = a
return line_cache[i]
total = len(cube.ilines)-2
if limit_inlines:
total = min(total, limit_inlines)
completed_now = 0
for i in range(1, total+1):
if i in state['completed_ilines']:
continue
il = int(cube.ilines[i])
columns = np.arange(1, len(cube.xlines)-1)
if sections and il not in selected_i:
columns = np.array(sorted(j for j in selected_j if 0 < j < len(cube.xlines)-1))
block = np.stack([line(i-1), line(i), line(i+1)])
view = np.lib.stride_tricks.sliding_window_view(block, 3, axis=1).transpose(1, 0, 3, 2)
for j0 in range(0, len(columns), p['volume']['batch_size']):
cols = columns[j0:j0+p['volume']['batch_size']]
x = np.ascontiguousarray(view[cols-1].reshape(len(cols), 9, len(times)), dtype=np.float64)
x = (x-x.mean(axis=2, keepdims=True))/(x.std(axis=2, keepdims=True)+1e-8)
mu, sigma = predict_batch(models, x, device)
outputs[0][i, cols] = mu
outputs[1][i, cols] = sigma
for arr in outputs:
arr.flush()
state['completed_ilines'].append(i)
write_json(state_file, state)
completed_now += 1
elapsed = time.perf_counter()-start
update(status='Đang suy luận volume', message=f'Đã ghi inline {il}; phần biên không có đủ patch được giữ NaN.',
completed=len(state['completed_ilines']), total=total,
eta_seconds=elapsed/completed_now*(total-len(state['completed_ilines'])), tasks={'p3-vol': 'doing'})
for old in list(line_cache):
if old < i:
del line_cache[old]
meta = {'shape': shape, 'ilines': cube.ilines.tolist(), 'xlines': cube.xlines.tolist(), 'times_ms': times.tolist(),
'members': len(models), 'units': 'porosity fraction', 'sections_only': sections, 'pilot': bool(limit_inlines),
'wall_seconds': time.perf_counter()-start, 'edge_policy': p['volume']['edge'],
'interpretation': p['volume']['interpretation'], 'fingerprint': key}
write_json(dest/'metadata.json', meta)
plot_sections(outputs[0], outputs[1], data, cube.ilines, cube.xlines, times, dest)
update(status='Volume đã hoàn tất' if not limit_inlines else 'Pilot volume đã hoàn tất',
message='Đầu ra sonic-derived porosity và σ; không dùng volume để chấm G-C.', completed=None, total=None,
eta_seconds=None, tasks={'p3-vol': 'todo' if limit_inlines else 'done'})
return meta
def plot_sections(mean, sigma, data, ilines, xlines, times, dest):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
limits = [(float(np.nanmin(mean))*100, float(np.nanmax(mean))*100), (0., float(np.nanmax(sigma))*100)]
for w in data.wells:
i = int(np.flatnonzero(ilines == int(data.ext(w, 'il')))[0])
j = int(np.flatnonzero(xlines == int(data.ext(w, 'xl')))[0])
for name, a, b, axis in (('inline', mean[i], sigma[i], xlines), ('crossline', mean[:, j], sigma[:, j], ilines)):
if not np.isfinite(a).any():
continue
fig, axs = plt.subplots(1, 2, figsize=(12, 5), sharey=True, layout='constrained')
for ax, values, title, clim, cmap_name in zip(axs, (a, b), ('Mean (p.u.)', 'Predictive sigma (p.u.)'), limits, ('viridis', 'magma')):
cmap = matplotlib.colormaps[cmap_name].with_extremes(bad='#bdbdbd')
dt = float(times[1]-times[0])
img = ax.imshow(100*values.T, origin='upper', aspect='auto', interpolation='nearest', cmap=cmap,
vmin=clim[0], vmax=clim[1], extent=[axis[0]-.5, axis[-1]+.5, times[-1]+dt/2, times[0]-dt/2])
ax.set(title=title, xlabel=name)
fig.colorbar(img, ax=ax)
axs[0].set_ylabel('TWT (ms)')
fig.suptitle(f'{w} — descriptive sonic-derived porosity; gray = unavailable')
fig.savefig(dest/f'{w}_{name}.png', dpi=140)
plt.close(fig)