Physics-informed neural networks I: formulation, forward and inverse problems
A physics-informed neural network represents the solution of a PDE and trains on its residual, boundary conditions and data. Implement forward and inverse PINNs and compare their cost and accuracy with classical solvers.
After this lesson you can
- Formulate a PINN loss for a PDE with initial and boundary conditions and data.
- Calculate higher-order input derivatives with autograd and understand their cost.
- Impose boundary conditions strongly with distance functions and weakly with penalties.
- Solve an inverse problem by estimating physical parameters and the solution from sparse noisy data.
- Compare a PINN against finite differences or FEM in error, time and dimensional scaling.
Before you start
- 29Weak (variational) formulationTikhonov regularizationPDE-constrained optimizationMethod of manufactured solutionsWeak solutions and entropy conditionODE model calibration
- 15Multilayer perceptronTanh activationMicro framework to PyTorch correspondence
- 09Mode composition and higher-order derivatives
- 06AdamLimited-memory BFGS
- 00PyTorch tensorDevice placement and CPU-GPU transfersCUDA asynchronous execution
An equation is not a collection of points
Imagine a bar where five sensors record temperature. You know the boundary conditions and the diffusion equation, but not the diffusion coefficient. A network can represent both temperature and coefficient and fit data and equation simultaneously. You do not need to build a mesh to evaluate the network, although you must choose where to evaluate the equation and where to check the solution. Not needing a mesh does not mean the result has been verified.
To understand the difference, consider the heat equation on and , with and positive integer . Candidate function has residual
At every point the residual is zero, but not between them. Zero loss on those particular points does not prove the equation has been solved. This distinction between discrete fit and solution error runs through the lesson.
This example uses and smooth front on and . Initial and boundary conditions come from that expression. The figure contains saved values from a real Adam run with seed 24, 256 fixed interior points, 64 initial and 128 boundary points. The evaluation grid has 41 positions by 21 times. In that run discrete relative error was approximately 0.957 at the start and 0.00715 after 1000 steps. The result depends on training and point distribution: it is no accuracy guarantee for other problems.
Network, equation and data
A physics-informed neural network (PINN) represents an unknown function by a network and uses network derivatives in the objective. The equation may be completely known, a forward problem, or contain parameters estimated together with , an inverse problem. The formulation of Raissi, Perdikaris and Karniadakis combines data and equation residual using automatic differentiation.
Equation, temperature and coordinates may have different units. Thus one should not simply add their residuals in physical units without thought: first nondimensionalize, or divide each component by a characteristic scale and record the weights. Changing scales changes the optimization problem unless weights are adjusted too. Unlike the weak formulation, here a strong differential equation is evaluated pointwise; a weak solution with discontinuities need not satisfy it classically at the shock. For conservation laws, see also the entropy condition.
The viscous Burgers equation is
If is known, seek to satisfy the equation and its initial and boundary data. If unknown, a parameter can be included and written to ensure positivity. An optimizer returning a number does not prove the sensors identify : two different values can yield similar observations within the noise.
Network derivatives
To calculate and , PyTorch records the computation of the output from coordinates. Calling autograd.grad with create_graph=True builds a graph for the derivative, needed both to differentiate it again and to backpropagate residual loss to parameters. Memory cost grows because intermediate operations are retained. API details are in the PyTorch documentation.
The derivative of a sum of outputs with respect to a matrix of inputs equals the desired derivatives row by row only if each output depends on its own row. An MLP applied independently to points satisfies this assumption; an architecture mixing points within a batch need not. The following snippet assumes that independence and inputs of shape (N, 2), with columns :
import torch
def residual_burgers(model, xt, nu):
xt = xt.detach().clone().requires_grad_(True)
u = model(xt)
du = torch.autograd.grad(u, xt, torch.ones_like(u), create_graph=True)[0]
ux, ut = du[:, :1], du[:, 1:2]
dux = torch.autograd.grad(ux, xt, torch.ones_like(ux), create_graph=True)[0]
uxx = dux[:, :1]
return ut + u * ux - nu * uxx
For multiple inputs, torch.func.hessian combined with vmap can express each point’s Hessian; it does not eliminate the cost of its components. The exact Laplacian is the trace of the spatial Hessian. A Hutchinson estimator uses Hessian-vector products but introduces variance: for a random vector with , . Samples must be independent of the evaluation where this identity is used, or conditioning must be justified.
import torch
from torch.func import hessian, vmap
def scalar(z):
return z[0]**2 + 3*z[1]**2
points = torch.tensor([[0.2, 0.4], [0.7, 0.1]], dtype=torch.float64)
H = vmap(hessian(scalar))(points)
print('forma', tuple(H.shape), 'diagonal del primer punto', H[0].diagonal().tolist())npm run lab and open the connection link.Here the first dimension of H enumerates points and the other two are input coordinates. For a time-dependent PDE, sum only spatial diagonal entries, not the time derivative. In a real network measure memory and cost, because vectorization does not make higher-order derivatives free.
A network with tanh activation has smooth derivatives. In contrast, a piecewise ReLU network is piecewise affine and its classical second derivatives are zero almost everywhere, so a strong second-order loss does not represent the desired curvature well. The ansatz choice is part of the method, not cosmetic.
Scales and optimization
If characteristic length is , diffusive time is . With and , the heat equation becomes . This transformation makes scales explicit before choosing weights and points. For an output with characteristic amplitude , also use ; the chain rule introduces corresponding factors in each original equation term. Normalizing data without transforming the operator changes the problem.
A common practice is to start with Adam and refine with L-BFGS. The latter evaluates the function several times per step and needs a closure that recalculates both loss and gradients; points and loss must remain fixed during a line search. Neither guarantees a global minimum. Total loss, its components and an independent error measure should be recorded separately.
For heat on , with zero endpoints and , the exact solution is . An ansatz imposing both data simultaneously is . The initial extension is compatible with endpoints; if initial and boundary data disagree at their intersections, both cannot be satisfied there without clarifying the problem. The official DeepXDE demonstration uses the same equation and checks against that exact solution.
Laboratory: reproducible traveling front
The following local cell builds a network and repeats the figure’s experiment from scratch. The exact solution allows error to be calculated without confusing it with training loss. The example checks the mechanism on a particular problem: it does not measure scaling or replace the pending comparison with finite volumes and finite elements. Initialization, points and optimizer are fixed; device differences can slightly change the result.
import torch
from torch import nn
import time
torch.manual_seed(24)
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.float64
nu = 0.1
def exact(xt):
return 0.5 * (1 - torch.tanh((xt[:, :1] - 0.5 * xt[:, 1:2]) / (4 * nu)))
def residual(model, coords, nu=nu):
xt = coords.detach().clone().requires_grad_(True)
u = model(xt)
first = torch.autograd.grad(u, xt, torch.ones_like(u), create_graph=True)[0]
second = torch.autograd.grad(first[:, :1], xt, torch.ones_like(first[:, :1]), create_graph=True)[0]
return first[:, 1:2] + u * first[:, :1] - nu * second[:, :1]
model = nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1)).to(device=device, dtype=dtype)
gen = torch.Generator(device=device).manual_seed(24)
interior = torch.rand((256, 2), generator=gen, device=device, dtype=dtype)
interior[:, 0] = 2 * interior[:, 0] - 1
initial = torch.rand((64, 2), generator=gen, device=device, dtype=dtype)
initial[:, 0] = 2 * initial[:, 0] - 1
initial[:, 1] = 0
boundary = torch.rand((128, 2), generator=gen, device=device, dtype=dtype)
boundary[:64, 0], boundary[64:, 0] = -1, 1
optimizer = torch.optim.Adam(model.parameters(), lr=0.002)
x = torch.linspace(-1, 1, 41, device=device, dtype=dtype)
t = torch.linspace(0, 1, 21, device=device, dtype=dtype)
T, X = torch.meshgrid(t, x, indexing='ij')
grid = torch.stack([X.flatten(), T.flatten()], dim=1)
truth = exact(grid)
if device.type == 'cuda':
torch.cuda.synchronize()
train_start = time.perf_counter()
for step in range(1001):
optimizer.zero_grad(set_to_none=True)
lr = residual(model, interior).square().mean()
li = (model(initial) - exact(initial)).square().mean()
lb = (model(boundary) - exact(boundary)).square().mean()
if step in (0, 100, 500, 1000):
with torch.no_grad():
err = torch.linalg.vector_norm(model(grid) - truth) / torch.linalg.vector_norm(truth)
print(step, 'error relativo', round(err.item(), 6), 'residuo', round(lr.item(), 6))
if step < 1000:
(lr + li + lb).backward()
optimizer.step()
if device.type == 'cuda':
torch.cuda.synchronize()
train_seconds = time.perf_counter() - train_startnpm run lab and open the connection link.Finite-volume control
As an independent control for this front, approximate conservative flux with a Rusanov flux and diffusion with centered differences. The following cell uses exact ghost-cell values for time-varying boundaries and compares both methods at the same centers at final time. The mesh solves a different discrete problem; repeat at higher resolution to study convergence. PINN timing includes training steps and a final evaluation, while solver timing includes time stepping. Network setup is outside the timer: the figure is illustrative, not a general hardware or method benchmark.
import numpy as np
def exact_np(x, t):
return 0.5 * (1 - np.tanh((x - 0.5*t) / (4*nu)))
N = 100
dx = 2 / N
centers = -1 + (np.arange(N) + 0.5)*dx
u_fv = exact_np(centers, 0)
steps = int(np.ceil(1 / min(0.4*dx, 0.4*dx**2/nu)))
dt = 1 / steps
start_fv = time.perf_counter()
for k in range(steps):
tk = k*dt
padded = np.r_[exact_np(-1-dx/2, tk), u_fv, exact_np(1+dx/2, tk)]
left, right = padded[:-1], padded[1:]
flux = 0.25*(left**2+right**2) - 0.5*np.maximum(np.abs(left), np.abs(right))*(right-left) - nu*(right-left)/dx
u_fv = u_fv - dt/dx*np.diff(flux)
fv_seconds = time.perf_counter() - start_fv
coords = torch.tensor(np.column_stack([centers, np.ones(N)]), device=device, dtype=dtype)
if device.type == 'cuda':
torch.cuda.synchronize()
start_prediction = time.perf_counter()
with torch.no_grad():
u_pinn = model(coords).cpu().numpy().ravel()
if device.type == 'cuda':
torch.cuda.synchronize()
pinn_seconds = train_seconds + time.perf_counter() - start_prediction
u_true = exact_np(centers, 1)
scale = np.linalg.norm(u_true)
print('errores relativos: PINN', round(np.linalg.norm(u_pinn-u_true)/scale, 6),
'volúmenes finitos', round(np.linalg.norm(u_fv-u_true)/scale, 6))
print('dispositivo PINN', device, '; volúmenes finitos en CPU')
print('tiempo medido, s: PINN entrenamiento y evaluación', round(pinn_seconds, 3),
'volúmenes finitos avance', round(fv_seconds, 3))npm run lab and open the connection link.Final-time error alone does not characterize error across the entire space-time domain. Also, comparing CPU and GPU mixes implementation and hardware. For a production comparison, measure the same norm at several resolutions and error targets and include setup, boundary conditions and evaluations required by the application.
Adapting the previous solver
The finite-volume implementation provides fv_rhs for a hyperbolic flux and periodic or outflow boundaries. The next block copies that function and its limiters from the previous lesson; it adds centered diffusion and ghost cells with time-varying exact averages. The SSP-RK3 integrator evaluates the boundary at each stage. The adaptation and its limitations belong to this lesson, not features claimed by the original solver. Compare cell averages of both methods with the integrated exact solution; the network is integrated using four-point Gaussian quadrature per cell.
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
nu = 0.1
def exact_average(x, dx, t):
left = (x-dx/2-0.5*t)/(4*nu)
right = (x+dx/2-0.5*t)/(4*nu)
return 0.5 - 2*nu/dx*(np.log(np.cosh(right))-np.log(np.cosh(left)))
def solve_viscous_l08(n):
dx = 2/n
centers = -1 + (np.arange(n)+0.5)*dx
u = exact_average(centers, dx, 0)
def rhs_viscous(v, t):
padded = np.r_[exact_average(-1-dx/2,dx,t), v, exact_average(1+dx/2,dx,t)]
transport = fv_rhs(padded, dx, lambda z: z*z/2, lambda z: np.abs(z),
limiter='first', bc='outflow')[1:-1]
diffusion = nu*(padded[2:]-2*v+padded[:-2])/dx**2
return transport + diffusion
steps = int(np.ceil(1/min(0.2*dx, 0.2*dx**2/nu)))
dt = 1/steps
for k in range(steps):
t = k*dt
u1 = u + dt*rhs_viscous(u,t)
u2 = 0.75*u + 0.25*(u1 + dt*rhs_viscous(u1,t+dt))
u = u/3 + (2/3)*(u2 + dt*rhs_viscous(u2,t+dt/2))
return centers, u, dx
start_l08 = time.perf_counter()
centers_l08, u_l08, dx_l08 = solve_viscous_l08(100)
elapsed_l08 = time.perf_counter()-start_l08
nodes, weights = np.polynomial.legendre.leggauss(4)
xq = centers_l08[:,None] + dx_l08*nodes[None,:]/2
inputs = torch.tensor(np.column_stack((xq.ravel(), np.ones(xq.size))), device=device, dtype=dtype)
if device.type == 'cuda':
torch.cuda.synchronize()
start_eval = time.perf_counter()
with torch.no_grad():
values = model(inputs).cpu().numpy().reshape(len(centers_l08),-1)
if device.type == 'cuda':
torch.cuda.synchronize()
elapsed_pinn = train_seconds + time.perf_counter()-start_eval
pinn_average = values @ weights / 2
truth_average = exact_average(centers_l08, dx_l08, 1)
norm = np.linalg.norm(truth_average)
print('errores relativos de medias de celda: PINN', round(np.linalg.norm(pinn_average-truth_average)/norm, 6),
'adaptación l08', round(np.linalg.norm(u_l08-truth_average)/norm, 6))
print('dispositivos: PINN', device, '; adaptación l08 CPU')
print('tiempo en s: PINN entrenamiento y evaluación', round(elapsed_pinn, 3), 'adaptación l08', round(elapsed_l08, 3))npm run lab and open the connection link.A first-order limiter was used for this control. The exact ghost-cell reference is useful in a manufactured problem; a real application requires implementation of the available physical condition. This run’s cost includes adaptation and stepping, while the PINN includes training and quadrature; network setup is excluded. Repeat at different resolutions and tolerances before drawing efficiency conclusions.
The next refinement keeps the same collocation points fixed. L-BFGS must be able to call the closure several times: each call zeros gradients and recalculates the three terms. The figure state and preceding comparison correspond to Adam, before this refinement.
optimizer_lbfgs = torch.optim.LBFGS(model.parameters(), max_iter=100, line_search_fn='strong_wolfe')
def burgers_closure():
optimizer_lbfgs.zero_grad(set_to_none=True)
loss = (residual(model, interior).square().mean()
+ (model(initial)-exact(initial)).square().mean()
+ (model(boundary)-exact(boundary)).square().mean())
loss.backward()
return loss
optimizer_lbfgs.step(burgers_closure)
with torch.no_grad():
err = torch.linalg.vector_norm(model(grid)-truth) / torch.linalg.vector_norm(truth)
print('error relativo tras L-BFGS', round(err.item(), 6))npm run lab and open the connection link.Exact and penalized boundaries
On an interval with homogeneous endpoint values, is a simple choice. For a domain with holes, must vanish on both the outer boundary and each hole; multiplying factors can produce gradients at very different scales. A penalty-imposed condition permits finite discrepancy in exchange for flexibility, while the hard construction removes that discrepancy by design and changes the function class explored by the optimizer.
Poisson on an annulus
The method of manufactured solutions verifies a problem with a hole without needing an external measurement. Consider annulus with and . Let and choose
Dirichlet data are zero on both circles. The cell constructs and minimizes residual . It samples uniformly in area with uniform between and . Test points are new and relative error compares with , not training residuals. Adam precedes L-BFGS; the L-BFGS closure must recalculate loss and gradients on every evaluation.
import math
torch.manual_seed(7)
generator = torch.Generator(device=device).manual_seed(7)
a, b = 0.3, 1.0
def sample_annulus(n):
q = a*a + (b*b-a*a) * torch.rand((n, 1), generator=generator, device=device, dtype=dtype)
angle = 2 * math.pi * torch.rand((n, 1), generator=generator, device=device, dtype=dtype)
return torch.cat([q.sqrt() * angle.cos(), q.sqrt() * angle.sin()], dim=1)
class AnnulusNet(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1))
def forward(self, z):
q = z.square().sum(dim=1, keepdim=True)
return (q-a*a) * (b*b-q) * self.net(z)
def annulus_source(z):
q = z.square().sum(dim=1, keepdim=True)
return -(1 + z[:, :1]) * (4*(a*a+b*b) - 16*q) - 4*z[:, :1]*(a*a+b*b-2*q)
def poisson_loss(net, points):
z = points.detach().clone().requires_grad_(True)
u = net(z)
du = torch.autograd.grad(u, z, torch.ones_like(u), create_graph=True)[0]
uxx = torch.autograd.grad(du[:, :1], z, torch.ones_like(du[:, :1]), create_graph=True)[0][:, :1]
uyy = torch.autograd.grad(du[:, 1:2], z, torch.ones_like(du[:, 1:2]), create_graph=True)[0][:, 1:2]
return (-uxx - uyy - annulus_source(z)).square().mean()
net = AnnulusNet().to(device=device, dtype=dtype)
points = sample_annulus(512)
adam = torch.optim.Adam(net.parameters(), lr=0.002)
for _ in range(800):
adam.zero_grad(set_to_none=True)
loss = poisson_loss(net, points)
loss.backward()
adam.step()
lbfgs = torch.optim.LBFGS(net.parameters(), max_iter=100, line_search_fn='strong_wolfe')
def closure():
lbfgs.zero_grad(set_to_none=True)
loss = poisson_loss(net, points)
loss.backward()
return loss
lbfgs.step(closure)
test = sample_annulus(2048)
with torch.no_grad():
q = test.square().sum(dim=1, keepdim=True)
exact_poisson = (q-a*a)*(b*b-q)*(1+test[:, :1])
error = torch.linalg.vector_norm(net(test)-exact_poisson) / torch.linalg.vector_norm(exact_poisson)
print('error relativo en puntos nuevos', round(error.item(), 6))npm run lab and open the connection link.The next cell literally reuses P1 assembly from the finite-element lesson and applies it to the same manufactured source. It measures FEM and PINN on the same nodes and refines the mesh. FEM boundaries are inscribed polygons whose vertices lie on the circles: the discrete domain differs from the exact annulus and zero data are imposed at vertices and interpolated on edges. Errors are discrete nodal norms, not an exact integral or a timing comparison. Refinement also reduces geometric error; this test does not prove the same budget works for arbitrary geometries.
from scipy.sparse.linalg import spsolve
"""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 out
def annulus_mesh(nr,nt):
radii=np.linspace(.3,1,nr+1)
theta=2*np.pi*np.arange(nt)/nt
nodes=np.array([(r*np.cos(t),r*np.sin(t)) for r in radii for t in theta])
tri=[]
for j in range(nr):
for k in range(nt):
a=j*nt+k; b=j*nt+(k+1)%nt; c=(j+1)*nt+k; d=(j+1)*nt+(k+1)%nt
tri.extend(((a,c,d),(a,d,b)))
boundary=np.r_[np.arange(nt),nr*nt+np.arange(nt)]
return nodes,np.array(tri),boundary
def exact_annulus_nodes(x,y):
q=x*x+y*y
return (q-.3**2)*(1-q)*(1+x)
def forcing(x,y):
q=x*x+y*y
return -(1+x)*(4*(.3**2+1)-16*q)-4*x*(.3**2+1-2*q)
for nr,nt in [(8,48),(16,96),(32,192)]:
nodes,tri,boundary=annulus_mesh(nr,nt)
K,_,load=assemble_p1(nodes,tri,f=forcing)
A,rhs,free,lift=apply_dirichlet(K,load,boundary,0.)
u=reconstruct(spsolve(A,rhs),free,lift)
true=exact_annulus_nodes(nodes[:,0],nodes[:,1])
with torch.no_grad():
predicted = net(torch.tensor(nodes, device=device, dtype=dtype)).cpu().numpy().ravel()
print(nr, nt, 'nodos', len(nodes), 'error FEM', np.linalg.norm(u-true)/np.linalg.norm(true),
'error PINN en los mismos nodos', np.linalg.norm(predicted-true)/np.linalg.norm(true))npm run lab and open the connection link.Identification and comparison
In a PINN inverse problem, observations constrain a solution and equation parameters simultaneously. For spatially varying diffusion, the correct conservative equation is , not unless is constant. Differentiating the flux introduces . A second network can represent , but with few sensors recovery may be unstable. Tikhonov regularization expresses a preference for stable solutions; its strength must be chosen without using test data. An adjoint method computes gradients of the same objective constrained by a PDE discretization, as in PDE-constrained optimization.
The four trajectories use the same architecture and exact wave as before, with true viscosity 0.1 and initial parameter . Each run receives 3 or 10 interior observations, noiseless or with Gaussian noise of standard deviation 0.03, as well as the same types of initial and boundary data. Those initial and boundary data also contain information about the solution. One seed per configuration cannot establish that more sensors always improve the result or quantify uncertainty. Studying identifiability requires multiple positions, noise realizations and comparison of fits obtained with alternative parameters.
A local way to study this is to write the sensor prediction vector as and calculate its Jacobian . If a direction satisfies , a small change in that direction does not alter predictions to first order. With known positive-definite noise covariance , summarizes local noise-weighted sensitivity. Full column rank of avoids first-order null directions, but does not prove global uniqueness or protect against ill-conditioning. This distinction matters especially when an entire network represents the coefficient: the effective parameter count can greatly exceed the number of sensors.
The next cell reproduces the trajectories. It uses exact, residual, device and dtype from the preceding cell; it reinitializes the network and generators for each configuration. The residual also accepts viscosity calculated from a trainable parameter.
for count in (3, 10):
for noise in (0.0, 0.03):
torch.manual_seed(24)
gen = torch.Generator(device=device).manual_seed(42)
net = nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1)).to(device=device, dtype=dtype)
alpha = nn.Parameter(torch.tensor(-2.0, device=device, dtype=dtype))
opt = torch.optim.Adam([*net.parameters(), alpha], lr=0.002)
inner = torch.rand((256, 2), generator=gen, device=device, dtype=dtype)
inner[:, 0] = 2 * inner[:, 0] - 1
start = torch.rand((64, 2), generator=gen, device=device, dtype=dtype)
start[:, 0] = 2 * start[:, 0] - 1
start[:, 1] = 0
edge = torch.rand((128, 2), generator=gen, device=device, dtype=dtype)
edge[:64, 0], edge[64:, 0] = -1, 1
sensors = torch.rand((count, 2), generator=gen, device=device, dtype=dtype)
sensors[:, 0] = 2 * sensors[:, 0] - 1
y = exact(sensors) + noise * torch.randn((count, 1), generator=gen, device=device, dtype=dtype)
for step in range(1001):
opt.zero_grad(set_to_none=True)
viscosity = torch.nn.functional.softplus(alpha)
loss = (residual(net, inner, viscosity).square().mean()
+ (net(start) - exact(start)).square().mean()
+ (net(edge) - exact(edge)).square().mean()
+ (net(sensors) - y).square().mean())
if step < 1000:
loss.backward()
opt.step()
print('sensores', count, 'ruido', noise, 'viscosidad', round(viscosity.item(), 6))npm run lab and open the connection link.An unknown diffusion field
Now study a stationary problem on , with . To generate control data, set and ; calculate from the equation and add noise to nine interior observations of . In a real application would be unavailable and coefficient error could not be measured this way.
The first reconstruction uses a discrete adjoint: discretize flux at interfaces, solve , and compute . The second uses two networks, and . Both use the same data and coefficient smoothness penalty. The PINN also penalizes residual, whereas the adjoint solves the discrete equation: they are not exactly the same optimization problem and do not have the same parameter space. The comparison aims to reveal these differences, not declare a speed winner.
import numpy as np
import scipy.linalg as la
from scipy.optimize import minimize
n, weight, reg = 99, 100.0, 0.001
h = 1 / (n + 1)
xi = np.arange(1, n + 1) * h
edges = (np.arange(n + 1) + 0.5) * h
truth_a = 1 + 0.3 * np.sin(2 * np.pi * edges)
forcing = (np.pi**2 * (1 + 0.3 * np.sin(2*np.pi*xi)) * np.sin(np.pi*xi)
- 0.6*np.pi**2*np.cos(2*np.pi*xi)*np.cos(np.pi*xi))
idx = np.arange(9, 99, 10)
rng = np.random.default_rng(24)
observed = np.sin(np.pi * xi[idx]) + 0.005 * rng.standard_normal(len(idx))
def solve_diffusion(a, rhs):
ab = np.zeros((3, n))
ab[1] = (a[:-1] + a[1:]) / h**2
ab[0, 1:] = ab[2, :-1] = -a[1:-1] / h**2
return la.solve_banded((1, 1), ab, rhs)
def inverse_objective(a):
u = solve_diffusion(a, forcing)
difference = u[idx] - observed
rhs = np.zeros(n)
rhs[idx] = 2 * weight * difference / len(idx)
p = solve_diffusion(a, rhs) # A es simétrica
up, pp = np.r_[0., u, 0.], np.r_[0., p, 0.]
d = np.diff(a)
gradient = -np.diff(up)*np.diff(pp)/h**2
gradient[:-1] -= 2 * reg * d / h
gradient[1:] += 2 * reg * d / h
return weight*np.mean(difference**2) + reg*np.sum(d*d)/h, gradient
a0 = np.ones(n+1)
direction = rng.standard_normal(n+1)
direction /= np.linalg.norm(direction)
eps = 1e-5
fd = (inverse_objective(a0+eps*direction)[0]-inverse_objective(a0-eps*direction)[0])/(2*eps)
adj = inverse_objective(a0)[1] @ direction
print('gradiente direccional: adjunto', round(adj, 8), 'diferencia centrada', round(fd, 8))
fit = minimize(inverse_objective, a0, jac=True, bounds=[(0.1, 3)]*(n+1),
method='L-BFGS-B', options={'maxiter': 500, 'ftol': 1e-12})
print('adjunto:', fit.message, 'error relativo de a', round(np.linalg.norm(fit.x-truth_a)/np.linalg.norm(truth_a), 6))
torch.manual_seed(24)
def field_net():
return nn.Sequential(nn.Linear(1,32), nn.Tanh(), nn.Linear(32,32), nn.Tanh(), nn.Linear(32,1)).to(device=device, dtype=dtype)
u_net, a_net = field_net(), field_net()
collocation = torch.linspace(0.005, 0.995, 200, device=device, dtype=dtype)[:, None]
sensor = torch.tensor(xi[idx, None], device=device, dtype=dtype)
obs = torch.tensor(observed[:, None], device=device, dtype=dtype)
def field_loss():
x = collocation.detach().clone().requires_grad_(True)
u = x*(1-x)*u_net(x)
a = torch.nn.functional.softplus(a_net(x)) + 0.1
ux = torch.autograd.grad(u, x, torch.ones_like(u), create_graph=True)[0]
flux = a*ux
flux_x = torch.autograd.grad(flux, x, torch.ones_like(flux), create_graph=True)[0]
ax = torch.autograd.grad(a, x, torch.ones_like(a), create_graph=True)[0]
f = (torch.pi**2*(1+0.3*torch.sin(2*torch.pi*x))*torch.sin(torch.pi*x)
- 0.6*torch.pi**2*torch.cos(2*torch.pi*x)*torch.cos(torch.pi*x))
prediction = sensor*(1-sensor)*u_net(sensor)
return (-flux_x-f).square().mean() + weight*(prediction-obs).square().mean() + reg*ax.square().mean()
optim = torch.optim.Adam([*u_net.parameters(), *a_net.parameters()], lr=0.002)
for _ in range(2000):
optim.zero_grad(set_to_none=True)
loss = field_loss()
loss.backward()
optim.step()
with torch.no_grad():
xedge = torch.tensor(edges[:, None], device=device, dtype=dtype)
predicted_a = (torch.nn.functional.softplus(a_net(xedge))+0.1).cpu().numpy().ravel()
print('PINN: error relativo de a', round(np.linalg.norm(predicted_a-truth_a)/np.linalg.norm(truth_a), 6))npm run lab and open the connection link.The directional gradient test checks the adjoint implementation at one point; it does not prove the inverse is identifiable. Vary noise, sensors and regularization weight, reserve observations for evaluation and compare reconstructions with their uncertainties before trusting a physical field.
The calibration lesson uses a two-dimensional P1 adjoint and checks its Taylor remainders. This problem is a one-dimensional flux with interface coefficients, not that P1 implementation: its gradient uses state and adjoint differences at each interface. We apply the same test to the previous objective and direction. Under smoothness assumptions, corrected remainders should decrease at second order before the roundoff limit.
value, gradient = inverse_objective(a0)
errors = []
for eps in (2.5e-2, 1.25e-2, 6.25e-3, 3.125e-3):
errors.append(abs(inverse_objective(a0+eps*direction)[0]-value-eps*gradient@direction))
print('restos Taylor:', errors, 'tasas:', np.log2(np.array(errors[:-1])/errors[1:]))npm run lab and open the connection link.Observed rates for this direction are close to two. The test checks the implementation locally; it does not prove identifiability or replace repetition in other directions and points.
The adjoint’s discrete penalty matches the convention of the Tikhonov lesson. If contains consecutive differences between interfaces and is their separation, then and give . That lesson’s tikhonov_general function solves an augmented linear problem. Here map is nonlinear: sensors cannot simply be passed to it as if the map were a fixed matrix. It could be used in a linearized substep with a sensitivity matrix and consistent penalty, but that would be another algorithm requiring validation.
The same inverse problem with DeepXDE
In DeepXDE geometry, residual and boundary data are declared separately. The two outputs of this network represent and an unconstrained parameter transformed to obtain . Boundary conditions are penalized instead of imposed by construction, and the network shares layers between outputs; this implementation is therefore not identical to the previous two networks. The second residual implements the smoothness penalty and the last weight corresponds to observations.
The local environment needs DeepXDE with the PyTorch backend. The environment variable is set before importing the library; run cells in order in a new session so another backend is not loaded first. This run uses xi, idx, observed and truth_a from the preceding cell.
import os
os.environ['DDE_BACKEND'] = 'pytorch'
import deepxde as dde
dde.config.set_default_float('float64')
dde.config.set_random_seed(24)
def dde_pde(x, y):
a = torch.nn.functional.softplus(y[:, 1:2]) + 0.1
ux = dde.grad.jacobian(y, x, i=0, j=0)
flux_x = dde.grad.jacobian(a * ux, x, i=0, j=0)
ax = dde.grad.jacobian(a, x, i=0, j=0)
f = (torch.pi**2*(1+0.3*torch.sin(2*torch.pi*x))*torch.sin(torch.pi*x)
- 0.6*torch.pi**2*torch.cos(2*torch.pi*x)*torch.cos(torch.pi*x))
return [-flux_x - f, np.sqrt(0.001)*ax]
geometry = dde.geometry.Interval(0, 1)
bc = dde.icbc.DirichletBC(geometry, lambda x: 0, lambda _, on: on, component=0)
observation = dde.icbc.PointSetBC(xi[idx, None], observed[:, None], component=0)
data = dde.data.PDE(geometry, dde_pde, [bc, observation], num_domain=200, num_boundary=2)
net = dde.nn.FNN([1, 32, 32, 2], 'tanh', 'Glorot normal')
model = dde.Model(data, net)
model.compile('adam', lr=0.002, loss_weights=[1, 1, 1, 100])
model.train(iterations=2000, display_every=2000)
prediction = model.predict(edges[:, None])
estimated_a = torch.nn.functional.softplus(torch.from_numpy(prediction[:, 1])).numpy() + 0.1
print('DeepXDE: error relativo de a', round(np.linalg.norm(estimated_a-truth_a)/np.linalg.norm(truth_a), 6))npm run lab and open the connection link.Collocation points, representation and boundary enforcement affect the result. In one run of this protocol the coefficient relative error at interfaces was approximately 0.241 after 2000 steps. This is one run, not evidence of library superiority. DeepXDE displays a loss called test loss, but no separate test set was requested in this configuration. The cell compares the coefficient to manufactured truth on a grid without guaranteeing all points are new; reserve independent points to evaluate generalization. A controlled comparison would align these choices and repeat across seeds.
If the unknown is a free source in , point sensors alone do not determine an arbitrary function either. For distinct interior positions , add to any compatible solution the term
It vanishes at endpoints and every sensor for any , but changes and therefore the source. Restricting the source family, adding observations or regularizing can select a solution, always under assumptions that must be stated. A small loss does not remove this structural ambiguity.
A comparison with classical solvers must fix equation, domain, conditions, accuracy, hardware and budget. Error must be measured at independent points and, when available, against an exact solution or refined reference. For a low-dimensional forward problem, a well-implemented finite-difference or finite-element method is an essential reference. In high dimension a tensor mesh cost grows rapidly, but that does not guarantee a PINN will train or generalize well. An inverse problem with sparse data is plausible, not a guarantee of superiority.
For example, a Burgers comparison must include the same viscosity, initial and boundary conditions, and space-time norm. The finite-volume method approximates fluxes between cells; a PINN evaluates a continuous ansatz at points. Their costs are not directly comparable by point count: training includes many evaluations and derivatives, while a solver also pays setup and time steps. For a single query count training cost; for many, state how many and amortize training explicitly. Without these decisions, a timing ratio can answer a different question from the apparent one.
On GPU synchronize before and after the measured interval, because operations may launch asynchronously. Record numerical precision, point count, stopping criterion and out-of-sample errors; repeat with several budgets to obtain a cost–accuracy curve. Do not compare one network run with one mesh without a convergence study and conclude one method family is better. On complex domains, building geometry and its conditions is also part of total work.
To see what changes with dimension, take a tensor mesh with nodes per axis: it has nodes in dimensions. A PINN with collocation points avoids storing that full mesh, but the needed for fixed accuracy is not universal and can grow with and solution difficulty. With the most direct nested reverse procedure, the exact Laplacian of a scalar output requires one pass for the gradient and for diagonals; a trace estimator with Hessian-vector products changes that count to an initial pass and products, at the cost of sampling error. The following count is a cost model, not measured time or a guarantee of comparable accuracy.
m, r = 10, 8
for d in (1, 2, 5, 10):
print('dimensión', d, 'nodos tensoriales', m**d,
'pasadas exactas', 1+d, 'pasadas con productos', 1+r)Choosing between methods also requires measurement at a specific tolerance and domain. The node count excludes solver sparsity and adaptivity; the derivative count also excludes cost per pass, optimization, error between points and sample count required for the estimator.
Exercises
Step 1 of 2. What happens at a boundary point?
pde_residual(model, xt, nu) for a model evaluating each row of xt independently. xt has columns x and t and the result must have shape (N, 1).import torch
def pde_residual(model, xt, nu):
passSummary
- The residual is differentiated from the network using automatic differentiation; for higher-order derivatives, ansatz regularity and the graph matter.
- A hard constraint satisfies the boundary by construction, provided the extension and boundary-vanishing function are compatible and regular.
- In an inverse problem, available information and regularization determine which parameter variations can be distinguished; a single-seed run does not quantify uncertainty.
- Compare methods on the same problem and at comparable accuracy, including full costs and independent evaluation points.