Deep Operator Networks: Labs


Learning Objectives¶

After studying this notebook, you should be able to

  • say what an operator is, and explain why a network that takes a whole input function removes the need to retrain for every new case;
  • build a DeepONet from a branch net and a trunk net, and read the prediction as an inner product $\sum_k b_k(u)\,\tau_k(z)$ of learned coefficients with a learned basis;
  • prepare the branch input by sampling the input function at $m$ fixed sensor locations, and explain why the sensors must stay fixed while the trunk coordinate may be anything;
  • train an operator on the governing equation alone, with the residual evaluated at coordinates drawn afresh at every step and no solution data anywhere in the loss;
  • extend a trunk net from one coordinate to two, so that the output becomes a field rather than a curve;
  • add Fourier features to a trunk net when the response is oscillatory, and say what problem they solve;
  • combine measured responses with physics residuals when neither alone is enough, and explain why input functions that carry no measurement can still be used by the residual;
  • judge a trained operator on held-out input functions, and design a test — such as a constant input the network never saw — that separates learning the physics from learning the training family;
  • set up a PI-DeepONet for plane stress with two coupled displacement fields and residual and boundary terms built from torch.autograd, trained with no solved examples at all;
  • combine a handful of CFD solutions with the Navier-Stokes residual to learn the map from viscosity to the velocity and pressure fields, and explain why a trained operator acts as a computational accelerator.

Where we are going. The theory behind everything used here — why an operator is the right object to learn, where the branch–trunk form comes from, and what the universal approximation theorem for operators actually promises — is developed in Deep Neural Operators. This notebook is the practice. Five problems are solved by one architecture: a draining tank, a channel flow, a two-degree-of-freedom oscillator, a stretched thin plate, and the flow around a cylinder. Read them as one recipe applied five times; what changes from lab to lab is what the branch net reads, what the trunk net reads, and how many fields come out.




1. From a Parameter to a Function¶

In the previous notebook a PINN was asked to recover one number. The tank drained, nine water-level readings were available, and the network returned a single drainage constant $C$. Everything the problem did not know was contained in that one scalar.

Now the unknown is a whole function. A pump feeds the tank, and its flow rate $Q_{in}(t)$ changes over time. Every different pump schedule gives a different water level history. A PINN trained on one schedule knows nothing about the next one, so solving a hundred schedules means training a hundred networks.

What we want instead is a single network that takes the schedule itself as input and returns the corresponding solution. That is an operator: a map from a function to a function.


1.1. What Changes from a PINN¶

Level 1 (PINN) Level 2 (DeepONet)
Input a number, $C$ a function, $Q_{in}(t)$
Output one solution $h(t)$ a solution for every input function
A new case costs a full retraining one forward pass

The physics does not change. The tank obeys the same mass balance it did before, and we still teach it to the network as a residual rather than with labelled solutions.


1.2. The DeepONet Architecture¶

A DeepONet splits the job between two networks.

  • The branch net reads the input function. A network cannot read a function, so we sample it at $m$ fixed sensor locations and feed the resulting vector.
  • The trunk net reads the coordinate at which we want the answer: $t$ for the tank, $(y, t)$ for a field.

Their outputs are two vectors of the same length $p$, and the prediction is their inner product:


$$G_\theta(u)(z) \;=\; \sum_{k=1}^{p} b_k(u)\, \tau_k(z)$$


$b_k$ comes from the branch net and $\tau_k$ from the trunk net. There is no bias term on the product. The trunk net therefore learns a basis over the coordinate, and the branch net learns the coefficients that pick out one member of the solution family.

Physics-informed means the training signal is the governing equation evaluated on the output, not a set of precomputed solutions. No solver is run to produce labels.


1.3. Notation¶

Symbol Meaning Python Shape
$u$ input function sampled at the sensors U $(N_b, m)$
$m$ number of sensors m scalar
$p$ width of the branch and trunk output p scalar
$Q_{in}(t)$ inflow rate into the tank Q_train $(N, m)$
$h(t)$ water level h $(N_b, 1)$
$C$ drainage constant of the tank — scalar, 1
$G(t)$ pressure gradient driving the channel G_train $(N, m)$
$u(y,t)$ streamwise velocity — $(N_b, 1)$
$y$ coordinate across the gap y $(N_b, 1)$

$u$ denotes the input function of the DeepONet in Lab 1 and the velocity field in Lab 2. The number of sensors $m$ and the width $p$ are fixed within a lab but change between labs: $m = 20$ and $p = 100$ in Labs 1 and 2, $m = 100$ and $p = 32$ in Lab 3, $m = 250$ and $p = 100$ in Lab 4, and a single sensor with $p = 100$ in Lab 5.


