Frontier I: operator learning (DeepONet and FNO)
Learn operators mapping functions to PDE solutions with DeepONet and Fourier Neural Operators, and evaluate resolution transfer, distribution shift and surrogate error.
After this lesson you can
- Formulate operator learning and distinguish it from vector regression and PINNs.
- Implement DeepONet and relate it to the Chen and Chen universal approximation theorem for operators.
- Implement a Fourier Neural Operator layer and explain discretization invariance and its limits.
- Generate data using a classical solver, train both operators and evaluate resolution and distribution generalization.
- Use a trained operator as a surrogate in UQ or an inverse problem and quantify its error.
Before you start
- 29Pseudospectral methods and dealiasingDiscretization invarianceMultifidelity Monte CarloPINNs versus classical solversProper orthogonal decompositionKarhunen-Loève expansionBayesian inverse problem
- 15Universal approximation theoremMicro framework to PyTorch correspondence
- 16Fully convolutional networkU-Net and skip connections
- 09Discrete Fourier transform and FFTSampling and aliasing
From one solution to a family of solutions
A PINN trained for one instance approximates a solution with specific data. In design, uncertainty or calibration you may need to solve the same equation for thousands of coefficients. Operator learning aims to approximate the complete map between function spaces, not just an output vector for one fixed input. The cost of generating pairs and training is paid before evaluating new inputs.
As an example we use stationary Darcy flow:
Positive coefficient determines the solution. For the experiment we restrict to four cosine modes with Gaussian amplitudes. This is a finite-rank family, equivalent to a Karhunen–Loève expansion after normalizing its modes: it does not represent an arbitrary random field. P1 FEM from the previous lesson generates labels; changing the mesh also changes the numerical reference approximation.
A network always receives finite representations: samples of , coordinates and discrete values of . The functional question helps reason about families and discretizations, but an empirical claim requires specifying sensors, distribution, norm and held-out data. We measure per case, with a norm over nodes: it is not an exact domain integral.
Training minimizes mean squared relative errors per instance: each field has equal weight in that mean. By contrast, dividing total squared errors by total solution energies gives larger-norm solutions more weight. Neither number identifies where failure is concentrated. If a solution has near-zero norm, relative error requires a threshold or alternative metric; here the positive source means generated solutions are nonzero, and code retains a defensive numerical threshold.
A branch for the function and a trunk for the query
DeepONet by Lu and colleagues separates input sensors from output coordinates. The branch receives and produces ; the trunk evaluates at the queried position. A scalar output has the form
The Chen and Chen operator approximation theorem, under appropriate continuity and compactness assumptions, motivates this decomposition. An existence guarantee with sufficient resources gives no required size, does not ensure the optimizer finds those parameters and does not guarantee accuracy outside the intended input class. The branch cannot distinguish two functions agreeing at all its sensors, even if their solutions differ.
Here the branch uses fixed sensors, the trunk receives coordinates and both outputs have 32 components. We multiply the sum by to impose zero Dirichlet. This changes the preceding expression: the bias is multiplied by that factor too. Learned components need not be orthogonal and inversely changing their scale in branch and trunk leaves the product unchanged. Therefore do not interpret one component as a uniquely identified physical mode. In POD the basis is obtained from snapshots using another criterion; POD-DeepONet combines a chosen reduced basis with a learned branch.
When drawing, the positive coefficient is extended without variation in direction : the P1 FEM system is assembled and solved again in the browser and the branch processes 289 samples using trained weights. The drawing may produce fields outside the four-mode training family, so it is also an exploratory out-of-distribution test. Point controls allow keyboard editing; the displayed slice is at .
The separable form also clarifies cost. If querying many coordinates for the same input, calculate branch coefficients once, then evaluate trunk and products. If the location or number of input sensors changes, this particular branch no longer directly accepts the data; interpolation adds an operation and error. Querying outputs at new locations therefore does not mean accepting inputs observed on any mesh or geometry.
Sensor choice is a model assumption. Conductivity with a narrow strip between sensors might not be represented even if its sampled values look smooth. More sensors or geometric information are alternatives, but increase cost and do not by themselves solve distribution shift. Before deploying a surrogate, test inputs differing at scales the acquisition system can actually detect and evaluate missing observations.
A spectral layer is not a spectral solver
The Fourier Neural Operator of Li and colleagues builds field-to-field layers. A simplified periodic version writes
mixes channels using complex matrices on a finite set of frequencies. Local branch preserves pointwise information; the nonlinearity can generate other frequencies. FFT assumes a periodic extension of the data, although our equation has Dirichlet conditions: coordinates and boundary factor help represent the problem, but do not automatically remove boundary artifacts. Truncating a layer’s modes is not equivalent to solving the PDE with a pseudospectral method and does not guarantee absence of aliasing after nonlinearity.
The figure shows only latent channel zero’s contribution to channel zero, plus the local branch bias; other channels and activation are missing. It is not a reconstruction of the full output. Weights were trained with six modes per block; using fewer in the figure is a post-training ablation, not a network retrained for each choice.
In two dimensions with rfft2, the last axis retains only nonnegative frequencies. Our implementation stores two complex blocks for positive and negative frequencies on the first axis. Usable modes must fit each mesh and blocks must not overlap. Stored complex parameters do not mean all components are independent degrees of freedom of a real function: Hermitian symmetry and FFT conventions matter.
The spectral operation is global: a local change can affect all positions after the inverse transform. The local branch contributes a shared transformation at each node; in a stack with activations, both contributions are recombined. By contrast, a U-Net uses local convolutions, resolution reduction and connections recovering details from earlier scales. Both families can receive grid fields, but behavior near boundaries and when changing resolution depends on specific operations, interpolation and normalization.
Resolution and distribution are different tests
Discretization invariance, in the sense of the operator family of Kovachki and colleagues, allows parameters to be shared among compatible discretizations. It does not claim error remains constant when the mesh changes. A fine input may contain frequencies absent in training, truncation may remove detail, and the discrete reference operator changes under refinement. On too coarse a mesh, different continuous functions may produce identical samples: no network can recover information it did not receive without additional assumptions.
We train with 1024 FEM pairs on nodes and hold out 128 cases from the same distribution. For transfer we solve 32 of those cases on and nodes. DeepONet retains its branch sensors and queries another set of coordinates; FNO and U-Net receive the field sampled on the evaluated mesh. A small U-Net is a practical reference, not a representation of all possible U-Nets. All three networks share the boundary factor and number of epochs, but not parameter count or compute time.
In the documented run, 40-epoch loops on CUDA took about 17.7 s for DeepONet, 54.9 s for FNO and 19.4 s for U-Net, including periodic test evaluations. These are times from one run under shared load; they exclude FEM generation and do not justify a general speed relation. The lab measures them again in the reader’s environment. An amortization study would add preparation, training and cost per query, requiring solver-comparable accuracy.
In this run FNO mean test error is about 0.00765; for an amplitude distribution twice as dispersed it is 0.0574. The plot also shows that other resolutions do not maintain the same accuracy. Do not interpret these as a universal ranking: they depend on solver, coefficient family, resolution, seeds and budget. The out-of-distribution test is not a test of all discontinuities or new geometries.
Besides the mean, inspect percentiles and worst cases, flux error and equation residuals where relevant. A different mesh may change both FEM labels and neural approximation: to isolate effects, refine the reference and evaluate all solutions on a common physical set using declared interpolation. Our plot uses nodal norms on each mesh, useful for this control but not identical to a continuous norm. More dispersed cases change the magnitude of smooth coefficients; they do not test generalization to jumps, holes or new boundary conditions.
The dataset split also matters. If multiple meshes of the same function appear in both training and test, the model may recognize the instance despite never seeing that resolution. Here coefficients are split before solving on different meshes: the 32 transferred functions come from the held-out set. A broader generalization comparison would retrain with several seeds and declare uncertainty intervals; our figures describe one run per architecture.
In evolution, a single final-time metric can hide transient errors or progressive accumulation. If a one-step prediction is composed many times, each approximate output becomes the next input and may leave the training distribution. Compare whole trajectories, mass, energy or flux as appropriate, and compare with a refined solver at the same times. This lesson’s Burgers case directly learns the map to a fixed final time; it does not establish stability of recurrent composition.
Other geometries and pretraining
Graph operators can use nodes and edges of an irregular mesh, with aggregations depending on positions and local relationships. The general neural-operator family of Kovachki and colleagues includes parametrizations of this type. A graph representation does not eliminate the need to define connectivity, quadratures, boundary conditions and tests when geometry changes. Costs may also change as neighbor count increases.
Transformers for physical fields use spatial or temporal tokens and attention mechanisms to combine distant information. One research direction pretrains on multiple PDEs and adapts the model to a new task; POSEIDON exemplifies this proposal. Transfer depends on which equations, conditions and distributions entered pretraining and which data are used for adaptation. It does not automatically make a model a reliable solver for any law or regime. When evaluating, hold out complete families and conditions, quantify long-horizon errors and check conservation and stability, not only one-step error.
Surrogates in uncertainty and calibration
A surrogate for uncertainty quantification can reduce marginal cost of evaluating many inputs, but introduces model error. For an expectation, estimate surrogate error and Monte Carlo error separately. A multifidelity scheme can correct the cheap average with differences between solver and surrogate over a paired sample; correction cost and variance also count. Comparing one network pass with a solver while ignoring data generation and training is insufficient.
For example, for scalar quantity calculated with the solver and its surrogate , use cheap evaluations and pairs from the same distribution:
If is fixed independently of evaluation samples and both samples follow the target distribution, the expectation of the first term plus the second is . The surrogate need not be exact. Usefulness depends on paired difference variance being sufficiently small relative to its cost; using a different distribution or reusing fit data without analyzing dependence can invalidate that interpretation. Our lab only compares the discrete posterior: this mean correction is presented as a possible procedure, not a measured result.
In a Bayesian inverse problem, if with Gaussian noise, replacing with changes the likelihood and can shift the posterior. Small global field error does not ensure small sensor error, especially with small observed noise. A chain converging for the approximate posterior still samples that approximate posterior; a short or poorly mixed chain adds another error source.
One option is to use the surrogate to propose candidates and then apply a correction based on the exact solver for the discrete model; preserving the desired distribution requires defining and verifying acceptance probabilities of the particular algorithm. Another is to use paired samples to correct a statistic, without claiming the approximate chain is already exact. The following example implements neither correction: it calculates both posteriors on a grid and makes their difference visible.
In the lab the parameter is one coefficient of and the prior is uniform over 301 values of . Five synthetic observations with standard deviation 0.004 are generated with FEM. The discrete posterior is normalized exactly on that grid: means are 0.8069 with FEM and 0.8188 with FNO; total variation distance is 0.0514. The generating value is 0.6, but noise and prior mean the posterior mean need not equal it. Metropolis, with 2000 discarded steps and 20000 saved, produced means 0.8041 and 0.8222. This is one chain per model: compare with exact normalization and do not infer general good mixing. It is neither an exact surrogate correction nor a continuous posterior.
Reproducible laboratory
The following cells generate data using P1 assembly, train networks and compare the posterior. Use local Python with NumPy, SciPy and PyTorch; GPU is selected only if available. Generation and training take time and memory; metrics from one run may vary by device and version. Functions and artifacts are created in the reader’s working directory. The P1 code is the actual cell from the preceding lesson, reproduced so the lab does not depend on a previous Pyodide session.
Reference P1 assembly
"""Ensamblaje P1 triangular para difusión-reacción y condiciones de borde.
Índices desde cero; nodos (n,2), triángulos (m,3). k y c son constantes
por elemento o escalares. f(x,y), g(x,y), alpha(x,y), r(x,y) son funciones
vectorizadas o escalares. Se admiten triángulos en ambas orientaciones.
"""
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
def _field(value, x, y):
result=value(x,y) if callable(value) else value
return np.broadcast_to(np.asarray(result,dtype=float),np.shape(x))
def element_geometry(nodes, triangles):
nodes=np.asarray(nodes,dtype=float); tri=np.asarray(triangles,dtype=int)
if nodes.ndim!=2 or nodes.shape[1]!=2 or tri.ndim!=2 or tri.shape[1]!=3 or len(tri)==0 or not np.all(np.isfinite(nodes)):
raise ValueError('nodos (n,2), triángulos (m,3)')
if np.any(tri<0) or np.any(tri>=len(nodes)):
raise ValueError('índice de nodo fuera de rango')
p=nodes[tri]
J=np.stack((p[:,1]-p[:,0],p[:,2]-p[:,0]),axis=-1)
det=np.linalg.det(J)
scale=np.max(np.abs(J),axis=(1,2))
if np.any(np.abs(det)<=np.finfo(float).eps*scale*scale):
raise ValueError('triángulo degenerado')
ref=np.array([[-1.,-1.],[1.,0.],[0.,1.]])
gradients=np.einsum('ij,ejk->eik',ref,np.linalg.inv(J))
return p,np.abs(det)/2,gradients
def assemble_p1(nodes, triangles, k_elem=1.0, c_elem=0.0, f=0.0):
"""Devuelve (K,C,b): rigidez, masa ponderada y carga volumétrica.
K_ij = integral k grad(phi_i).grad(phi_j), C_ij = integral c phi_i phi_j.
k,c son constantes por elemento; la carga usa cuadratura triangular de
grado 2. No incorpora automáticamente condiciones de contorno.
"""
nodes=np.asarray(nodes,dtype=float); tri=np.asarray(triangles,dtype=int)
p,area,grad=element_geometry(nodes,tri); m=len(tri); n=len(nodes)
k=np.broadcast_to(np.asarray(k_elem,dtype=float),(m,))
c=np.broadcast_to(np.asarray(c_elem,dtype=float),(m,))
if np.any(k<=0) or np.any(c<0) or not np.all(np.isfinite(k)) or not np.all(np.isfinite(c)):
raise ValueError('se requiere k positivo y c no negativo y finitos')
klocal=area[:,None,None]*k[:,None,None]*np.einsum('eik,ejk->eij',grad,grad)
mass=np.ones((3,3))+np.eye(3)
clocal=(area*c)[:,None,None]*mass[None,:,:]/12
rows=np.broadcast_to(tri[:,:,None],(m,3,3)).ravel()
cols=np.broadcast_to(tri[:,None,:],(m,3,3)).ravel()
K=coo_matrix((klocal.ravel(),(rows,cols)),shape=(n,n)).tocsr()
C=coo_matrix((clocal.ravel(),(rows,cols)),shape=(n,n)).tocsr()
bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
points=np.einsum('qi,eid->eqd',bary,p)
values=_field(f,points[:,:,0],points[:,:,1])
local=(area[:,None]/3)*np.einsum('eq,qi->ei',values,bary)
b=np.zeros(n); np.add.at(b,tri.ravel(),local.ravel())
return K,C,b
def assemble_boundary(nodes, edges, g=0.0, alpha=0.0, r=0.0):
"""Retorna (R,b): Neumann g y Robin k du/dn+alpha*u=r.
Los bordes deben ser disjuntos si no se desea sumar ambas contribuciones.
Cuadratura Gauss de dos puntos por arista.
"""
nodes=np.asarray(nodes,dtype=float); edges=np.asarray(edges,dtype=int)
if edges.ndim!=2 or edges.shape[1]!=2 or np.any(edges<0) or np.any(edges>=len(nodes)):
raise ValueError('aristas (m,2) con índices válidos')
p=nodes[edges]; length=np.linalg.norm(p[:,1]-p[:,0],axis=1)
if np.any(length<=0): raise ValueError('arista degenerada')
z=np.array([(1-1/np.sqrt(3))/2,(1+1/np.sqrt(3))/2])
basis=np.stack((1-z,z),axis=1)
points=np.einsum('qi,eid->eqd',basis,p); x,y=points[:,:,0],points[:,:,1]
ga=_field(g,x,y); ra=_field(r,x,y); aa=_field(alpha,x,y)
local_b=(length[:,None]/2)*np.einsum('eq,qi->ei',ga+ra,basis)
local_R=(length[:,None,None]/2)*np.einsum('eq,qi,qj->eij',aa,basis,basis)
m=len(edges); rows=np.broadcast_to(edges[:,:,None],(m,2,2)).ravel()
cols=np.broadcast_to(edges[:,None,:],(m,2,2)).ravel()
R=coo_matrix((local_R.ravel(),(rows,cols)),shape=(len(nodes),len(nodes))).tocsr()
b=np.zeros(len(nodes));np.add.at(b,edges.ravel(),local_b.ravel())
return R,b
def apply_dirichlet(A, b, ids, values):
"""Devuelve (A_ff,b_f,free,lift); b_f incluye -A_fD u_D."""
A=csr_matrix(A); b=np.asarray(b,dtype=float); ids=np.asarray(ids,dtype=int)
if A.shape[0]!=A.shape[1] or b.shape!=(A.shape[0],): raise ValueError('formas incompatibles')
if ids.ndim!=1 or np.any(ids<0) or np.any(ids>=len(b)) or len(np.unique(ids))!=len(ids):
raise ValueError('índices Dirichlet inválidos o repetidos')
values=np.broadcast_to(np.asarray(values,dtype=float),ids.shape)
lift=np.zeros(len(b));lift[ids]=values
mask=np.ones(len(b),dtype=bool);mask[ids]=False;free=np.flatnonzero(mask)
return A[free][:,free],(b-A@lift)[free],free,lift
def reconstruct(u_free, free, lift):
"""Inserta la solución reducida en el levantamiento y devuelve todos los nodos."""
out=np.asarray(lift,dtype=float).copy();out[np.asarray(free,dtype=int)]=u_free
return outnpm run lab and open the connection link.Data generation
The coefficient per element is the mean of its nodal values. Amplitude standard deviation is 0.4 in training and test, and 0.8 in the out-of-distribution set. All three meshes evaluate the same continuous function, but each solution comes from its own FEM. Save the data before training.
"""Datos Darcy con el FEM P1 de m29-l09; semillas independientes."""
import sys
from pathlib import Path
import numpy as np
from scipy.sparse.linalg import spsolve
def mesh(n):
t=np.linspace(0,1,n); xx,yy=np.meshgrid(t,t,indexing='xy')
nodes=np.column_stack((xx.ravel(),yy.ravel()))
tri=[]
for j in range(n-1):
for i in range(n-1):
a=j*n+i; tri.extend(((a,a+1,a+n+1),(a,a+n+1,a+n)))
boundary=np.flatnonzero((nodes[:,0]==0)|(nodes[:,0]==1)|(nodes[:,1]==0)|(nodes[:,1]==1))
return nodes,np.asarray(tri),boundary
def coefficient(nodes, coeff):
x,y=nodes.T
basis=np.stack([np.cos(np.pi*x),np.cos(np.pi*y),
.5*np.cos(2*np.pi*x)*np.cos(np.pi*y),
.5*np.cos(np.pi*x)*np.cos(2*np.pi*y)],axis=1)
return np.exp(basis@coeff)
def solve(coeff,n):
nodes,tri,boundary=mesh(n)
a=coefficient(nodes,coeff)
K,_,load=assemble_p1(nodes,tri,k_elem=a[tri].mean(axis=1),f=1.)
A,rhs,free,lift=apply_dirichlet(K,load,boundary,0.)
u=reconstruct(spsolve(A,rhs),free,lift)
return a.reshape(n,n),u.reshape(n,n)
def build(coeffs,n):
a=[]; u=[]
for i,c in enumerate(coeffs):
aa,uu=solve(c,n); a.append(aa); u.append(uu)
if (i+1)%200==0: print(n,i+1,flush=True)
return np.asarray(a,dtype=np.float32),np.asarray(u,dtype=np.float32)
rng=np.random.default_rng(26)
train_coeff=rng.normal(0,.4,(1024,4))
test_coeff=rng.normal(0,.4,(128,4))
ood_coeff=rng.normal(0,.8,(64,4))
train_a,train_u=build(train_coeff,17)
test_a,test_u=build(test_coeff,17)
ood_a,ood_u=build(ood_coeff,17)
transfer_coeff=test_coeff[:32]
transfer9_a,transfer9_u=build(transfer_coeff,9)
transfer33_a,transfer33_u=build(transfer_coeff,33)
np.savez_compressed('darcy_data.npz',train_coeff=train_coeff,test_coeff=test_coeff,
ood_coeff=ood_coeff,train_a=train_a,train_u=train_u,test_a=test_a,test_u=test_u,
ood_a=ood_a,ood_u=ood_u,transfer9_a=transfer9_a,transfer9_u=transfer9_u,
transfer33_a=transfer33_a,transfer33_u=transfer33_u)
print('datos creados: 1024/128/64, transferencia 32 instancias en 9 y 33 nodos',flush=True)
npm run lab and open the connection link.Train and measure
Models use 40 epochs and fixed seeds; test is recorded during training without selecting an epoch based on it. For more rigorous evaluation, reserve a separate validation set to choose architecture and hyperparameters and use test only at the end. Transfer metrics use the same 32 inputs; the DeepONet branch retains sensors at 17 nodes per axis.
"""Tres operadores reales sobre Darcy; métricas de resolución y distribución."""
import json, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(26)
d=np.load('darcy_data.npz')
train_a=torch.tensor(d['train_a'],device=device); train_u=torch.tensor(d['train_u'],device=device)
test_a=torch.tensor(d['test_a'],device=device); test_u=torch.tensor(d['test_u'],device=device)
ood_a=torch.tensor(d['ood_a'],device=device); ood_u=torch.tensor(d['ood_u'],device=device)
def coords(n,device):
t=torch.linspace(0,1,n,device=device)
y,x=torch.meshgrid(t,t,indexing='ij')
return torch.stack((x,y),dim=-1)
def mask(n,device):
xy=coords(n,device); x,y=xy[...,0],xy[...,1]
return x*(1-x)*y*(1-y)
class SpectralConv2d(nn.Module):
def __init__(self,width,modes):
super().__init__(); self.modes=modes
self.pos=nn.Parameter(torch.randn(width,width,modes,modes,dtype=torch.cfloat)/width)
self.neg=nn.Parameter(torch.randn(width,width,modes,modes,dtype=torch.cfloat)/width)
def forward(self,x):
batch,ch,n,m=x.shape
k=min(self.modes,n//2,m//2+1)
z=torch.fft.rfft2(x,norm='ortho')
out=torch.zeros(batch,ch,n,m//2+1,dtype=z.dtype,device=x.device)
out[:,:,:k,:k]=torch.einsum('bixy,ioxy->boxy',z[:,:,:k,:k],self.pos[:,:,:k,:k])
out[:,:,-k:,:k]=torch.einsum('bixy,ioxy->boxy',z[:,:,-k:,:k],self.neg[:,:,:k,:k])
return torch.fft.irfft2(out,s=(n,m),norm='ortho')
class FNO(nn.Module):
def __init__(self,width=20,modes=6):
super().__init__(); self.lift=nn.Linear(3,width)
self.spectral=nn.ModuleList([SpectralConv2d(width,modes) for _ in range(3)])
self.local=nn.ModuleList([nn.Conv2d(width,width,1) for _ in range(3)])
self.out=nn.Sequential(nn.Linear(width,32),nn.GELU(),nn.Linear(32,1))
def forward(self,a):
n=a.shape[-1]; xy=coords(n,a.device).expand(a.shape[0],-1,-1,-1)
x=self.lift(torch.cat((a[...,None],xy),dim=-1)).permute(0,3,1,2)
for spectral,local in zip(self.spectral,self.local): x=F.gelu(spectral(x)+local(x))
x=self.out(x.permute(0,2,3,1)).squeeze(-1)
return x*mask(n,a.device)
class DeepONet(nn.Module):
def __init__(self,p=32):
super().__init__(); self.branch=nn.Sequential(nn.Linear(17*17,96),nn.Tanh(),nn.Linear(96,96),nn.Tanh(),nn.Linear(96,p))
self.trunk=nn.Sequential(nn.Linear(2,96),nn.Tanh(),nn.Linear(96,96),nn.Tanh(),nn.Linear(96,p))
self.bias=nn.Parameter(torch.zeros(()))
def forward(self,a,query_n=None):
n=query_n or a.shape[-1]
if a.shape[-1]!=17: raise ValueError('La rama requiere sus 17×17 sensores fijos')
branch=self.branch(a.flatten(1)); trunk=self.trunk(coords(n,a.device).reshape(-1,2))
return ([email protected]+self.bias).reshape(-1,n,n)*mask(n,a.device)
class TinyUNet(nn.Module):
def __init__(self,w=20):
super().__init__()
self.enc=nn.Sequential(nn.Conv2d(3,w,3,padding=1),nn.GELU(),nn.Conv2d(w,w,3,padding=1),nn.GELU())
self.low=nn.Sequential(nn.Conv2d(w,2*w,3,padding=1),nn.GELU(),nn.Conv2d(2*w,w,3,padding=1),nn.GELU())
self.out=nn.Sequential(nn.Conv2d(2*w,w,3,padding=1),nn.GELU(),nn.Conv2d(w,1,1))
def forward(self,a):
n=a.shape[-1]; xy=coords(n,a.device).expand(a.shape[0],-1,-1,-1)
x=torch.cat((a[...,None],xy),dim=-1).permute(0,3,1,2)
skip=self.enc(x); low=self.low(F.avg_pool2d(skip,2))
up=F.interpolate(low,size=(n,n),mode='bilinear',align_corners=True)
return self.out(torch.cat((skip,up),dim=1)).squeeze(1)*mask(n,a.device)
def relative(pred,target):
return torch.linalg.vector_norm((pred-target).flatten(1),dim=1)/torch.linalg.vector_norm(target.flatten(1),dim=1).clamp_min(1e-12)
models={'DeepONet':DeepONet().to(device),'FNO':FNO().to(device),'U-Net':TinyUNet().to(device)}
history={}; elapsed={}; snapshots={}
for name,model in models.items():
opt=torch.optim.Adam(model.parameters(),lr=.001)
gen=torch.Generator(device=device).manual_seed(26)
log=[]; start=time.perf_counter()
for epoch in range(1,41):
order=torch.randperm(len(train_a),generator=gen,device=device)
model.train()
for ix in order.split(32):
opt.zero_grad(set_to_none=True)
loss=relative(model(train_a[ix]),train_u[ix]).square().mean()
loss.backward(); opt.step()
if epoch in (1,10,20,40):
model.eval()
with torch.no_grad():
error=relative(model(test_a),test_u).mean().item()
log.append({'epoch':epoch,'test_relative_mean':error})
print(name,epoch,error,flush=True)
if device.type=='cuda': torch.cuda.synchronize()
elapsed[name]=time.perf_counter()-start; history[name]=log
metrics={}; examples={}
with torch.no_grad():
for name,model in models.items():
model.eval()
metrics[name]={'test17':relative(model(test_a),test_u).mean().item(),
'ood17':relative(model(ood_a),ood_u).mean().item()}
for n in (9,33):
aa=torch.tensor(d[f'transfer{n}_a'],device=device)
uu=torch.tensor(d[f'transfer{n}_u'],device=device)
pred=model(test_a[:32],query_n=n) if name=='DeepONet' else model(aa)
metrics[name][f'transfer{n}']=relative(pred,uu).mean().item()
examples[name]=model(test_a[:1]).squeeze(0).cpu().tolist()
branch=models['DeepONet'].branch(test_a[:1].flatten(1)).squeeze(0).cpu().tolist()
trunk=models['DeepONet'].trunk(coords(17,device).reshape(-1,2)).T.reshape(32,17,17).cpu().tolist()
out={'seed':26,'device':str(device),'epochs':40,'metrics':metrics,'seconds':elapsed,'history':history,
'input':d['test_a'][0].tolist(),'truth':d['test_u'][0].tolist(),'examples':examples,
'branch':branch,'trunk':trunk,'note':'FEM P1 Darcy; 1024 entrenamiento, 128 prueba, 64 fuera de distribución; transferencia 32 entradas.'}
Path('operators_metrics.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
torch.save({k:v.state_dict() for k,v in models.items()},'operators.pt')
print('métricas',metrics,flush=True)
npm run lab and open the connection link.Posterior and Metropolis
The chain moves on integer indices with symmetric proposals up to five positions and rejects proposals outside the prior. Exact grid calculation separates posterior change from sampling error; the preceding cell must run to create operators.pt.
model=FNO().to(device)
model.load_state_dict(torch.load('operators.pt',map_location=device,weights_only=True)['FNO'])
model.eval()
theta=np.linspace(-1.5,1.5,301)
coeff=np.column_stack((theta,np.zeros((len(theta),3))))
fields,solutions=build(coeff,17)
sensors=np.array([[4,4],[8,8],[12,12],[4,12],[12,4]])
rng=np.random.default_rng(260)
_,true_u=solve(np.array([.6,0,0,0]),17)
sigma=.004
obs=true_u[sensors[:,0],sensors[:,1]]+sigma*rng.standard_normal(len(sensors))
with torch.no_grad():
model_out=[]
for chunk in np.array_split(fields,10):
model_out.append(model(torch.tensor(chunk,device=device)).cpu().numpy())
pred=np.concatenate(model_out)
direct=solutions[:,sensors[:,0],sensors[:,1]]
surrogate=pred[:,sensors[:,0],sensors[:,1]]
log_direct=-.5*np.sum(((direct-obs)/sigma)**2,axis=1)
log_sur=-.5*np.sum(((surrogate-obs)/sigma)**2,axis=1)
def normalize(logp):
p=np.exp(logp-logp.max()); return p/p.sum()
p=normalize(log_direct); q=normalize(log_sur)
def metropolis(logp,seed):
random=np.random.default_rng(seed); state=len(theta)//2; samples=[]; accepted=0
for step in range(22000):
candidate=state+int(random.integers(-5,6))
if 0<=candidate<len(theta) and np.log(random.random())<min(0.,logp[candidate]-logp[state]):
state=candidate; accepted+=1
if step>=2000: samples.append(theta[state])
return np.asarray(samples),accepted/22000
chain_p,acc_p=metropolis(log_direct,260)
chain_q,acc_q=metropolis(log_sur,261)
out={'theta':theta.tolist(),'direct_posterior':p.tolist(),'fno_posterior':q.tolist(),
'direct_mean':float(theta@p),'fno_mean':float(theta@q),'tv':float(.5*np.abs(p-q).sum()),
'mh_direct_mean':float(chain_p.mean()),'mh_fno_mean':float(chain_q.mean()),
'mh_direct_acceptance':acc_p,'mh_fno_acceptance':acc_q,'sigma':sigma,
'observations':obs.tolist(),'theta_true':.6,
'notes':'Prior uniforme sobre 301 valores; MH discreto simétrico con rechazos fuera del intervalo, 2000 burn-in y 20000 muestras. Una sola cadena por modelo; no se garantiza mezcla.'}
Path('posterior_results.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
print({k:v for k,v in out.items() if k not in ('theta','direct_posterior','fno_posterior')},flush=True)
npm run lab and open the connection link.Second problem: periodic Burgers
To separate architecture from problem, train three more models from scratch on in a periodic domain, with and final time 0.1. Input is a Gaussian combination of three sines and three cosines. Inputs are analytically calculated cell averages. We literally reuse the fv_rhs flux from finite volumes and add centered diffusion and SSP-RK3: l08 alone did not include diffusion. The step satisfies explicit advection and diffusion bounds.
The dataset has 1024 training, 128 test and 64 higher-dispersion inputs. The same 32 test inputs are solved on 32, 64, 128 and 256 cells. When restricted to 64 cells, mean relative difference of FV64 versus FV256 is 0.003394, and FV128 versus FV256 is 0.000735. This supports refinement in these cases, not a certificate of error against the exact solution. Mass conservation is checked after conversion to float32.
With 40 epochs and one seed, mean test errors on 64 cells are 0.2579 for DeepONet, 0.0053 for FNO and 0.0219 for U-Net; in the more dispersed distribution they are 0.4340, 0.0672 and 0.1100. The DeepONet branch retains 64 input averages and evaluates the trunk at centers of other meshes; its output is compared with cell averages, an approximation adding representation difference. FNO receives averages on the corresponding mesh. The 1D U-Net uses circular convolutions and receives averages on the evaluated mesh; internal resampling and scales also change with resolution. No number guarantees performance on shocks or other times.
import numpy as np
def minmod(a, b):
return np.where(a*b > 0, np.sign(a)*np.minimum(np.abs(a), np.abs(b)), 0.0)
def slope_limited(left, u, right, limiter):
dl, dr = u-left, right-u
if limiter == 'first':
return np.zeros_like(u)
if limiter == 'minmod':
return minmod(dl, dr)
if limiter == 'mc':
return minmod((dl+dr)/2, minmod(2*dl,2*dr))
if limiter == 'superbee':
p, q = minmod(2*dl,dr), minmod(dl,2*dr)
return np.where(np.abs(p)>=np.abs(q),p,q)
raise ValueError('limitador desconocido')
def fv_rhs(u, dx, flux, speed, limiter='mc', bc='periodic', numerical_flux=None):
"""Derivada semidiscreta conservativa. Frontera periódica o salida libre."""
u=np.asarray(u,dtype=float)
if u.ndim != 1 or len(u)<3 or dx<=0:
raise ValueError('u debe ser vector de al menos tres celdas y dx positivo')
if bc not in ('periodic','outflow'):
raise ValueError('frontera desconocida')
left=np.roll(u,1); right=np.roll(u,-1)
if bc == 'outflow':
left[0]=u[0]; right[-1]=u[-1]
slope=slope_limited(left,u,right,limiter)
L=np.empty(len(u)+1); R=np.empty(len(u)+1)
L[1:-1]=u[:-1]+slope[:-1]/2; R[1:-1]=u[1:]-slope[1:]/2
if bc == 'periodic':
L[0]=L[-1]=u[-1]+slope[-1]/2
R[0]=R[-1]=u[0]-slope[0]/2
else:
L[0]=R[0]=u[0]; L[-1]=R[-1]=u[-1]
if numerical_flux is None:
alpha=np.maximum(np.asarray(speed(L)),np.asarray(speed(R)))
faces=(flux(L)+flux(R))/2-alpha*(R-L)/2
else:
faces=numerical_flux(L,R)
return -(faces[1:]-faces[:-1])/dx
"""Burgers viscoso periódico con el flujo conservativo de m29-l08."""
import sys
from pathlib import Path
import numpy as np
def initial_means(coeff,n):
x=(np.arange(n)+.5)/n
result=np.zeros(n)
for j in range(3):
k=j+1
result+=np.sinc(k/n)*(coeff[2*j]*np.sin(2*np.pi*k*x)+coeff[2*j+1]*np.cos(2*np.pi*k*x))
return result
def viscous_burgers(coeff,n,nu=.02,tf=.1):
dx=1/n; u=initial_means(coeff,n); t=0.
def rhs(z):
advection=fv_rhs(z,dx,lambda q:q*q/2,np.abs,limiter='mc',bc='periodic')
diffusion=nu*(np.roll(z,-1)-2*z+np.roll(z,1))/dx**2
return advection+diffusion
while t<tf:
dt=min(tf-t,.2*dx/max(np.max(np.abs(u)),1e-12),.2*dx*dx/nu)
u1=u+dt*rhs(u);u2=.75*u+.25*(u1+dt*rhs(u1))
u=u/3+(2/3)*(u2+dt*rhs(u2));t+=dt
return initial_means(coeff,n),u
def build_burgers(coeffs,n):
pairs=[viscous_burgers(c,n) for c in coeffs]
return np.asarray([p[0] for p in pairs],dtype=np.float32),np.asarray([p[1] for p in pairs],dtype=np.float32)
rng=np.random.default_rng(126)
train=rng.normal(0,.3,(1024,6));test=rng.normal(0,.3,(128,6));ood=rng.normal(0,.6,(64,6))
data={}
for name,coeff in [('train',train),('test',test),('ood',ood)]:
data[name+'_x'],data[name+'_y']=build_burgers(coeff,64)
print(name,64,len(coeff),flush=True)
for n in (32,128,256):
data[f'transfer{n}_x'],data[f'transfer{n}_y']=build_burgers(test[:32],n)
print('transferencia',n,flush=True)
np.savez_compressed('burgers_data.npz',**data)
# Control de refinamiento sobre las mismas 32 entradas; medias finas restringidas a 64 celdas.
fine=data['transfer256_y'].reshape(32,64,4).mean(axis=2)
medium=data['transfer128_y'].reshape(32,64,2).mean(axis=2)
coarse=data['test_y'][:32]
print('error 64 vs 256:',np.mean(np.linalg.norm(coarse-fine,axis=1)/np.linalg.norm(fine,axis=1)))
print('error 128 vs 256, restringido:',np.mean(np.linalg.norm(medium-fine,axis=1)/np.linalg.norm(fine,axis=1)))
print('cambio máximo de masa:',np.max(np.abs(data['test_x'].mean(axis=1)-data['test_y'].mean(axis=1))))npm run lab and open the connection link."""DeepONet y FNO 1D con datos de Burgers viscoso periódico."""
import json,time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1);torch.manual_seed(126)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
d=np.load('burgers_data.npz')
train_x=torch.tensor(d['train_x'],device=device);train_y=torch.tensor(d['train_y'],device=device)
test_x=torch.tensor(d['test_x'],device=device);test_y=torch.tensor(d['test_y'],device=device)
ood_x=torch.tensor(d['ood_x'],device=device);ood_y=torch.tensor(d['ood_y'],device=device)
class SpectralConv1d(nn.Module):
def __init__(self,w,modes):
super().__init__();self.w=nn.Parameter(torch.randn(w,w,modes,dtype=torch.cfloat)/w)
def forward(self,x):
n=x.shape[-1];z=torch.fft.rfft(x,norm='ortho');k=min(self.w.shape[-1],n//2+1)
out=torch.zeros_like(z);out[:,:,:k]=torch.einsum('bik,iok->bok',z[:,:,:k],self.w[:,:,:k])
return torch.fft.irfft(out,n=n,norm='ortho')
class BurgersFNO(nn.Module):
def __init__(self,w=24):
super().__init__();self.lift=nn.Conv1d(1,w,1)
self.spec=nn.ModuleList([SpectralConv1d(w,12) for _ in range(3)])
self.local=nn.ModuleList([nn.Conv1d(w,w,1) for _ in range(3)])
self.out=nn.Sequential(nn.Conv1d(w,32,1),nn.GELU(),nn.Conv1d(32,1,1))
def forward(self,x):
h=self.lift(x[:,None,:])
for spec,local in zip(self.spec,self.local):h=F.gelu(spec(h)+local(h))
return self.out(h).squeeze(1)
class BurgersDeepONet(nn.Module):
def __init__(self,p=32):
super().__init__();self.branch=nn.Sequential(nn.Linear(64,96),nn.Tanh(),nn.Linear(96,p))
self.trunk=nn.Sequential(nn.Linear(2,96),nn.Tanh(),nn.Linear(96,p))
self.bias=nn.Parameter(torch.zeros(()))
def forward(self,x,n=None):
if x.shape[-1]!=64: raise ValueError('La rama usa 64 sensores fijos')
n=n or x.shape[-1];c=(torch.arange(n,device=x.device)+.5)/n
xy=torch.stack((torch.sin(2*torch.pi*c),torch.cos(2*torch.pi*c)),dim=1)
return self.branch(x)@self.trunk(xy).T+self.bias
class BurgersUNet(nn.Module):
def __init__(self,w=24):
super().__init__()
self.enc=nn.Sequential(nn.Conv1d(1,w,3,padding=1,padding_mode='circular'),nn.GELU(),
nn.Conv1d(w,w,3,padding=1,padding_mode='circular'),nn.GELU())
self.low=nn.Sequential(nn.Conv1d(w,2*w,3,padding=1,padding_mode='circular'),nn.GELU(),
nn.Conv1d(2*w,w,3,padding=1,padding_mode='circular'),nn.GELU())
self.out=nn.Sequential(nn.Conv1d(2*w,w,3,padding=1,padding_mode='circular'),nn.GELU(),nn.Conv1d(w,1,1))
def forward(self,x):
skip=self.enc(x[:,None,:]);low=self.low(F.avg_pool1d(skip,2))
up=F.interpolate(low,size=x.shape[-1],mode='linear',align_corners=False)
return self.out(torch.cat((skip,up),dim=1)).squeeze(1)
def relative(pred,target):
return torch.linalg.vector_norm(pred-target,dim=1)/torch.linalg.vector_norm(target,dim=1).clamp_min(1e-12)
models={'DeepONet':BurgersDeepONet().to(device),'FNO':BurgersFNO().to(device),'U-Net':BurgersUNet().to(device)}
history={};times={}
for name,model in models.items():
optim=torch.optim.Adam(model.parameters(),lr=.001);gen=torch.Generator(device=device).manual_seed(126)
start=time.perf_counter();history[name]=[]
for epoch in range(1,41):
order=torch.randperm(len(train_x),generator=gen,device=device)
for ix in order.split(32):
optim.zero_grad(set_to_none=True);loss=relative(model(train_x[ix]),train_y[ix]).square().mean()
loss.backward();optim.step()
if epoch in (1,10,20,40):
with torch.no_grad(): err=relative(model(test_x),test_y).mean().item()
history[name].append({'epoch':epoch,'error':err});print(name,epoch,err,flush=True)
if device.type=='cuda':torch.cuda.synchronize()
times[name]=time.perf_counter()-start
metrics={}
with torch.no_grad():
for name,model in models.items():
metrics[name]={'test64':relative(model(test_x),test_y).mean().item(),
'ood64':relative(model(ood_x),ood_y).mean().item(),
'transfer64':relative(model(test_x[:32]),test_y[:32]).mean().item()}
for n in (32,128,256):
x=torch.tensor(d[f'transfer{n}_x'],device=device); y=torch.tensor(d[f'transfer{n}_y'],device=device)
pred=model(test_x[:32],n=n) if name=='DeepONet' else model(x)
metrics[name][f'transfer{n}']=relative(pred,y).mean().item()
out={'seed':126,'device':str(device),'epochs':40,'metrics':metrics,'seconds':times,'history':history,
'notes':'Burgers viscoso periódico: FV de l08 adaptado explícitamente con difusión; medias de celda, t=.1, nu=.02.'}
Path('burgers_metrics.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
print('Burgers:',metrics,flush=True)npm run lab and open the connection link.Exercises
import torch
from torch import nn
class SpectralConv2d(nn.Module):
def __init__(self, in_ch, out_ch, modes1, modes2):
super().__init__()
# Crea dos bloques complejos de pesos.
def forward(self, x):
pass