Inverse problems II: model calibration, adjoints and inverse optimization
Real inverse problems often require nonlinear calibration, such as estimating ODE rates from time series or a conductivity field from temperatures. Use nonlinear least squares and multiple shooting, assess parameter identifiability with profile likelihood, derive adjoint gradients for PDE-constrained problems and infer an objective from observed optimal decisions.
After this lesson you can
- Calibrate an ODE model with Gauss–Newton, Levenberg–Marquardt and multiple shooting to reduce sensitivity to local minima.
- Distinguish structural and practical identifiability and diagnose them with profile likelihood and Fisher information.
- Derive a PDE-constrained functional gradient with the Lagrangian and adjoint equation and verify it with the Taylor test.
- Identify a distributed coefficient in an elliptic PDE using L-BFGS and an adjoint gradient.
- Formulate a linear inverse optimization problem and recover costs consistent with an observed decision.
Before you start
- 29Tikhonov regularizationIll-posed problem in the sense of HadamardSingle and multiple shootingLocal sensitivity analysisWeak (variational) formulationFinite element assemblyODE event detection
- 06Gauss-Newton methodLevenberg-Marquardt methodLimited-memory BFGSLagrangianKarush-Kuhn-Tucker conditionsStrong duality and Slater's condition
- 03Adjoint sensitivity methodVariational equation and sensitivities
- 09Discrete versus continuous adjointBinomial checkpointing
- 05Maximum likelihood estimator (MLE)Fisher informationProfile likelihood interval
From observations to parameters
A pharmacokinetic model predicts concentrations from rates and doses. A groundwater flow model predicts pressures from conductivities and sources. Calibration reverses that direction: it selects parameters that explain observations, accounting for noise, model uncertainty and forward-problem constraints.
With observations , positive-definite covariance and prediction , a least-squares function is
The residual must be scaled in units compatible with uncertainty. introduces additional information or constraints, such as Tikhonov regularization. A low minimum does not prove parameters are unique or the model represents reality.
The example is a synthetic, noiseless damped oscillator: with , and 60 times between zero and six. The model fits two initial coefficients per segment as well as . Segments are joined by a quadratic penalty with total weight distributed across continuity defects; the profiled surface is therefore a different function from single shooting. The figure calculates its Levenberg-Marquardt trajectory using finite differences of the profiled residual. Height is clipped for visualization. Multiple shooting can ease integration difficulties but does not guarantee convexity or that an initialization reaches the global minimum.
Calibration and sensitivities
For , , define sensitivity . If is sufficiently differentiable, differentiating the equation gives
Integrate state and sensitivities together and apply the chain rule to the observation function. Direct ODE sensitivities provide the columns of the residual Jacobian . Their cost grows with the number of parameters.
ODE calibration with Gauss-Newton approximates the residual by and minimizes its norm. Levenberg-Marquardt adds damping: it solves , adjusting according to step success. Factorization of the augmented system avoids forming . Scale parameters: rates in and should not blindly be treated as if a unit step meant the same thing.
In multiple shooting, initial states are introduced for each segment, each segment is integrated and continuity constraints are imposed between its end and the next initial state. These can be imposed exactly or their defects penalized; a finite penalty allows discontinuities and changes the solution if its weight is insufficient. Separating segments can improve conditioning of a long trajectory, but increases the number of variables. An initial approximation by collocation or derivative matching can help, provided the fit to the full dynamical system is subsequently checked.
In single shooting, changing an initial condition affects all subsequent integration. If the system is unstable, a small perturbation can grow over a long interval and make the objective very sensitive. In multiple shooting each segment starts at its own variable: local integration is shorter, but constraints must make the pieces form one trajectory. A loss with an overly weak continuity penalty can fit the data well with jumps that do not satisfy the original ODE.
There is also a difference between methods for initializing a search and the final objective. In gradient matching, a smooth curve is approximated from observations and its derivatives are compared with the ODE field. Smoothing can provide a useful initialization, but differentiating noisy data amplifies noise and matching derivatives does not automatically equal maximum likelihood of the data. Integrate the ODE and examine residuals, continuity and starting-point sensitivity after fitting.
Identifiability before intervals
Structural identifiability asks whether ideal data, under the model and observation design, uniquely determine a parameter. Practical identifiability asks whether finite noisy data determine it with useful precision. An exact symmetry causes structural non-identifiability; a very insensitive direction can be identifiable in principle yet poorly determined in practice.
The figure uses one observation of product with Gaussian error and , with no upper bound on . For each , choosing reproduces that observation exactly, so its profile is flat. A second independent observation of , with value and known standard deviation, adds to the increase in . The line corresponds to the 95% quantile of ; in this individual Gaussian example it gives the exact normal interval before imposing bounds. In general nonlinear models, the asymptotic threshold requires regularity assumptions and can mislead near boundaries or with little data. The figure’s interval is clipped to the displayed range.
The local Fisher information matrix for Gaussian observations with fixed covariance is , where . If is the whitened residual Jacobian, it is . A small eigenvalue indicates a weakly informed parameter combination, but units and parameter scale matter. A likelihood profile reoptimizes other parameters for each value of the examined parameter and can reveal asymmetry, multiple minima or a flat direction hidden by a local quadratic approximation. Raue et al. study such profiles for partially observed dynamic models.
Looking at Fisher’s diagonal is not enough. If two columns of are nearly parallel, each parameter may look influential separately while a combination barely changes the prediction. The eigenvector associated with the small eigenvalue identifies that local combination after fixing a parameter scale. A profile instead explores finite values and reoptimizes the others: a curved ridge or multiple branches can escape a single-point diagnosis.
The remedy depends on the cause. If only a product is observed, repeating the same measurement reduces noise in the product but does not separate its factors. A direct measurement of or an experiment changing its effect can break the symmetry. If the difficulty is only practical, greater precision, other measurement times or a different experimental input can increase information in the weak direction. All of this assumes an adequate observation model.
PDE constraints and the adjoint
In PDE-constrained optimization, a full formulation optimizes state and parameter subject to the equation; the reduced formulation solves for the state for each parameter and optimizes only over the latter. Consider on , with on the boundary, , and
The forward equation determines . To differentiate without solving one sensitivity per component of , use Lagrangian . With appropriate boundary conditions, imposing stationarity with respect to gives
The variation with respect to in direction is
With compatible boundary conditions for , integrating the second term by parts gives formal gradient . If variations do not eliminate the boundary term, it must be retained. This derivation fixes the sign through the chosen Lagrangian convention; changing that convention changes the sign of , not the final gradient.
The discrete adjoint must match the solver actually used by the optimizer. If and , solve
This formula is obtained without forming the full Jacobian of . Differentiate the system: if the load is independent of . The loss derivative through the state is , with . Solving converts that contribution into . If the load or observation operator depends on the parameter, additional terms appear and cannot be omitted.
The continuous gradient is written with respect to a function and an inner product; a vector optimizer expects derivatives with respect to specific discrete coordinates. The mass matrix, coefficient parameterization and quadrature can change that representation. For example, if to ensure positivity, the chain rule multiplies each derivative by the corresponding value of . Confusing derivatives with respect to and changes both step direction and scale.
One state and one adjoint are needed for a scalar loss, plus assembly of all components. With many independent outputs, few inputs or limited memory, the choice between direct and adjoint sensitivities can change. Memory also matters in time evolution: the adjoint needs previous states or a checkpointing strategy.
In an assembled finite-element solver, matrix comes from the chosen weak form, Dirichlet conditions and quadrature. Differentiating that exact matrix differs from discretizing a continuous adjoint equation under other rules. The Taylor test must evaluate the same reduced function with the same tolerance and boundary treatment that L-BFGS receives.
This example uses 1000 scalar forcings in and four synthetic observations. For loss , the recursion is and . The counter compares one forward calculation plus 1000 forward finite-difference perturbations with one forward and one adjoint sweep; these are not measured times and do not include all memory costs.
import numpy as np
T = 1000
indices = np.array([250,500,750,1000])
time_index = np.arange(T)
m = .01*np.sin(2*np.pi*time_index/200)
m_true = .012*np.sin(2*np.pi*time_index/200)+.002
def evolve(forcing):
x=np.zeros(T+1)
for t in range(T):
x[t+1]=.99*x[t]+forcing[t]
return x
target = evolve(m_true)[indices]
def temporal_loss(forcing):
error=evolve(forcing)[indices]-target
return .5*error@error
x=evolve(m)
adjoint=np.zeros(T+1)
increments=np.zeros(T+1)
increments[indices]=x[indices]-target
for t in range(T,-1,-1):
adjoint[t]=increments[t]+(.99*adjoint[t+1] if t<T else 0)
gradient=adjoint[1:]
for j in (0,333,999):
direction=np.zeros(T);direction[j]=1
eps=1e-5
fd=(temporal_loss(m+eps*direction)-temporal_loss(m-eps*direction))/(2*eps)
print("índice:",j,"adjunto:",gradient[j],"diferencia central:",fd)The Taylor test checks the implemented gradient. For direction and decreasing steps , calculate
If is sufficiently smooth and the directional derivative is nonzero, is first order and second order until solver tolerances or rounding dominate. A gradient with the wrong sign usually leaves first order. The dot-product test helps check the transpose operator, but does not replace the full reduced-gradient test.
In a practical test choose a direction that respects constraints or evaluate interior points, and calculate ratio . A ratio near four indicates second order; near two indicates first order. If the linear system is solved with too loose a tolerance, the remainder may stop decreasing before asymptotic theory is visible. Repeat with several directions and tolerances; a direction accidentally orthogonal to gradient error could hide it.
Tools such as dolfin-adjoint derive adjoints from annotated FEM programs. Automatically differentiating through a solver is another possibility, but the gradient still depends on the discretized algorithm, tolerances and recorded operations. Both techniques require checking boundary conditions, nondifferentiable points and a Taylor test in the code used for optimization.
Inverse optimization
Inverse optimization seeks an objective compatible with an observed decision. For a linear problem subject to , if is feasible and the problem has an optimum, multipliers exist satisfying
These are stationarity and complementary slackness. With fixed, its slacks are data, so these constraints are linear in . But always makes any feasible decision optimal. To obtain useful information you need normalization, prior information or a reference cost and distance criterion. With noisy decisions, feasibility and optimality can be relaxed through an explicit model; there is no single “noisy version.”
The figure’s problem projects an observed cost onto the cone compatible with a vertex of using Euclidean distance. This models noise in cost, not a general model of noisy decisions. Inverse optimization shares ideas with inverse reinforcement learning, but recovering rewards from trajectories requires additional assumptions about dynamics, policy and observations.
Ahuja and Orlin study linear inverse optimization formulations with L1 and L∞ distances. The example below uses L1 and explicitly shows the relation to the forward program.
Lab: a pharmacokinetic ODE
We use a one-compartment concentration with first-order elimination, , . We generate ten synthetic observations with , and Gaussian noise of standard deviation . These are not clinical measurements. The model has solution ; therefore direct sensitivities are and . Here they are closed-form, allowing the optimizer to be checked without integration error. In models without a closed-form solution, integrate the sensitivity equations above alongside the state.
import numpy as np
from scipy.optimize import least_squares
times = np.linspace(0,5,10)
noise_std = .03
generator = np.random.default_rng(42)
observations = 1.5*np.exp(-.6*times)+generator.normal(0,noise_std,len(times))
def residual(theta):
amplitude,k = theta
return (amplitude*np.exp(-k*times)-observations)/noise_std
def jacobian(theta):
amplitude,k = theta
e = np.exp(-k*times)
return np.column_stack((e,-times*amplitude*e))/noise_std
theta_test = np.array([1.2,.5])
v = np.array([.3,-.2])
step = 1e-6
fd = (residual(theta_test+step*v)-residual(theta_test-step*v))/(2*step)
print("error de sensibilidad direccional:",np.linalg.norm(fd-jacobian(theta_test)@v))Now implement LM from the analytic Jacobian. The step is calculated using augmented least squares and accepted only if it reduces loss; damping changes with that decision. Clipping to positive parameters is applied to the candidate and loss is evaluated again. We compare with the library solver using the same data and bounds.
def lm_direct(theta0, max_iter=100):
theta = np.asarray(theta0,float).copy()
mu = 1.
accepted = 0
for _ in range(max_iter):
r,J = residual(theta),jacobian(theta)
aug = np.vstack((J,np.sqrt(mu)*np.eye(len(theta))))
delta = np.linalg.lstsq(aug,np.r_[-r,np.zeros(len(theta))],rcond=None)[0]
candidate = np.maximum(theta+delta,1e-8)
if np.linalg.norm(residual(candidate)) < np.linalg.norm(r):
change = np.linalg.norm(candidate-theta)
theta = candidate
accepted += 1
mu = max(mu/2,1e-10)
if change < 1e-10:
break
else:
mu *= 4
return theta,accepted
own, accepted = lm_direct([1.,.2])
professional = least_squares(residual,[1.,.2],jac=jacobian,bounds=(0,np.inf))
print("LM propio:",own,"pasos aceptados:",accepted)
print("scipy:",professional.x,"éxito:",professional.success)
print("diferencia entre parámetros:",np.linalg.norm(own-professional.x))
print("norma de residuo:",np.linalg.norm(residual(own)))For multiple shooting we split into three segments. Each has a free initial state; we penalize its difference from the previous segment’s end using a continuity scale. That scale is a problem choice: here it is small to approximate continuity, but does not impose it exactly. The fit does not aim to prove this simple ODE needs multiple shooting.
boundaries = np.array([0.,5/3,10/3,5.])
which = np.minimum(np.searchsorted(boundaries[1:],times,side="right"),2)
local_time = times-boundaries[which]
continuity_scale = .002
def shooting_residual(q):
k,z = q[0],q[1:]
predicted = z[which]*np.exp(-k*local_time)
defects = z[1:]-z[:-1]*np.exp(-k*np.diff(boundaries)[:-1])
return np.r_[(predicted-observations)/noise_std,defects/continuity_scale]
def shooting_jac(q):
k,z = q[0],q[1:]
decay = np.exp(-k*local_time)
J = np.zeros((len(times)+2,4))
J[:len(times),0] = -local_time*z[which]*decay/noise_std
J[np.arange(len(times)),which+1] = decay/noise_std
for j,dt in enumerate(np.diff(boundaries)[:-1]):
e=np.exp(-k*dt)
J[len(times)+j,0]=z[j]*dt*e/continuity_scale
J[len(times)+j,j+1]=-e/continuity_scale
J[len(times)+j,j+2]=1/continuity_scale
return J
start = np.r_[.2,observations[[0,3,6]]]
shoot = least_squares(shooting_residual,start,jac=shooting_jac,bounds=(0,np.inf))
k,z = shoot.x[0],shoot.x[1:]
defects = z[1:]-z[:-1]*np.exp(-k*np.diff(boundaries)[:-1])
print("disparo múltiple:",shoot.x,"éxito:",shoot.success)
print("defectos de continuidad:",defects)
print("k simple y múltiple:",own[1],k)The scale penalizes but does not force the defect to zero. If a problem requires exact continuity, use explicit constraints or a method that satisfies them; do not automatically interpret a large penalty as exact equality.
Profile and information in a model with symmetry
If only is observed with Gaussian noise, Jacobian columns are proportional and Fisher information has rank one. The infinitesimal direction keeps constant. An additional measurement of adds information in a different direction and breaks symmetry.
from scipy.stats import chi2
a0,b0 = 1.2,1.5/1.2
sigma_product,sigma_a = .1,.1
Jprod = np.array([[b0,a0]])/sigma_product
Fprod = Jprod.T@Jprod
Jextra = np.array([[1.,0.]])/sigma_a
Fboth = Fprod+Jextra.T@Jextra
print("autovalores solo producto:",np.linalg.eigvalsh(Fprod))
print("autovalores con medición de a:",np.linalg.eigvalsh(Fboth))
threshold = chi2.ppf(.95,1)
print("umbral chi-cuadrado 1:",threshold)
print("intervalo normal para a:",a0-np.sqrt(threshold)*sigma_a,a0+np.sqrt(threshold)*sigma_a)A nearly singular matrix can result from poor scaling as well as lack of information. Examine units, normalize parameters interpretably and compare measurement designs. Regularization that selects a point on a ridge does not create experimental information about the flat direction: the posterior or penalized interval depends on the chosen prior or penalty.
A complete inverse linear program
In square we observe decision and reference cost . The first component already favors , but the second favors and contradicts the observed decision. We seek the nearest compatible cost in L1 norm. The figure’s model uses Euclidean distance; both distances are choices and can select different costs in general problems.
from scipy.optimize import linprog
Aineq = np.array([[1.,0.],[-1.,0.],[0.,1.],[0.,-1.]])
bineq = np.array([1.,0.,1.,0.])
x0 = np.array([1.,0.])
reference = np.array([-.8,-.6])
slack = bineq-Aineq@x0
# Variables: c(2), y(4), t(2). Minimiza t1+t2 = ||c-reference||_1.
objective = np.r_[np.zeros(6),np.ones(2)]
equal = np.zeros((6,8)); rhs = np.zeros(6)
equal[:2,:2] = np.eye(2); equal[:2,2:6] = Aineq.T
equal[2:,2:6] = np.diag(slack)
upper = np.zeros((4,8)); upper_rhs = np.r_[reference,-reference]
upper[:2,:2] = np.eye(2); upper[:2,6:] = -np.eye(2)
upper[2:,:2] = -np.eye(2); upper[2:,6:] = -np.eye(2)
result = linprog(objective,A_ub=upper,b_ub=upper_rhs,
A_eq=equal,b_eq=rhs,bounds=[(None,None)]*2+[(0,None)]*6,
method="highs")
assert result.success, result.message
cost,y = result.x[:2],result.x[2:6]
check = linprog(cost,A_ub=Aineq,b_ub=bineq,bounds=[(None,None)]*2,method="highs")
print("coste ajustado:",cost,"multiplicadores:",y)
print("objetivo en x0 y óptimo directo:",cost@x0,check.fun)
print("residuo estacionariedad:",np.linalg.norm(cost+Aineq.T@y))
print("residuo complementariedad:",np.linalg.norm(y*slack))The forward check verifies equality of optimal values, not uniqueness of . If a component of the fitted cost is zero, other points on a face can be equally optimal. The recovered cost is nearest under the chosen norm and constraints, not necessarily an agent’s true preference.
Lab: conductivity and discrete adjoint
We use the P1 assembly from the earlier lesson. The next cell reproduces its reader implementation so this lab is self-contained: nodes shaped (n,2), triangles (m,3), stiffness and load, Dirichlet elimination with lifting and reconstruction. This experiment’s boundary conditions are homogeneous.
"""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 outThe forward mesh has 13×13 nodes and the inverse mesh 7×7. The true field contains two smooth inclusions, the load is constant, sensors occupy interior nodes and Gaussian noise has standard deviation 0.0002. The field is parameterized at coarse nodes; each triangle’s conductivity is the mean of its three nodes. The element derivative is split into thirds by the chain rule. The true field is generated on the fine mesh, not using the reconstruction matrix.
import numpy as np
from scipy.optimize import minimize
from scipy.sparse.linalg import spsolve
def square_mesh(n):
t=np.linspace(0,1,n)
xx,yy=np.meshgrid(t,t,indexing='xy')
nodes=np.column_stack((xx.ravel(),yy.ravel()))
triangles=[]
for j in range(n-1):
for i in range(n-1):
a=j*n+i;triangles.extend(((a,a+1,a+n+1),(a,a+n+1,a+n)))
tri=np.asarray(triangles,dtype=int)
boundary=np.flatnonzero((nodes[:,0]==0)|(nodes[:,0]==1)|(nodes[:,1]==0)|(nodes[:,1]==1))
return nodes,tri,boundary
def true_field(nodes):
x,y=nodes.T
return 1+1.3*np.exp(-((x-.35)**2+(y-.48)**2)/.014)+1.0*np.exp(-((x-.68)**2+(y-.62)**2)/.012)
def forward(nodes,tri,boundary,k):
K,_,b=assemble_p1(nodes,tri,k_elem=k[tri].mean(axis=1),f=1.)
A,rhs,free,lift=apply_dirichlet(K,b,boundary,0.)
return reconstruct(spsolve(A,rhs),free,lift),A,free
nodes,tri,boundary=square_mesh(7)
fine,ft,fb=square_mesh(13)
fine_u,_,_=forward(fine,ft,fb,true_field(fine))
obs_ids=np.array([j*7+i for j in range(1,6) for i in range(1,6)])
fine_ids=np.array([(2*j)*13+2*i for j in range(1,6) for i in range(1,6)])
sigma=.0002
data=fine_u[fine_ids]+np.random.default_rng(4).normal(0,sigma,len(obs_ids))
_,area,grads=element_geometry(nodes,tri)
edges=np.unique(np.sort(np.vstack((tri[:,[0,1]],tri[:,[1,2]],tri[:,[2,0]])),axis=1),axis=0)
alpha,beta,smooth=2.,.1,.01
def objective(k,mode):
u,A,free=forward(nodes,tri,boundary,k)
r=(u[obs_ids]-data)/sigma
obj=.5*r@r
rhs=np.zeros(len(nodes));np.add.at(rhs,obs_ids,r/sigma)
p=np.zeros(len(nodes));p[free]=spsolve(A.T,rhs[free])
gu=np.einsum('eik,ei->ek',grads,u[tri]);gp=np.einsum('eik,ei->ek',grads,p[tri])
eg=-area*np.einsum('ek,ek->e',gu,gp)
grad=np.zeros(len(nodes));np.add.at(grad,tri.ravel(),np.repeat(eg/3,3))
diff=k[edges[:,1]]-k[edges[:,0]]
if mode=='tik':
obj+=.5*alpha*(diff@diff)
dg=alpha*diff
else:
den=np.sqrt(diff**2+smooth**2)
obj+=alpha*np.sum(den-smooth)
dg=alpha*diff/den
obj+=.5*beta*np.sum((k-1)**2)
np.add.at(grad,edges[:,0],-dg);np.add.at(grad,edges[:,1],dg)
grad+=beta*(k-1)
return obj,grad
The objective uses the whitened sensor residual, an edge penalty and a quadratic penalty anchoring the field near one. Here “TV” denotes the sum of edge differences smoothed by a square root with parameter 0.01, not exact continuous TV. This smoothing makes the problem differentiable for L-BFGS-B; its values and weights define this experiment, not a universal choice.
base=np.ones(len(nodes))
direction=np.random.default_rng(9).normal(size=len(nodes))
direction/=np.linalg.norm(direction)
_,A0,free0=forward(nodes,tri,boundary,base)
v=np.random.default_rng(10).normal(size=len(free0))
w=np.random.default_rng(11).normal(size=len(free0))
print("prueba producto escalar:",abs(w@(A0@v)-v@(A0.T@w)))
for mode in ('tik','tv'):
value,grad=objective(base,mode)
errors=[]
for eps in (2.5e-2,1.25e-2,6.25e-3,3.125e-3):
errors.append(abs(objective(base+eps*direction,mode)[0]-value-eps*grad@direction))
print(mode,"restos Taylor:",errors,"tasas:",np.log2(np.array(errors[:-1])/errors[1:]))The dot-product test checks the reduced transpose. Taylor remainders should tend toward second order while numerical errors do not dominate; smoothed TV may require smaller steps before entering that regime. If you alter Dirichlet conditions or parameterize by log conductivity, update the gradient and repeat the test.
fits={}
def field_rmse(k):
return np.sqrt(np.mean((k-true_field(nodes))**2))
for mode in ('tik','tv'):
initial,_=objective(base,mode)
result=minimize(objective,base,args=(mode,),jac=True,method='L-BFGS-B',
bounds=[(.5,3.)]*len(base),options={'maxiter':250,'ftol':1e-10,'gtol':1e-5})
fits[mode]=result
print(mode,"éxito:",result.success,"razón:",result.message,
"objetivo inicial y final:",initial,result.fun,
"RMSE inicial y final:",field_rmse(base),field_rmse(result.x),
"rango:",result.x.min(),result.x.max())The optimizer is bounded to conductivities between 0.5 and 3. Each run prints its status and loss decrease, as well as RMSE against truth, which we know only because the data are synthetic. Sparse measurements do not guarantee recovery of the inclusions’ exact shape: the penalty, mesh and noise condition the result.
import matplotlib.pyplot as plt
fig,axes=plt.subplots(1,3,figsize=(10,3))
levels=np.linspace(.5,2.4,14)
for ax,values,label in zip(axes,[true_field(nodes),fits['tik'].x,fits['tv'].x],
['Verdad en malla gruesa','Tikhonov','TV suavizada']):
image=ax.tricontourf(nodes[:,0],nodes[:,1],tri,values,levels=levels,extend='both')
ax.scatter(nodes[obs_ids,0],nodes[obs_ids,1],s=8,c='black')
ax.set_title(label);ax.set_aspect('equal')
fig.colorbar(image,ax=axes.tolist(),label="conductividad")
plt.show()Black points represent sensors, not additional interpolated values. The two reconstructions solve different objectives; RMSE evaluates this realization, not a guarantee that one penalty always wins.
Exercises
Step 1 of 3. What is the state variation in direction v?
Step 1 of 3. Which linear optimality conditions do you impose?
import numpy as np
def taylor_test(J,grad,m,dm):
return None