1.4. The Five Labs¶

Problem Branch input Trunk input Output
Lab 1 tank with a time-varying inflow $Q_{in}(t)$ $t$ $h(t)$
Lab 2 unsteady flow between parallel plates $G(t)$ $(y, t)$ $u(y,t)$
Lab 3 2-DOF forced vibration $F(t)$ $t$ $x_1(t),\,x_2(t)$
Lab 4 thin plate under an edge traction $P(y)$ $(x, y)$ $u(x,y),\,v(x,y)$
Lab 5 flow around a cylinder $\mu$ $(x, y)$ $u, v, p$

Lab 1 keeps the physics of the previous notebook and changes only what the input is, so that the operator idea arrives on familiar ground. Lab 2 adds a space coordinate, and the output becomes a field. The same two nets serve both; only the trunk input width changes from 1 to 2.

Lab 3 keeps a single coordinate but predicts two coupled outputs, and it is the first hybrid objective of the notebook: measured responses supply a data term, and the equations of motion and the initial conditions are added on top of them. Its physics terms are evaluated on three hundred further forces that were never solved, which is the practical reason for mixing the two kinds of supervision.

Labs 4 and 5 are the two largest runs of the notebook, and both come with pretrained models. Lab 4 is the physics-informed DeepONet in its purest form: a thin plate under a family of edge tractions, two coupled displacement fields, and nothing but the plane-stress equations and the boundary conditions in the loss. Lab 5 is the laboratory closest to industrial practice: the flow around a cylinder at varying viscosity, where nine CFD solutions and the Navier-Stokes residual together train an operator that answers a new Reynolds number in a single forward pass.




2. Lab 1: Tank with a Time-Varying Inflow¶


2.1. Problem Setup¶

A tank drains through a small orifice while a pump feeds it at a rate that changes over time. Mass conservation gives


$$A\frac{dh}{dt} = Q_{in}(t) - C\sqrt{h}, \qquad h(0) = h_0$$


  • Problem properties (nondimensionalized)

$$A = 1, \qquad C = 1, \qquad h_0 = 1, \qquad t \in [0, 2]$$


The outflow term $C\sqrt{h}$ is Torricelli's law and it is what makes the equation nonlinear, so the residual is not trivially satisfied.

  • Operator to be learned

$$Q_{in}(t) \;\longmapsto\; h(t)$$


  • Loss

$$\mathcal{L} = \mathcal{L}_{ODE} + \mathcal{L}_{IC}$$


No solution data enters the loss. A reference solution is computed for the test inputs only, and only to measure how well the operator did.


2.2. Solve the Operator Problem¶


Import Libraries

In [ ]:
import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML

CUDA

In [ ]:
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(device)
cuda:0

Generate Data

The input functions are random pump schedules: a smooth Gaussian random field with mean 0.67 and length scale 0.5, sampled at the $m = 20$ sensor times and kept above 0.1 so that the pump never stops. The seed is fixed, so every run of the notebook sees the same family. Each row of Q_train is one pump schedule — that vector, and nothing else, is what the branch net ever sees of the function.

No solution is computed for the 100 training inputs. Only the ten test inputs are solved, and only to grade the operator after training. Between sensors the inflow is interpolated linearly, and the reference solution uses the same interpolation as the training residual, so the two are grading the same problem.

In [ ]:
T, m = 2.0, 20                                    # time horizon, number of sensors
t_sensor = np.linspace(0, T, m)                   # the fixed sensor times
t_ref = np.linspace(0, T, 401)                    # the times at which the reference is evaluated

rng = np.random.default_rng(2)

def random_inflows(n, length = 0.5):              # smooth random pump schedules at the sensor times, (n, m)
    d = t_sensor[:, None] - t_sensor[None, :]
    L = np.linalg.cholesky(np.exp(-d**2/(2*length**2)) + 1e-6*np.eye(m))   # squared-exponential covariance
    z = rng.standard_normal((n, m)) @ L.T
    return np.clip(0.67 + 0.22*z, 0.1, None)      # mean inflow 0.67, never below 0.1

def solve_tank(Q):                                # reference h(t) for one inflow, Q_in interpolated as in sample_at
    sol = solve_ivp(lambda t, h: np.interp(t, t_sensor, Q) - np.sqrt(h), [0, T], [1.0],
                    t_eval = t_ref, rtol = 1e-8, atol = 1e-10, max_step = T/(m - 1))
    return sol.y[0]

