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.

  1. Load the arrays (Example 2-2).
  2. Split by run (Example 3-2).
  3. 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.
  4. 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.
  5. Build a baseline of four POD modes and a Gaussian process (Example 3-5).
  6. 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}")
  1. The mean and standard deviation of each of the 8 inputs, over every point of the training runs only (Equation 4-5); for α\alpha and Λ\Lambda these are the statistics of scale_designs.
  2. The 8 columns of X go to the three inputs of NeuralField: position, normal and design.
  3. A minibatch of 1,024 rows drawn at random from the table of all training points, so it mixes points of many training runs.
  4. scores pools the RMSE over every point of the group’s runs; the relative L2 error and ∣ΔCL∣|\Delta C_L| 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.

Table 4-2. Errors of the neural field and the POD + GP baseline, as the project script prints them: the RMSE pooled over all points of the group’s runs, the relative L2 error and the lift error averaged per run.
modelRMSE (CpC_p)rel. L2∣ΔCL∣|\Delta C_L|
Validation runs
neural field0.0477.19 %0.014
POD + GP0.0020.18 %0.002
Test, inside the box
neural field0.0477.02 %0.009
POD + GP0.0110.93 %0.012
Test, outside the box
neural field0.13718.25 %0.076
POD + GP0.18019.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.

Check yourself

  1. 1In the dataset, lift integrated from Cp and area runs about 0.06 below the stored CL. How should the integrated lift be used?
  2. 2POD + GP’s field error inside the box is far below the neural field’s. What is the right conclusion?
  3. 3The exercise suggests splitting the data at random by point instead of by run. What happens to the validation error, and why?

Exercises

  1. Exercise 4-4. Change one thing at a time in the project script and re-run. Widen the network to 128 or train for 20,000 steps: can it beat the baseline inside the box? Remove the Fourier features (a copy of NeuralField with n_in = 8), and compare the validation RMSE with the largest error at the 1 % of points of each validation run with the largest |cp|, the suction peaks. Keep 2 or 8 POD modes. Weight the RMSE by area. Split the data at random by point instead of by run.

    Answer

    Without the Fourier features the validation RMSE rises from 0.047 to about 0.07, but the largest error at the suction peaks falls from 0.50 to about 0.3 (0.068 and 0.29 with seed 0; 0.07 to 0.08 and 0.23 to 0.35 with other seeds): one number would hide that. With 2 modes the baseline’s validation error is 0.3 %; from 6 modes on it jumps to about 21 %. That is pod_baseline, not POD: it fits one kernel to all the coefficients, the small, noise-like ones drive its length scales to their lower bound, and the GP then predicts the mean field. With one GP per mode, 4 and 8 modes both give 0.05 %. The point split barely moves the validation error, because the fields vary so smoothly with α and Λ that a held-out run is almost as easy as a held-out point. That is a property of this solver: a point split never asks about a new design, and on rougher data it can flatter the model.

Go further