A first surrogate, end to end
One script: real solver runs, a split by design, normalisation, training, testing and a report.
Outcome: Load real solver runs and split them by design; train a neural field in PyTorch with training-set normalisation; report RMSE, relative L2 and lift error inside and outside the training range, against a POD + GP baseline.
Builds on Testing on unseen designs, Compressing fields: POD
This lesson puts the unit together in one script: load solver runs, split them by run, normalise, train a neural field, and test it against a classical baseline. It uses the download and the packages of from runs to arrays and runs in about ten seconds on a recent laptop CPU, with no GPU. The network here is a little larger than the site’s (width 64, 4,000 steps), so its numbers differ.
aircraft-runs.npz (about 1 MB) is the download of Example 2-2.
Example 4-9 has six numbered steps. It imports from aircraft.py, so it runs next to that file: load_runs, split_runs, pod_baseline and scores from Units 2 and 3, and NeuralField from 4.5.
- Load the arrays (Example 2-2).
- Split by run (Example 3-2).
- Build the point-wise table and normalise it with statistics of the training runs only (Equation 4-5), the coordinates included, where Example 4-7 scaled them by 0.25.
- Train the neural field of Example 4-7 with Adam and a cosine schedule, as in Example 4-5, on minibatches of points, and save it with its scaling to
field.pt. - Build a baseline of four POD modes and a Gaussian process (Example 3-5).
- Report the RMSE, the relative L2 error and the error in integrated lift, on the validation runs and on the test runs inside and outside the box (Example 3-3).
Example 4-9. The whole project, from the data to the report, in Python
import numpy as np
import torch
from torch import nn
from aircraft import (NeuralField, load_runs, pod_baseline,
scores, split_runs)
# 1. Data: 56 solver runs x 2,000 surface points.
d = load_runs()
n_runs, n_pts = d["cp"].shape
# 2. Split by run: 36 training, 8 validation, 12 test.
train, val, test, in_box = split_runs(d)
print(len(train), len(val), len(test), "runs")
# 3. Point-wise table and normalisation (training runs only).
D = np.column_stack([d["alpha"], d["sweep"]])
design = np.repeat(D[:, None, :], n_pts, axis=1)
X = np.concatenate([d["xyz"], d["normal"], design], axis=-1)
mu = X[train].reshape(-1, 8).mean(axis=0)1
sd = X[train].reshape(-1, 8).std(axis=0)
# Normals are unit vectors already: leave them as they are.
mu[3:6], sd[3:6] = 0.0, 1.0
X = torch.tensor((X - mu) / sd, dtype=torch.float32)
Y = torch.tensor(d["cp"], dtype=torch.float32)[..., None]
# 4. NeuralField of 4.5, on the 8 columns of X.
def field(model, x):
return model(x[..., :3], x[..., 3:6], x[..., 6:])2
torch.manual_seed(0)
model = NeuralField(width=64)
steps = 4000
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(
opt, T_max=steps, eta_min=1e-4)
Xtr = X[train].reshape(-1, 8)
Ytr = Y[train].reshape(-1, 1)
for step in range(steps):
i = torch.randint(0, len(Xtr), (1024,))3
loss = nn.functional.mse_loss(field(model, Xtr[i]), Ytr[i])
opt.zero_grad()
loss.backward()
opt.step()
sched.step()
# The trained field and its scaling, for later exercises.
torch.save({"model": model.state_dict(), "mu": mu.tolist(),
"sd": sd.tolist()}, "field.pt")
with torch.no_grad():
nf = field(model, X).squeeze(-1).numpy()
# 5. Baseline: four POD modes and a GP (3.5).
pod, _ = pod_baseline(d, train)
# 6. Errors on each group of runs (3.3).
groups = [("validation", val),
("test, inside box", test[in_box[test]]),
("test, outside box", test[~in_box[test]])]
for name, pred in [("neural field", nf), ("POD + GP", pod)]:
print(name)
for label, idx in groups:
s = scores(pred[idx], d, idx)4
print(f" {label:18s} RMSE {s['RMSE']:.3f}"
f" rel. L2 {s['rel_L2']:.2%}"
f" |dCL| {s['dCL']:.3f}")
- The mean and standard deviation of each of the 8 inputs, over every point of the training runs only (Equation 4-5); for and these are the statistics of
scale_designs. - The 8 columns of
Xgo to the three inputs ofNeuralField: position, normal and design. - A minibatch of 1,024 rows drawn at random from the table of all training points, so it mixes points of many training runs.
scorespools the RMSE over every point of the group’s runs; the relative L2 error and are computed per run, then averaged.
load_runs downloads the file the first time; with aircraft-runs.npz next to the script it runs offline. Numbers can differ slightly between machines.
Results
Example 4-9 prints the rows of Table 4-2.
| model | RMSE () | rel. L2 | |
|---|---|---|---|
| Validation runs | |||
| neural field | 0.047 | 7.19 % | 0.014 |
| POD + GP | 0.002 | 0.18 % | 0.002 |
| Test, inside the box | |||
| neural field | 0.047 | 7.02 % | 0.009 |
| POD + GP | 0.011 | 0.93 % | 0.012 |
| Test, outside the box | |||
| neural field | 0.137 | 18.25 % | 0.076 |
| POD + GP | 0.180 | 19.50 % | 0.252 |
The baseline wins on the field where there is data. The POD + GP is about 40 times more accurate on the validation runs, measured by the relative L2 error. This solver’s pressure distributions are almost exactly a mean plus a few fixed shapes (as compressing fields showed), which is the ideal case for POD. Lift on the four test runs inside the box is closer, with the network slightly ahead. On RANS data with separation, the gap may narrow or reverse.
Both fail outside the box. 18 to 20 % relative L2 error, with lift errors about 8 times (network) and 21 times (baseline) larger than inside.
Field and integral errors differ. Outside the box the network’s pressure field is about as far off as the baseline’s, yet its lift error is about 3 times smaller. Both should be reported, as measuring error recommends. The exercises of this lesson change one thing at a time: the width, the Fourier features, the number of POD modes, the split.
The neural field sees each point alone, with its position, its normal and the two design numbers; the models of grids, meshes and point clouds read the geometry itself.