Q_train = random_inflows(100)                     # inputs only: no solution is computed for these
Q_test = random_inflows(10)
h_test = np.array([solve_tank(Q) for Q in Q_test])

print('Q_train :', Q_train.shape)
print('Q_test  :', Q_test.shape)
print('h_test  :', h_test.shape)
Q_train : (100, 20)
Q_test  : (10, 20)
h_test  : (10, 401)
In [ ]:
plt.figure(figsize = (6, 4))
plt.plot(t_sensor, Q_train[:10].T, 'k', alpha = 0.3)
plt.xlabel('t')
plt.ylabel('Inflow rate, Q_in')
plt.title('Ten of the 100 Training Inflow Functions')
plt.grid(True)
plt.show()
No description has been provided for this image

Data Batch Generator

Two things are being sampled at once, and it is worth separating them. The input functions are drawn from the generated family, and the collocation times are drawn fresh from $U(0, T)$ at every step. A DeepONet therefore needs a batch in two dimensions: which function, and where on it.

In [ ]:
U = torch.tensor(Q_train, dtype = torch.float32).to(device)                  # (100, 20): the branch input
U_test = torch.tensor(Q_test, dtype = torch.float32).to(device)              # (10, 20)
t_s = torch.tensor(t_sensor, dtype = torch.float32).to(device)               # (20,): the sensor times

def sample_at(u, t):                              # u(t) by linear interpolation between the sensor values, (pairs, 1)
    i = torch.clamp(torch.searchsorted(t_s, t[:, 0].detach().contiguous()) - 1, 0, m - 2)   # the sensor interval of each t
    w = ((t[:, 0] - t_s[i])/(t_s[i + 1] - t_s[i])).reshape(-1, 1)
    row = torch.arange(len(u), device = device)
    return (1 - w)*u[row, i].reshape(-1, 1) + w*u[row, i + 1].reshape(-1, 1)

def get_batch(batch_size = 64):
    i = torch.randint(0, len(U), (batch_size,))                              # which inflow
    t = T*torch.rand(batch_size, 1, device = device, requires_grad = True)   # which time
    return U[i], t

Define Network and Hyper-parameters

The branch net reads the 20 sensor values and the trunk net reads $t$; both are seven layers of width 100 and both end at the same width $p = 100$, which is what makes the inner product $\sum_k b_k \tau_k$ possible. There is no bias on the product: whatever the prediction cannot be written as a combination of trunk basis functions, it cannot represent at all.

In [ ]:
def new_net(n_in, n_out):
    return nn.Sequential(nn.Linear(n_in, 100), nn.Tanh(),
                         nn.Linear(100, 100), nn.Tanh(),
                         nn.Linear(100, 100), nn.Tanh(),
                         nn.Linear(100, 100), nn.Tanh(),
                         nn.Linear(100, 100), nn.Tanh(),
                         nn.Linear(100, 100), nn.Tanh(),
                         nn.Linear(100, n_out)).to(device)

p = 100                                           # number of basis functions

torch.manual_seed(0)
branch = new_net(m, p)                            # 20 sensor values -> p coefficients
trunk = new_net(1, p)                             # t -> p basis values

def deeponet(u, y):
    return torch.sum(branch(u)*trunk(y), dim = 1, keepdim = True)

print('number of parameters :', sum(w.numel() for w in branch.parameters()) + sum(w.numel() for w in trunk.parameters()))
number of parameters : 123500

Define Functions to Compute Physics Loss

The initial-condition term is written as $h(0) - h_0$ so that every loss term is measured against zero.

Note where the derivative is taken. The quantity differentiated with respect to the trunk input is the output of the whole DeepONet, so what the residual constrains is the operator's prediction rather than one solution curve. It is the same differentiation used in the PINN labs, applied to a larger object.

In [ ]:
def derivative(f, x):
    return torch.autograd.grad(f, x, torch.ones_like(f), create_graph = True)[0]

def ode_loss():
    u, t = get_batch()
    h = deeponet(u, t)
    r = derivative(h, t) - sample_at(u, t) + torch.sqrt(torch.clamp(h, min = 0) + 1e-8)   # dh/dt = Q_in - sqrt(h)
    return torch.mean(r**2)

def ic_loss():
    u, t = get_batch()
    return torch.mean((deeponet(u, torch.zeros_like(t)) - 1)**2)             # h(0) = 1

Train

(This process may require a significant amount of time; therefore, we recommend not running it. However, we have provided a pretrained model for your convenience.)

Read the loop once even if you do not run it: nothing in it refers to a solution. A batch of pump schedules and a batch of times go in, the residual of the mass balance and the initial-condition error come out, and their sum is minimized. The network is being taught the equation for a whole family of inputs at once.

