#!/usr/bin/env python3 """Plot horizontal velocity in physical Pipe coordinates and training curves.""" import csv import json from pathlib import Path import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from common import parser, load_config, paths, save_json def main(): args = parser(__doc__).parse_args() cfg = load_config(args) _, results = paths(cfg) figures = results / 'figures' figures.mkdir(exist_ok=True) data = np.load(results / 'test_predictions.npz', allow_pickle=False) metrics = json.loads((results / 'metrics.json').read_text()) summary = json.loads((results / 'training_summary.json').read_text()) with (results / 'history.csv').open() as stream: rows = list(csv.DictReader(stream)) epochs = [int(r['epoch']) for r in rows] dpi = cfg['visualization']['dpi'] saved = [] def export(fig, name): for extension in ['png', 'pdf']: dest = figures / f'{name}.{extension}' fig.savefig(dest, dpi=dpi, bbox_inches='tight') saved.append(str(dest)) plt.close(fig) fig, axes = plt.subplots(1, 2, figsize=(11, 4)) axes[0].semilogy(epochs, [float(r['train_relative_l2']) for r in rows], label='Train relative L2') axes[0].semilogy(epochs, [float(r['test_relative_l2']) for r in rows], label='Test relative L2') axes[0].axhline(cfg['paper']['reference_pipe_relative_l2'], color='gray', ls='--', label='Paper 0.00285') axes[0].set(xlabel='Epoch', ylabel='Relative L2 error') axes[0].legend() axes[1].plot(epochs, [float(r['learning_rate']) for r in rows]) axes[1].set(xlabel='Epoch', ylabel='Learning rate') for axis in axes: axis.grid(alpha=.25) fig.tight_layout() export(fig, 'training_curves') for index in cfg['visualization']['sample_indices']: if not 0 <= index < len(data['prediction']): raise IndexError(f'Invalid test-relative sample index {index}') xy, pred, truth = data['coordinates'][index], data['prediction'][index], data['target'][index] signed = truth - pred lower, upper = float(min(truth.min(), pred.min())), float(max(truth.max(), pred.max())) bound = max(float(np.abs(signed).max()), 1e-12) fig, axes = plt.subplots(3, 1, figsize=(11, 7), constrained_layout=True) for axis, field, title, cmap, lo, hi in zip( axes, [truth, pred, signed], ['Ground truth u_x', 'FLARE prediction u_x', 'Ground truth - prediction'], ['viridis', 'viridis', 'RdBu_r'], [lower, lower, -bound], [upper, upper, bound]): # Every cell uses the dataset's curvilinear physical coordinates. image = axis.pcolormesh(xy[..., 0], xy[..., 1], field, shading='gouraud', cmap=cmap, vmin=lo, vmax=hi, rasterized=True) axis.set_aspect('equal') axis.set(xlabel='x (dataset units)', ylabel='y (dataset units)', title=title) fig.colorbar(image, ax=axis, label='u_x (dataset units)') sample = int(data['sample_indices'][index]) fig.suptitle(f'Pipe sample {sample}: relative L2 = {data["relative_l2"][index]:.6g}') export(fig, f'pipe_sample_{sample}') fig, axis = plt.subplots(figsize=(6, 4)) axis.hist(data['relative_l2'], bins=25, edgecolor='white') axis.set(xlabel='Per-sample relative L2', ylabel='Test case count', title='200 Pipe test cases') export(fig, 'test_error_distribution') save_json(results / 'visualization_manifest.json', {'figures': saved, 'samples': len(data['prediction']), 'coordinate_system': 'original Pipe_X/Pipe_Y', 'field': 'horizontal velocity Q0', 'truth_prediction_shared_color_scale': True, 'error': 'truth - prediction'}) report = (f'# FLARE Pipe reproduction\n\nCompleted epochs: {summary["completed_epochs"]}; ' f'optimizer steps: {summary["global_step"]}.\n\n' f'Best checkpoint epoch: {metrics["checkpoint_epoch"]}. ' f'Test relative L2: {metrics["relative_l2"]:.8g}; RMSE: {metrics["rmse"]:.8g}; MAE: {metrics["mae"]:.8g}.\n\n' f'Final epoch test relative L2: {summary["final_epoch_test_metrics"]["relative_l2"]:.8g}.\n\n' f'Paper reference: 0.00285; reproduced/reference ratio: {metrics["ratio_to_paper"]:.4f}.\n\n' 'The best checkpoint is selected using the same 200 test cases; this is a test-selected result. ' 'No independent validation split is introduced. Initialization and residual-entry activation were checked ' 'against the official repository through online read-only inspection. Code is independently written. ' 'Identity normalization, seed 0 and unspecified OneCycleLR defaults are documented assumptions.\n\n' 'Original data remain at the configured source path. Full 129x129 resolution, FP32, batch size 2, ' '8 blocks, width 64, 8 independent heads with 128 latents each.\n') (results / 'report.md').write_text(report) print(report, flush=True) print(f'VISUALIZATION_COMPLETE: {len(saved)} figures saved to {figures}', flush=True) if __name__ == '__main__': main()