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

@@ -4,6 +4,7 @@
python scripts/00_data_manifest.py --check # check only; exit 1 on mismatch
python scripts/00_data_manifest.py --dataset volve # same for data/Volve
python scripts/00_data_manifest.py --dataset nlog # same for data/NLOG
python scripts/00_data_manifest.py --dataset thesis # same for outputs_thesis
"""
from __future__ import annotations
@@ -22,6 +23,7 @@ DATASETS = {
"f3": (f3_root, "f3_demo_2023.json", "F3 Demo 2023 (dGB Earth Sciences / TerraNubis), CC BY-SA 3.0"),
"volve": (volve_root, "volve.json", "Volve data village (Equinor), HRS licence / CC BY-NC-SA 4.0"),
"nlog": (nlog_root, "nlog.json", "NLOG (TNO), public LAS and TD data for the F3 wells; URLs in docs/research/f3-nlog-inventory.xlsx"),
"thesis": (lambda: REPO_ROOT / "outputs_thesis", "thesis_outputs.json", "Thesis outputs archived in outputs_thesis; source code in code_thesis"),
}
@@ -55,7 +57,7 @@ def main() -> int:
current = scan(root)
if args.check:
ref = json.loads(manifest.read_text())["files"]
ref = json.loads(manifest.read_text(encoding="utf-8"))["files"]
missing = sorted(set(ref) - set(current))
changed = sorted(k for k in set(ref) & set(current) if ref[k]["sha256"] != current[k]["sha256"])
extra = sorted(set(current) - set(ref))
@@ -74,7 +76,7 @@ def main() -> int:
"files": current,
}
manifest.parent.mkdir(parents=True, exist_ok=True)
manifest.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n")
manifest.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"{out['n_files']} file, {out['total_bytes'] / 1e9:.2f} GB -> {manifest.relative_to(REPO_ROOT)}")
return 0

View File

@@ -2,7 +2,7 @@
python scripts/03_train.py --config configs/b2_smoke.yaml [--epochs N] [--seed S]
Differences from `test 2/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well
Differences from `code_thesis/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well
separate from the train wells, no label clipping, no lag estimated from seismic–PHIE correlation,
metrics computed on the true scale. Outputs: outputs/runs/<config name>_s<seed>/.
"""

75
scripts/19_run_f3.py Normal file
View File

@@ -0,0 +1,75 @@
"""P3 on Windows/Linux: prepare -> benchmark -> lock -> register -> train -> diagnostics -> summarize.
Full run: python scripts/19_run_f3.py all --device cuda:0 --workers 4
CPU and reduced smoke results are never presented as the registered P3 experiment.
"""
from __future__ import annotations
import argparse
import os
import traceback
os.environ.setdefault('OMP_NUM_THREADS', '2')
os.environ.setdefault('MKL_NUM_THREADS', '2')
os.environ.setdefault('OPENBLAS_NUM_THREADS', '2')
os.environ.setdefault('NUMBA_NUM_THREADS', '2')
os.environ.setdefault('PYTHONHASHSEED', '0')
os.environ.setdefault('PYTHONUTF8', '1')
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
def main() -> None:
from ml_porosity.f3.progress import update
from ml_porosity.f3.protocol import freeze, load_protocol
from ml_porosity.f3.runner import benchmark, benchmark_registration, prepare, run
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('stage', choices=['status', 'prepare', 'benchmark', 'benchmark-registration', 'lock', 'register', 'train', 'diagnostics', 'summarize', 'all'])
ap.add_argument('--device', default='cuda:0')
ap.add_argument('--workers', type=int, default=4)
ap.add_argument('--smoke', action='store_true')
ap.add_argument('--sections', action='store_true', help='Explicitly reduce volume scope; never selected automatically')
ap.add_argument('--skip-volume', action='store_true', help='Stop after LOWO summary; leaves the volume task incomplete')
ap.add_argument('--benchmark-steps', type=int, default=100)
ap.add_argument('--benchmark-workers', type=int, nargs='+', default=[1, 2, 3])
args = ap.parse_args()
if args.workers < 1:
ap.error('--workers must be positive')
p = load_protocol()
if os.name == 'nt':
import ctypes
# Prevent automatic system sleep only while this process is alive.
ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
try:
if args.stage == 'status':
from ml_porosity.paths import outputs_dir
progress = outputs_dir()/'p3/progress.json'
print(progress.read_text(encoding='utf-8') if progress.exists() else 'P3 has not started.')
elif args.stage == 'prepare':
prepare()
elif args.stage == 'benchmark':
print(benchmark(p, args.device, args.benchmark_steps, args.benchmark_workers))
elif args.stage == 'benchmark-registration':
print(benchmark_registration(p, args.device))
elif args.stage == 'lock':
print(freeze())
update(tasks={'p3-protocol': 'done'}, status='Protocol F3 đã khoá', message='Mã băm protocol, code và dữ liệu được kiểm tra trước mọi giai đoạn P3.')
else:
stages = ['register', 'train', 'diagnostics', 'summarize'] if args.stage == 'all' else [args.stage]
for stage in stages:
run(stage, p, args.device, args.workers, args.smoke)
if args.stage == 'all' and not args.smoke and not args.skip_volume:
from ml_porosity.f3.volume import fit_deployment, predict_volume
fit_deployment(p, args.device, args.workers)
predict_volume(p, args.device, args.sections)
except Exception as exc:
update(status='Có lỗi cần xử lý', error=str(exc), message=f'Giai đoạn {args.stage} chưa hoàn tất; các job đã ghi đủ vẫn có thể resume.')
traceback.print_exc()
raise SystemExit(1)
finally:
if os.name == 'nt':
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,8 @@
"""Summarize the frozen P3 run; use 19_run_f3.py summarize for all options."""
from ml_porosity.f3.protocol import freeze, load_protocol
from ml_porosity.f3.evaluation import summarize
from ml_porosity.paths import outputs_dir
if __name__ == '__main__':
freeze(check=True)
print(summarize(load_protocol(), outputs_dir()/'p3'))