In [ ]:
optimizer = torch.optim.Adam(list(branch.parameters()) + list(trunk.parameters()), lr = 5e-4)
n_iter = 20000
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma = 0.02**(1/n_iter))   # 5e-4 -> 1e-5 over the run

# for epoch in range(1, n_iter + 1):
#     loss_ode = ode_loss()
#     loss_ic = ic_loss()
#     loss = loss_ode + loss_ic

#     optimizer.zero_grad()
#     loss.backward()
#     optimizer.step()
#     scheduler.step()

#     if epoch % 2000 == 0:
#         print('epoch %6d | loss %.4e | ode %.4e | ic %.4e' % (epoch, loss.item(), loss_ode.item(), loss_ic.item()))
epoch   2000 | loss 8.6833e-04 | ode 8.0558e-04 | ic 6.2745e-05
epoch   4000 | loss 5.3855e-04 | ode 5.2637e-04 | ic 1.2177e-05
epoch   6000 | loss 6.1605e-04 | ode 5.9719e-04 | ic 1.8857e-05
epoch   8000 | loss 4.7444e-04 | ode 4.6654e-04 | ic 7.8939e-06
epoch  10000 | loss 1.9369e-04 | ode 1.9290e-04 | ic 7.9349e-07
epoch  12000 | loss 1.8177e-04 | ode 1.7896e-04 | ic 2.8067e-06
epoch  14000 | loss 1.1071e-04 | ode 1.0947e-04 | ic 1.2400e-06
epoch  16000 | loss 9.8088e-05 | ode 9.7138e-05 | ic 9.5054e-07
epoch  18000 | loss 9.8362e-05 | ode 9.8091e-05 | ic 2.7104e-07
epoch  20000 | loss 1.0616e-04 | ode 1.0560e-04 | ic 5.6362e-07
In [ ]:
# torch.save([branch, trunk], 'tank_deeponet_model.pt')
In [ ]:
!gdown 1dFr__e1yKq7o8aZ-CYvkknF_M3iZQ5Wb -O /content/tank_deeponet_model.pt
Downloading...
From: https://drive.google.com/uc?id=1dFr__e1yKq7o8aZ-CYvkknF_M3iZQ5Wb
To: /content/tank_deeponet_model.pt

  0% 0.00/510k [00:00<?, ?B/s]
100% 510k/510k [00:00<00:00, 126MB/s]
In [ ]:
branch, trunk = torch.load('/content/tank_deeponet_model.pt', map_location = device, weights_only = False)

Result

The ten test functions below were drawn from the same family but never shown to the network during training.

"Never shown" is the point of the test. For a PINN, a new pump schedule would mean a new training run; here it is one forward pass through a network whose weights are already fixed.

In [ ]:
y_ref = torch.tensor(t_ref.reshape(-1, 1), dtype = torch.float32).to(device)   # the reference times

with torch.no_grad():
    h_pred = (branch(U_test) @ trunk(y_ref).T).cpu().numpy()                # (10, times): every test inflow at every time

rel = np.linalg.norm(h_pred - h_test, axis = 1)/np.linalg.norm(h_test, axis = 1)
print('mean relative L2 error over 10 unseen inflows : %.4f' % rel.mean())
mean relative L2 error over 10 unseen inflows : 0.0049
In [ ]:
plt.figure(figsize = (9, 3))
for j in range(3):
    plt.subplot(1, 3, j + 1)
    plt.plot(t_ref, h_test[j], 'k', alpha = 0.3, linewidth = 4, label = 'Reference')
    plt.plot(t_ref, h_pred[j], 'r--', label = 'DeepONet')
    plt.ylim([0, 1.2])
    plt.title('Unseen inflow %d' % (j + 1))
    plt.xlabel('t')
    if j == 0:
        plt.ylabel('Water level, h')
        plt.legend()
plt.tight_layout()
plt.show()
No description has been provided for this image

One network answered three different pump schedules without being retrained, and it was never shown a single solution while learning. What it was shown is the equation.


Another of the test schedules in motion. The marker on the left rides along $Q_{in}(t)$ and the level on the right is drawn up to that instant, with the whole reference faint behind it. Every turning point of $h$ is an instant where inflow and outflow balance. The dashed curve is produced from the left panel alone, in one forward pass, for a schedule the network never saw.

In [ ]:
frames = range(0, len(t_ref), 8)

fig, (ax_q, ax_h) = plt.subplots(1, 2, figsize = (9, 3))

