File size: 7,515 Bytes
b144968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""Plot Pipe horizontal velocity and errors on the actual curved mesh."""
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT))


def run(results_dir, indices):
    from common import atomic_json, require_compute_node
    require_compute_node()
    import numpy as np
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    result=Path(results_dir); figures=result/'figures'; figures.mkdir(parents=True,exist_ok=True)
    prediction=np.load(result/'predictions.npy',mmap_mode='r')
    target=np.load(result/'targets.npy',mmap_mode='r')
    coords=np.load(result/'coordinates.npy',mmap_mode='r')
    sample_ids=np.load(result/'sample_indices.npy')
    metrics=json.loads((result/'metrics.json').read_text())
    assert prediction.shape==target.shape and coords.shape==(*target.shape,2)
    with (result/'train_history.csv').open() as f:history=list(csv.DictReader(f))
    epochs=np.array([int(r['epoch']) for r in history])
    assert len(history)==500 and np.array_equal(epochs,np.arange(1,501))
    plt.rcParams.update({'font.size':10,'figure.dpi':120,'savefig.dpi':300})
    fig, axes=plt.subplots(1,2,figsize=(11,3.8),layout='constrained')
    for name,label in [('train_l2','Train'),('test_l2','Test')]:
        axes[0].semilogy(epochs,[float(r[name]) for r in history],label=label)
    axes[0].axhline(0.0030,color='gray',ls='--',label='Paper (3-seed mean)')
    axes[0].set(xlabel='Epoch',ylabel='Mean relative L2');axes[0].legend();axes[0].grid(alpha=.25)
    axes[1].step(epochs,[float(r['lr']) for r in history],where='post')
    axes[1].set(xlabel='Epoch',ylabel='Learning rate',yscale='log');axes[1].grid(alpha=.25)
    fig.savefig(figures/'training_curve.png');fig.savefig(figures/'training_curve.pdf');plt.close(fig)
    saved=[]
    for index in indices:
        if index<0 or index>=len(sample_ids):raise IndexError(f'Test-relative index {index} outside split')
        xy=coords[index]; truth=target[index]; pred=prediction[index]; error=pred-truth
        lo,hi=min(truth.min(),pred.min()),max(truth.max(),pred.max())
        max_error=max(float(np.abs(error).max()),1e-12)
        relative=float(np.linalg.norm(error.ravel().astype(np.float64))/np.linalg.norm(truth.ravel().astype(np.float64)))
        for physical in [True,False]:
            fig,axes=plt.subplots(1,4,figsize=(17,4),layout='constrained')
            fields=[truth,pred,error,np.abs(error)]
            labels=['Reference horizontal velocity','D-SENO prediction','Signed error (prediction - reference)','Absolute error']
            for j,(ax,field,label) in enumerate(zip(axes,fields,labels)):
                kw={'cmap':'viridis','vmin':float(lo),'vmax':float(hi)} if j<2 else ({'cmap':'RdBu_r','vmin':-max_error,'vmax':max_error} if j==2 else {'cmap':'magma','vmin':0.,'vmax':max_error})
                if physical:
                    artist=ax.pcolormesh(xy[...,0],xy[...,1],field,shading='gouraud',rasterized=True,**kw)
                    ax.plot(xy[0,:,0],xy[0,:,1],'k-',lw=.45);ax.plot(xy[-1,:,0],xy[-1,:,1],'k-',lw=.45)
                    ax.plot(xy[:,0,0],xy[:,0,1],'k-',lw=.45);ax.plot(xy[:,-1,0],xy[:,-1,1],'k-',lw=.45)
                    ax.set(xlabel='X (dataset coordinate)',ylabel='Y (dataset coordinate)');ax.set_aspect('equal')
                else:
                    artist=ax.imshow(field.T,origin='lower',**kw)
                    ax.set(xlabel='Grid axis 0',ylabel='Grid axis 1')
                ax.set_title(label,fontsize=10);fig.colorbar(artist,ax=ax,shrink=.8)
            fig.suptitle(f'Pipe sample {sample_ids[index]} | best epoch {metrics["checkpoint_epoch"]} | relative L2 {relative:.6f}')
            stem=f'pipe_{sample_ids[index]}_'+('physical' if physical else 'grid')
            fig.savefig(figures/(stem+'.png'));fig.savefig(figures/(stem+'.pdf'));plt.close(fig)
            saved.append(str(figures/(stem+'.png')))
    with (result/'per_sample_metrics.csv').open() as f:per_sample=list(csv.DictReader(f))
    fig,ax=plt.subplots(figsize=(6,4),layout='constrained')
    ax.hist([float(r['relative_l2']) for r in per_sample],bins=25,edgecolor='white')
    ax.set(xlabel='Test sample relative L2',ylabel='Count',title='Fixed held-out set (200 samples)')
    fig.savefig(figures/'test_error_distribution.png');plt.close(fig)
    report=f'''# D-SENO Pipe reproduction

Completed **500 epochs**, seed {metrics['seed']}. Input: physical X/Y coordinates, target: Q channel 0. Fixed split: [0,1000) train, [1000,1200) test, full 129 x 129 resolution.

Best-checkpoint mean relative L2: **{metrics['mean_relative_l2']:.8f}** at epoch **{metrics['checkpoint_epoch']}**. Final-epoch test relative L2: {float(history[-1]['test_l2']):.8f}. RMSE: {metrics['rmse']:.8f}; MAE: {metrics['mae']:.8f}. Paper reference: 0.0030 averaged over three seeds, not a guaranteed target for one run.

Training uses width96 and 7 DS blocks with dilation [23,17,13,9,7,3,1], relative L2, Adam lr0.001 and weight decay0.0001, StepLR step100 gamma0.5, batch20, FP32 and no early stopping. Each training batch sums sample losses; reported scores average sample-relative L2 errors.

The checkpoint is selected by lowest test metric as requested. These 200 samples are therefore a selection set; this score is not an estimate on a separate unseen final holdout.

Paper precedence: Section5.2 specifies two input coordinates, and the conclusion says no positional encoding. The extra grid channels in the official script are omitted. Normalization (training-only pointwise unbiased std plus1e-5), Adam implementation details and projection96->128->1 fill missing paper details using online read-only official references. No official repository was downloaded or copied. Independent implementation has 1,305,761 parameters; the paper rounds to1.306M.

Hardware: allocated Hygon DCU compute node instead of the paper's NVIDIA A10080GB. Exact device, node, environment, source hashes and SLURM job ID are in run_metadata.json. No training or inference ran on login nodes.

Only horizontal velocity is available to this surrogate; no vector streamlines, pressure, lift, drag, or divergence-free claim is derived. Coordinate and velocity units and Reynolds number are not specified in the supplied protocol and are not invented. Figures use the true curved mesh, matched truth/prediction color ranges and separate error colorbars; computational-grid views are also supplied.

Sources: [paper](https://arxiv.org/pdf/2601.17407), [official missing-detail reference](https://github.com/pj1911/Efficient-Dilated-Squeeze-and-Excitation-Neural-Operator-for-Differential-Equations/blob/main/scripts/d_seno_pipe.py).
'''
    (result/'reproduction_report.md').write_text(report)
    atomic_json(result/'visualization_manifest.json',{'figures':saved,'physical_mesh':True,'dpi':300,
                 'matched_reference_prediction_colors':True,'velocity_units':'not specified','n_test':len(sample_ids)})
    print('VISUALIZATION_COMPLETE '+json.dumps({'results':str(result),'examples':len(indices),'figures':saved}),flush=True)


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--results-dir',type=Path,default=ROOT/'results')
    p.add_argument('--indices',type=int,nargs='+',default=[0,50,100,199],help='Indices relative to the 200-sample test split')
    args=p.parse_args();run(args.results_dir,args.indices)


if __name__=='__main__':main()