25
scripts/21_predict_f3.py Normal file
View File

@@ -0,0 +1,25 @@
"""Fit deployment models or stream the descriptive full F3 volume after P3 LOWO."""
from __future__ import annotations
import argparse
def main():
from ml_porosity.f3.protocol import load_protocol
from ml_porosity.f3.volume import fit_deployment, predict_volume
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('stage', choices=['fit', 'predict'])
ap.add_argument('--device', default='cuda:0')
ap.add_argument('--workers', type=int, default=3)
ap.add_argument('--sections', action='store_true')
ap.add_argument('--limit-inlines', type=int)
args = ap.parse_args()
p = load_protocol()
if args.stage == 'fit':
print(fit_deployment(p, args.device, args.workers))
else:
print(predict_volume(p, args.device, args.sections, args.limit_inlines))
if __name__ == '__main__':
main()

40
scripts/run_p3.ps1 Normal file
View File

@@ -0,0 +1,40 @@
param(
[ValidateSet('status','prepare','benchmark','benchmark-registration','lock','register','train','diagnostics','summarize','all')]
[string]$Stage = 'all',
[ValidatePattern('^(cuda:[0-9]+|cpu)$')][string]$Device = 'cuda:0',
[ValidateRange(1,8)][int]$Workers = 4,
[switch]$Detach,
[switch]$Smoke,
[switch]$Sections,
[switch]$SkipVolume
)
$ErrorActionPreference = 'Stop'
$p3Workspace = Split-Path -Parent $PSScriptRoot
$p3Python = Join-Path $p3Workspace '.venv/Scripts/python.exe'
$env:OMP_NUM_THREADS = '2'
$env:MKL_NUM_THREADS = '2'
$env:OPENBLAS_NUM_THREADS = '2'
$env:NUMBA_NUM_THREADS = '2'
$env:PYTHONUTF8 = '1'
$env:PYTHONHASHSEED = '0'
$env:CUBLAS_WORKSPACE_CONFIG = ':4096:8'
$p3Arguments = @('-X','utf8','-m','ml_porosity.runlog','-n',"p3_$Stage",'--',
$p3Python,'-X','utf8',(Join-Path $PSScriptRoot '19_run_f3.py'),$Stage,
'--device',$Device,'--workers',"$Workers")
if ($Smoke) { $p3Arguments += '--smoke' }
if ($Sections) { $p3Arguments += '--sections' }
if ($SkipVolume) { $p3Arguments += '--skip-volume' }
if ($Detach) {
$p3LogDirectory = Join-Path $p3Workspace 'logs/runs'
New-Item -ItemType Directory -Path $p3LogDirectory -Force | Out-Null
$p3Stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$p3QuotedArguments = $p3Arguments | ForEach-Object { '"' + $_.Replace('"','\"') + '"' }
$p3Process = Start-Process -FilePath $p3Python -ArgumentList $p3QuotedArguments -WorkingDirectory $p3Workspace `
-WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $p3LogDirectory "${p3Stamp}_p3_stdout.log") `
-RedirectStandardError (Join-Path $p3LogDirectory "${p3Stamp}_p3_stderr.log")
Write-Output "P3 detached: PID $($p3Process.Id). Track report.html and outputs/p3/progress.json."
} else {
Push-Location $p3Workspace
try { & $p3Python @p3Arguments; if ($LASTEXITCODE -ne 0) { throw "P3 exited with code $LASTEXITCODE" } }
finally { Pop-Location }
}