j = 3
ax_q.plot(t_sensor, Q_test[j], 'b')
mark, = ax_q.plot([], [], 'bo')
ax_q.set_xlim([0, T])
ax_q.set_xlabel('t')
ax_q.set_ylabel('Inflow, Q_in')
ax_q.set_title('Input, Q_in(t)')

ax_h.plot(t_ref, h_test[j], c = '0.85', linewidth = 0.8)
line_ref, = ax_h.plot([], [], 'k', alpha = 0.3, linewidth = 4, label = 'Reference')
line_pred, = ax_h.plot([], [], 'r--', label = 'DeepONet')
clock = ax_h.text(0.04, 0.90, '', transform = ax_h.transAxes)
ax_h.set_xlim([0, T])
ax_h.set_ylim([0, 1.2])
ax_h.set_xlabel('t')
ax_h.set_ylabel('Water level, h')
ax_h.set_title('Water level, h(t)')
ax_h.legend(loc = 'lower left')
plt.tight_layout()
plt.close()

def update(k):
    mark.set_data([t_ref[k]], [np.interp(t_ref[k], t_sensor, Q_test[j])])
    line_ref.set_data(t_ref[:k + 1], h_test[j, :k + 1])
    line_pred.set_data(t_ref[:k + 1], h_pred[j, :k + 1])
    clock.set_text('t = %.2f' % t_ref[k])

anim = FuncAnimation(fig, update, frames = frames)
HTML(anim.to_jshtml(fps = 12))
Out[ ]:
No description has been provided for this image

2.3. What This Lab Showed¶

One network answered ten pump schedules it had never seen, with a mean relative $L^2$ error of about half a percent, and it was never shown a single solution while learning. What it was shown is the mass balance and the initial condition, evaluated at times drawn afresh at every step.


Three things carried over from the PINN labs unchanged: the residual, the way the derivative of the prediction is taken, and the habit of writing every loss term as a deviation from zero. What changed is the input. A PINN takes a coordinate and returns a number; this network takes a function, sampled at twenty fixed times, and returns the solution that function produces. The cost of a new case fell from a training run to a forward pass, and that is the whole of what the operator formulation buys.


Two limits are worth carrying forward. The sensor vector is the entire extent of what the branch net knows about its input, so a schedule that varies faster than twenty samples can resolve cannot be read correctly however well the network is trained. And the ten test schedules were drawn from the same family as the hundred training ones, which makes this an interpolation test; nothing here says what the operator would do with an input of a different character.




3. Lab 2: Unsteady Flow Between Parallel Plates¶


3.1. Problem Setup¶

Two stationary parallel plates a distance apart, with fluid between them driven along by a pressure gradient that varies in time. The flow is fully developed, so it depends on the cross-stream coordinate $y$ and on time, and the convective term is exactly zero. Starting from rest,


$$\frac{\partial u}{\partial t} = G(t) + \frac{\partial^2 u}{\partial y^2}, \qquad y \in [0, 1], \quad t \in [0, 1]$$


$$u(0, t) = u(1, t) = 0 \quad \text{(no-slip)}, \qquad u(y, 0) = 0 \quad \text{(starts from rest)}$$

  • $u$ is the streamwise velocity, $y$ runs across the gap, and $G(t) = -\frac{1}{\rho}\frac{\partial p}{\partial x}(t)$ is the driving pressure gradient. Constants are set to 1.

  • Operator to be learned

$$G(t) \;\longmapsto\; u(y, t)$$


  • Loss

$$\mathcal{L} = \mathcal{L}_{PDE} + \mathcal{L}_{BC} + \mathcal{L}_{IC}$$


Two things are new relative to Lab 1. The trunk net now reads two coordinates instead of one, so the output is a field rather than a curve. And $G(t)$ carries no sign constraint - a pulsating pressure gradient genuinely reverses, and the flow reverses with it.

If $G$ is held constant the solution settles to the fully developed parabola $u = \frac{G}{2}y(1-y)$, which is the profile the PINN lecture already draws. That limit is used as a check at the end.


3.2. Solve the Operator Problem¶


Generate Data

The pressure gradients are drawn much as the pump schedules of Lab 1 were: a smooth Gaussian random field at the 20 sensor times, each function scaled so that its peak $|G|$ is 1. One thing differs, and it matters for the physics: no sign filter is applied, so most of the gradients reverse at least once and the flow reverses with them.

As in Lab 1, only the ten test inputs are solved. Expanding $u$ in $\sin(n\pi y)$, which already satisfies both walls, turns the PDE into one decoupled ODE per mode,


$$\frac{db_n}{dt} = -(n\pi)^2\, b_n + \frac{4}{n\pi}\,G(t), \qquad n = 1, 3, 5, \dots$$


and the even modes stay at zero because a uniform push has no even component. The reference is therefore exact up to the truncation of the series, and it is computed for the test inputs only.

In [ ]:
T, m = 1.0, 20                                    # time horizon, number of sensors
t_sensor = np.linspace(0, T, m)                   # the fixed sensor times
t_eval = np.linspace(0, T, 115)                   # the grid on which the reference is evaluated
y_eval = np.linspace(0, 1, 51)

rng = np.random.default_rng(5)

def random_gradients(n, length = 0.25):          # pressure gradients at the sensor times, (n, m)
    d = t_sensor[:, None] - t_sensor[None, :]
    w, V = np.linalg.eigh(np.exp(-d**2/(2*length**2)))      # squared-exponential covariance
    modes = V[:, -5:]*np.sqrt(w[-5:])                        # its five leading Karhunen-Loeve modes
    G = rng.standard_normal((n, 5)) @ modes.T
    return G/np.abs(G).max(axis = 1, keepdims = True)        # peak |G| = 1, either sign

n_mode = np.arange(1, 200, 2)                     # odd sine modes; the even ones receive no forcing
lam, c = (n_mode*np.pi)**2, 4/(n_mode*np.pi)      # decay rate and forcing weight of each mode

def solve_channel(G):                             # reference u(y, t) for one gradient, as a sine series in y
    sol = solve_ivp(lambda t, b: c*np.interp(t, t_sensor, G) - lam*b, [0, T], np.zeros(len(n_mode)),
                    t_eval = t_eval, method = 'BDF', jac = np.diag(-lam), rtol = 1e-8, atol = 1e-10)
    return sol.y.T @ np.sin(np.pi*np.outer(n_mode, y_eval))         # (times, positions)

G_train = random_gradients(100)                   # inputs only: no solution is computed for these
G_test = random_gradients(10)
u_test = np.array([solve_channel(G) for G in G_test])

print('G_train :', G_train.shape)
print('G_test  :', G_test.shape)
print('u_test  :', u_test.shape)
G_train : (100, 20)
G_test  : (10, 20)
u_test  : (10, 115, 51)
In [ ]:
plt.figure(figsize = (6, 4))
plt.plot(t_sensor, G_train[:10].T, 'k', alpha = 0.3)
plt.axhline(0, c = 'b', linewidth = 0.8, label = 'G = 0, flow reverses below')
plt.legend()
plt.xlabel('t')
plt.ylabel('Pressure gradient, G')
plt.title('Ten of the 100 Training Pressure Gradients')
plt.grid(True)
plt.show()
No description has been provided for this image

Data Batch Generator

Each term of the loss samples where its own condition lives: the residual at interior points, the no-slip condition on the two walls, and the initial condition at $t = 0$. The pressure gradient is interpolated from its 20 sensor values at whatever interior time is drawn, so the input function is read at the same resolution the reference solution used.

In [ ]:
U = torch.tensor(G_train, dtype = torch.float32).to(device)                  # (100, 20)
U_test = torch.tensor(G_test, dtype = torch.float32).to(device)              # (10, 20)
t_s = torch.tensor(t_sensor, dtype = torch.float32).to(device)

def get_batch(batch_size = 64):
    i = torch.randint(0, len(U), (batch_size,))                              # which pressure gradient
    y = torch.rand(batch_size, 1, device = device)                           # which position
    t = T*torch.rand(batch_size, 1, device = device)                         # which time
    return U[i], torch.cat([y, t], dim = 1).requires_grad_(True)

Define Network and Hyper-parameters

The same two nets as Lab 1, with one number changed: the trunk input width goes from 1 to 2. Everything that makes this a field rather than a curve is contained in that number. The trunk net now receives $(y, t)$ and therefore learns basis functions over the plane; the branch net and the inner product are untouched.

In [ ]:
torch.manual_seed(0)
branch = new_net(m, p)                            # 20 sensor values -> p coefficients
trunk = new_net(2, p)                             # (y, t) -> p basis values

Define Functions to Compute Physics Loss

The residual needs a second derivative in $y$ and a first derivative in $t$, and both come from the same automatic differentiation used for the ordinary derivative of Lab 1 — applied twice for the second derivative, exactly as the beam's higher derivatives were built in the PINN labs. Moving from a curve to a field adds no new machinery to the loss.

In [ ]:
def pde_loss():
    u, yt = get_batch()
    v = deeponet(u, yt)
    v_y, v_t = derivative(v, yt).split(1, dim = 1)
    v_yy, _ = derivative(v_y, yt).split(1, dim = 1)
    r = v_t - sample_at(u, yt[:, 1:2]) - v_yy                                # u_t = G(t) + u_yy
    return torch.mean(r**2)

def bc_loss():
    u, yt = get_batch()
    t = yt[:, 1:2]
    bottom = deeponet(u, torch.cat([torch.zeros_like(t), t], dim = 1))      # u = 0 on y = 0
    top = deeponet(u, torch.cat([torch.ones_like(t), t], dim = 1))          # u = 0 on y = 1
    return torch.mean(bottom**2) + torch.mean(top**2)

def ic_loss():
    u, yt = get_batch()
    y = yt[:, 0:1]
    return torch.mean(deeponet(u, torch.cat([y, torch.zeros_like(y)], dim = 1))**2)   # u = 0 at t = 0

Train

Same optimizer and same schedule as Lab 1.

(Again, this process may require a significant amount of time; therefore, we recommend not running it. However, we have provided a pretrained model for your convenience.)

In [ ]:
optimizer = torch.optim.Adam(list(branch.parameters()) + list(trunk.parameters()), lr = 5e-4)
n_iter = 100000
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma = 0.02**(1/n_iter))

for epoch in range(1, n_iter + 1):
    loss_pde = pde_loss()
    loss_bc = bc_loss()
    loss_ic = ic_loss()
    loss = loss_pde + loss_bc + loss_ic

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    scheduler.step()

    if epoch % 10000 == 0:
        print('epoch %6d | loss %.4e | pde %.4e | bc %.4e | ic %.4e' % (epoch, loss.item(), loss_pde.item(), loss_bc.item(), loss_ic.item()))
epoch  10000 | loss 1.6014e-03 | pde 7.1469e-04 | bc 6.5517e-04 | ic 2.3158e-04
epoch  20000 | loss 4.1023e-04 | pde 2.4065e-04 | bc 1.1031e-04 | ic 5.9273e-05
epoch  30000 | loss 3.6097e-04 | pde 2.8123e-04 | bc 6.7547e-05 | ic 1.2188e-05
epoch  40000 | loss 2.0953e-04 | pde 1.6788e-04 | bc 2.5040e-05 | ic 1.6604e-05
epoch  50000 | loss 8.8105e-05 | pde 4.8052e-05 | bc 3.3356e-05 | ic 6.6965e-06
epoch  60000 | loss 6.7160e-05 | pde 3.3569e-05 | bc 2.6761e-05 | ic 6.8303e-06
epoch  70000 | loss 5.7352e-05 | pde 4.0397e-05 | bc 1.1496e-05 | ic 5.4588e-06
epoch  80000 | loss 4.2569e-05 | pde 3.2258e-05 | bc 7.6559e-06 | ic 2.6555e-06
epoch  90000 | loss 3.1713e-05 | pde 2.5552e-05 | bc 4.9543e-06 | ic 1.2072e-06
epoch 100000 | loss 1.7507e-05 | pde 1.2440e-05 | bc 3.6666e-06 | ic 1.4005e-06

Save and Load

Since running the training process takes a long time, we are providing the pre-trained networks, allowing you to use them for evaluating unseen data directly.

As in Lab 1, everything below this point is evaluation.

In [ ]:
# torch.save([branch, trunk], 'unsteadyflow_deeponet_model.pt')
In [ ]:
!gdown 1ibMy5tP4NHLxISo3ww9iNX9JLMJO7jV4 -O /content/unsteadyflow_deeponet_model.pt
Downloading...
From: https://drive.google.com/uc?id=1ibMy5tP4NHLxISo3ww9iNX9JLMJO7jV4
To: /content/unsteadyflow_deeponet_model.pt

  0% 0.00/510k [00:00<?, ?B/s]
100% 510k/510k [00:00<00:00, 123MB/s]
In [ ]:
branch, trunk = torch.load('/content/unsteadyflow_deeponet_model.pt', map_location = device, weights_only = False)

Result

The left panel is the input the two fields answer - one pressure gradient the network never saw. Read it together with them: all three share $t$ as the horizontal axis, so a vertical slice of a field is the velocity across the gap at the instant marked on the left. Where $G$ crosses zero the push reverses, and the field follows with a delay.

In [ ]:
yy, tt = np.meshgrid(y_eval, t_eval)
pts = torch.tensor(np.column_stack([yy.ravel(), tt.ravel()]), dtype = torch.float32).to(device)   # every (y, t) of the evaluation grid

with torch.no_grad():
    u_pred = (branch(U_test) @ trunk(pts).T).cpu().numpy().reshape(-1, len(t_eval), len(y_eval))   # (10, times, positions)

rel = np.linalg.norm(u_pred - u_test, axis = (1, 2))/np.linalg.norm(u_test, axis = (1, 2))
print('mean relative L2 error over 10 unseen pressure gradients : %.4f' % rel.mean())
mean relative L2 error over 10 unseen pressure gradients : 0.0229
In [ ]:
span = np.abs(u_test[0]).max()
titles = ['Reference u(y, t)', 'DeepONet u(y, t)']
fields = [u_test[0], u_pred[0]]

plt.figure(figsize = (13, 3))

plt.subplot(1, 3, 1)
plt.plot(t_sensor, G_test[0], 'k', label = 'Input, G(t)')
plt.axhline(0, c = 'b', linewidth = 0.8, label = 'G = 0, flow reverses below')
plt.xlim([0, 1])
plt.legend()
plt.title('The Input This Field Answers')
plt.xlabel('t')
plt.ylabel('Pressure gradient, G')

for j in range(2):
    plt.subplot(1, 3, j + 2)
    plt.imshow(fields[j].T, cmap = 'rainbow', origin = 'lower', aspect = 'auto', extent = [0, 1, 0, 1], vmin = -span, vmax = span)
    plt.colorbar(label = 'Velocity, u')
    plt.title(titles[j])
    plt.xlabel('t')
    plt.ylabel('y')
plt.tight_layout()
plt.show()
No description has been provided for this image

The field is easier to judge as a set of profiles. Each curve below is the velocity across the gap at one instant.

A contour plot shows the whole field at once but hides the shape of the profile; a set of profiles shows the shape but only at a few instants. Both are worth looking at, which is why both are here.

In [ ]:
k_list = [11, 34, 68, 114]
lim = 1.1*np.abs(u_test[0]).max()

plt.figure(figsize = (10, 3))
for j, k in enumerate(k_list):
    plt.subplot(1, 4, j + 1)
    plt.plot(u_test[0, k], y_eval, 'k', alpha = 0.3, linewidth = 4, label = 'Reference')
    plt.plot(u_pred[0, k], y_eval, 'r--', label = 'DeepONet')
    plt.xlim([-lim, lim])
    plt.title('t = %.2f' % t_eval[k])
    plt.xlabel('Velocity, u')
    if j == 0:
        plt.ylabel('y')
        plt.legend()
plt.tight_layout()
plt.show()
No description has been provided for this image

The four panels above are four instants out of 115. Below is the same test input in motion: the marker on the left rides along $G(t)$, and the profile on the right is the velocity across the gap at that instant, with every instant drawn faintly behind it.

Watch the profile cross to the other side of zero after $G$ does, not with it. For this input the pressure gradient changes sign at $t = 0.49$ and the velocity at mid-gap follows at $t = 0.58$. That delay is the fluid's inertia: the gradient sets the acceleration and not the velocity, so the profile is always catching up with the forcing, and it is the part a set of still frames does not show.

In [ ]:
frames = range(0, len(t_eval), 3)

fig, (ax_g, ax_u) = plt.subplots(1, 2, figsize = (9, 3))

j = 0
ax_g.plot(t_sensor, G_test[j], 'b')
ax_g.axhline(0, c = 'k', linewidth = 0.8)
mark, = ax_g.plot([], [], 'bo')
ax_g.set_xlim([0, 1])
ax_g.set_xlabel('t')
ax_g.set_ylabel('Pressure gradient, G')
ax_g.set_title('Input, G(t)')

for k in frames:
    ax_u.plot(u_test[j, k], y_eval, c = '0.85', linewidth = 0.6)
line_ref, = ax_u.plot([], [], 'k', alpha = 0.3, linewidth = 4, label = 'Reference')
line_pred, = ax_u.plot([], [], 'r--', label = 'DeepONet')
clock = ax_u.text(0.04, 0.90, '', transform = ax_u.transAxes)
ax_u.set_xlim([-lim, lim])
ax_u.set_xlabel('Velocity, u')
ax_u.set_ylabel('y')
ax_u.set_title('Velocity profile, u(y, t)')
ax_u.legend(loc = 'lower right')
plt.tight_layout()
plt.close()

def update(k):
    mark.set_data([t_eval[k]], [np.interp(t_eval[k], t_sensor, G_test[j])])
    line_ref.set_data(u_test[j, k], y_eval)
    line_pred.set_data(u_pred[j, k], y_eval)
    clock.set_text('t = %.2f' % t_eval[k])

anim = FuncAnimation(fig, update, frames = frames)
HTML(anim.to_jshtml(fps = 12))
Out[ ]:
No description has been provided for this image