Constrained Optimization and Adjoint Methods¶
A heater supplies one room, and a thermometer measures the temperature in a neighboring room. The wall conductances are unknown. Which conductances should change to bring the predicted temperature closer to the measurement?
The forward model predicts temperatures from conductances. An inverse update needs the derivative of the measurement loss with respect to each conductance. The adjoint computes these derivatives through one additional linear solve for a scalar objective.
The worked examples below identify wall conductances and heat sources. The state is the temperature, the parameters describe the unknown physics, and the objective measures disagreement with observations. All vector gradients are column vectors, and every derivation uses the sign convention \(\mathcal L=J-\lambda^T R\) for a residual \(R=0\).
The course page contains the same worked examples.
1. Heat exchange between two rooms¶
Temperatures and conductances¶
Room A receives a known heater power \(Q=30\) W. Room B has a thermometer that reads \(25^\circ\mathrm C\). Both rooms exchange heat with the outdoors at \(T_{\rm out}=10^\circ\mathrm C\).
The unknown conductances are \(k_1\) from Room A to outdoors, \(k_2\) through the shared wall, and \(k_3\) from Room B to outdoors. Each conductance has units W/K. A larger conductance produces a larger heat flow for a given temperature difference.
Use temperature above ambient as the state,
The observed state in Room B is therefore \(u_B^{\rm obs}=15\) K. Temperature differences have the same numerical value in kelvin and degrees Celsius. The outdoor reference state is zero.
Assume steady linear conduction and no other heat sources. The heat balances are
The first balance accounts for the heater and both heat-loss paths from Room A. The second balance equates the heat received from Room A with the heat lost outdoors. Collecting terms gives the forward system
For positive conductances, \(K\) is symmetric positive definite. Its solution gives the temperatures for a chosen parameter vector \(k\). The inverse problem adjusts \(k\) to reduce the error at Room B.
A forward prediction and its error¶
Start with \(k_1=k_2=k_3=1\) W/K. The forward system becomes
The second row gives \(u_A=2u_B\). Substituting into the first gives \(3u_B=30\), so
Room B is five degrees colder than the measurement. Use the squared measurement error as the objective,
The derivative of this objective with respect to the state is
The zero component means the loss has no explicit dependence on \(u_A\). Room A still affects the measured temperature through the heat balances. The left panel below shows the current state, and the other panels show the adjoint and parameter derivatives derived next.
The forward states are temperatures above the outdoor reference. The adjoint is driven by the signed error at Room B. The shared-wall derivative uses differences across that wall in both fields.
2. Differentiate the forward system¶
The ordinary chain rule expresses the derivative of the loss through the state sensitivity,
The heater power is fixed, so differentiating \(K(k)u(k)=q\) gives
The state sensitivity therefore satisfies a linear system with the same matrix as the forward solve,
Each parameter changes the right-hand side of this sensitivity equation. The matrix derivatives for the room model are
Using \(u=(20,10)^T\) gives
Solving these systems produces
The chain rule multiplies the second component of each sensitivity by the error \(-5\). The resulting parameter derivatives are
| Parameter | \(\partial u_B/\partial k_i\) | \(dJ/dk_i\) | Descent direction |
|---|---|---|---|
| \(k_1\) | \(-20/3\) | \(100/3\) | Decrease |
| \(k_2\) | \(10/3\) | \(-50/3\) | Increase |
| \(k_3\) | \(-20/3\) | \(100/3\) | Decrease |
The exterior conductances should decrease to retain more heat. The shared-wall conductance should increase to supply more heat to Room B. These directions follow from the local derivatives at the current parameter values.
For \(P\) conductance parameters, this direct method generally needs \(P\) additional right-hand-side solves. A factorization of \(K\) can be reused, but each sensitivity still requires a solve. Can the scalar loss derivative be computed without forming every state-sensitivity vector?
3. Rearrange the chain rule¶
The sensitivity equation can be written as \(u_{,i}=-K^{-1}K_i u\). The inverse denotes a linear solve and need not be formed. Substituting into the chain rule gives
The row vector \(e^TK^{-1}\) is the same for every parameter. Compute that vector once by defining \(\lambda^T=e^TK^{-1}\). Transposing this identity gives the adjoint equation,
The adjoint depends on the current forward state through the error \(e\). Once it is available, every parameter derivative follows from a contraction,
Both methods differentiate the same forward problem. The adjoint reduces the number of linear solves for a scalar objective. Evaluating and assembling all parameter derivatives still requires computation.
Solve the room adjoint¶
For the current room model, the adjoint equation is
Its solution is
The error at the thermometer supplies a signed right-hand side. Solving the transposed system determines how perturbations of the heat balances affect the loss. The adjoint has units determined by this sensitivity relation and need not have temperature units.
The forward and adjoint matrices agree here because the conduction matrix is symmetric. A nonsymmetric model requires the transpose. Symmetry does not remove the adjoint solve because its right-hand side differs from the heater input.
A wall derivative combines differences across that wall¶
For the shared wall, substituting \(K_2\) gives
The forward difference is \(u_A-u_B=10\). The adjoint difference is \(\lambda_A-\lambda_B=5/3\). Their negative product gives \(dJ/dk_2=-50/3\).
The exterior walls have zero reference state and zero adjoint value outside. Their derivatives are
All derivatives agree with direct differentiation. A wall with zero forward temperature difference has zero conductance sensitivity in this model. A wall with zero adjoint difference also has zero first-order influence on this objective.
Take an inverse update¶
A gradient step uses \(k^{\rm new}=k-\eta\nabla_kJ\). With \(\eta=0.005\), the updated conductances are
Solving the forward system again gives
The measurement loss decreases from \(12.5\) to \(2\). A finite step requires a new forward solve to assess its effect, and other step sizes can increase the loss. An optimizer must also preserve positive conductances, for example through bounds or a positive parameterization.
A single measured temperature cannot uniquely determine these three conductances. Different parameter combinations can reproduce the same observation. Additional heater experiments, sensors, or prior constraints are needed to distinguish them.
4. Why a Lagrange multiplier gives the adjoint¶
The room model defines a feasible state through the residual
Introduce a multiplier \(\lambda\) and define the Lagrangian
At every feasible state, \(\mathcal L=J\) for any multiplier. Differentiating along the feasible solution \(u(k)\) gives
If \(\lambda\) depends on \(k\), its derivative contributes a term proportional to \(R\), which vanishes at a feasible state. Choosing \(K^T\lambda=e\) cancels the entire state-sensitivity term. The remaining term is the parameter-gradient formula from the chain rule.
This cancellation applies at each forward prediction during optimization. The condition \(\partial\mathcal L/\partial u=0\) selects the adjoint even when the parameter gradient is nonzero. At an unconstrained interior optimum, stationarity with respect to the parameters is an additional condition.
The finite-dimensional geometry¶
Consider minimizing \(f(x,y)=x^2+y^2\) subject to \(g(x,y)=x+y-1=0\). Substitution gives \(f(x,1-x)=2x^2-2x+1\), whose minimum is at \(x=y=1/2\). The figure shows the objective level curve tangent to the feasible line at this point.
At the constrained minimum, \(\nabla f=\lambda\nabla g\). The point \((1/2,1/2)\) has multiplier \(\lambda=1\) and objective \(f=1/2\).
The Lagrangian \(\mathcal L=f-\lambda g\) gives
The multiplier enforces a relation between the objective and constraint gradients. In a simulation, the state has many components and its governing equations supply many constraints. The vector of multipliers is the adjoint state.
5. Identify heat sources on a discrete rod¶
A source parameter enters a heat balance differently from a conductance. To see the resulting gradient, consider the nondimensional rod problem
The endpoints have prescribed zero temperature. Choose interior nodes \(x_1=1/3\), \(x_2=2/3\) and spacing \(h=1/3\). Centered differences give
Define the scaled sources \(b_j=h^2s(x_j)\). The two interior balances become
Start from \(b=(3,0)^T\). The forward solution is \(u=(2,1)^T\), and a sensor at node 2 has target value \(4\). Thus the loss and its state gradient are
The current scaled sources are \((3,0)\) and the temperatures are \((2,1)\). The derivatives \((-1,-2)\) predict that increasing either source reduces the loss, with a larger first-order effect at node 2 for equal scaled-source changes.
The source gradient is the adjoint¶
The residual is now \(R(u,b)=Ku-b\). Differentiating at fixed \(K\) gives \(K\,du=db\), and the loss differential is
Define the adjoint through \(K^T\lambda=e\) as before. Then
The negative sign in \(R_b=-I\) makes the source gradient positive \(\lambda\) under the convention \(\mathcal L=J-\lambda^TR\). For this example,
Direct differentiation gives \(\partial u/\partial b_1=(2,1)^T/3\) and \(\partial u/\partial b_2=(1,2)^T/3\). Their contractions with \(e\) give the same derivatives \(-1\) and \(-2\). If the parameters are the unscaled nodal sources \(s_j\), the chain rule instead gives \(\partial J/\partial s_j=h^2\lambda_j\).
With step size \(\eta=1/2\), the scaled-source update gives
The loss decreases from \(4.5\). The sensor prediction is \(u_2=(b_1+2b_2)/3\), so every pair satisfying \(b_1+2b_2=12\) matches the observation. The adjoint supplies a derivative even when the inverse solution is nonunique.
6. A continuous source gradient¶
The continuous rod uses the same forward equation, but now suppose an entire target field is available. This observation model differs from the single sensor in the discrete example. The objective is
A source perturbation \(\delta s\) causes a state perturbation satisfying
The first-order change in the objective is
The unknown state perturbation appears in this expression. To eliminate it, multiply its governing equation by a function \(\lambda\) and integrate by parts twice,
The prescribed temperatures imply \(\delta u=0\) at both endpoints. Their derivatives \(\delta u'\) can still vary, so the remaining term \(-\lambda\delta u'\) vanishes when \(\lambda=0\) at both endpoints. This boundary calculation determines the homogeneous adjoint boundary conditions.
Choose the adjoint to satisfy
The integral above then equals \(\delta J\). Consequently,
This is the functional gradient in the \(L^2\) inner product. Its values describe the effect of spatial source perturbations on the objective. A different choice of inner product would give a different gradient representation of the same differential.
For a point sensor at \(x_s\), the adjoint right-hand side becomes \((u(x_s)-d)\delta(x-x_s)\) in the distributional formulation. The full-field loss above instead produces a distributed error source. In either case, the adjoint depends on the observation operator and its weights.
An analytic example¶
Set \(s(x)=2\) and \(u_{\rm target}(x)=2x(1-x)\). The current state is \(u(x)=x(1-x)\), so
The adjoint equation gives \(\lambda''=x-x^2\). Integrating twice and imposing the endpoint conditions produces
The figure follows the current state through its error to the source gradient. The gradient is negative throughout the interior. An increase of the source there therefore decreases the loss to first order.
The current source is \(s=2\), while the target requires \(s=4\). The midpoint gradient is \(\lambda(1/2)=-5/192\approx-0.02604\). The prescribed endpoint temperatures and the adjoint both vanish at the ends.
An independent check restricts the source to a constant amplitude \(s(x)=a\). The forward solution is \(u(x;a)=\frac a2x(1-x)\), and direct integration gives
The adjoint gives the same scalar derivative by integrating the functional gradient,
A general parameterization \(s(x;\theta)\) uses the same relation with \(\partial s/\partial\theta_i\) inside the integral. The adjoint field is computed once at the current source. Each parameter derivative then follows by integrating against its source perturbation.
7. A conductivity field uses spatial gradients¶
The shared-wall derivative involved a forward difference multiplied by an adjoint difference. A spatially varying conductivity has the continuous version of that structure. Consider the steady equation on a domain \(\Omega\) with prescribed homogeneous Dirichlet temperatures,
Assume positive scalar conductivity and an objective that depends on \(k\) only through \(u\). Let \(e\) denote its state derivative, so \(\delta J=\langle e,\delta u\rangle\). The adjoint solves
At fixed \(u\), a conductivity perturbation gives \(R_k[\delta k]=-\nabla\cdot(\delta k\nabla u)\). The adjoint eliminates \(\delta u\), leaving
The boundary term vanishes because \(\lambda=0\) there. The conductivity gradient density is therefore
Aligned forward and adjoint gradients give a negative conductivity derivative. Opposed gradients give a positive derivative, and perpendicular gradients give zero first-order sensitivity. The signed derivative determines the direction of a local conductivity update.
The square has zero boundary temperature, a source near the upper left, and a sensor near the lower right. The sensor target is twice the current prediction, so its error and the adjoint are negative. The last panel shows derivatives with respect to the nodal conductivity parameters of a conservative grid model. Green is positive and pink is negative, with zero at the dark midpoint. Every plotted derivative is checked against a separate finite-difference perturbation.
The figure uses an \(11\times11\) interior grid and arithmetic means of adjacent nodal conductivities on each edge. For an edge with conductance \(k_e\), the discrete derivative is \(-(u_i-u_j)(\lambda_i-\lambda_j)\). Each nodal conductivity derivative receives half of each incident-edge contribution under this averaging rule.
The forward field, the adjoint field, and the parameter derivative have distinct roles. The derivative formula follows from how the unknown enters the governing equation. For a source it is \(\lambda\), for a wall conductance it is a product of differences, and for a conductivity field it is a dot product of spatial gradients.
8. The general residual formula¶
The examples differ in their parameter derivatives while sharing the same chain-rule calculation. Let a differentiable simulator satisfy \(R(u,\theta)=0\), and let \(J(u,\theta)\) be a scalar objective. Assume the state Jacobian \(R_u\) is invertible at the current solution.
Differentiating the residual gives
The objective differential is
Choose the adjoint through the transposed state Jacobian,
Substituting the differentiated residual into the objective differential gives
The partial derivative accounts for explicit parameter dependence, including regularization. The residual derivative \(R_\theta\) holds the state fixed. The product \(R_\theta^T\lambda\) can be evaluated without storing a full parameter Jacobian.
| Unknown | Forward equation | Adjoint equation | Gradient for \(\mathcal L=J-\lambda^TR\) |
|---|---|---|---|
| Room conductances \(k_i\) | \(K(k)u=q\) | \(K^T\lambda=e\) | \(-\lambda^TK_i u\) |
| Scaled rod sources \(b\) | \(Ku=b\) | \(K^T\lambda=e\) | \(\lambda\) |
| Continuous source \(s\) | \(-u''=s\) | \(-\lambda''=u-u_{\rm target}\) | \(\lambda(x)\) in \(L^2\) |
| Conductivity \(k(x)\) | \(-\nabla\cdot(k\nabla u)=f\) | \(-\nabla\cdot(k\nabla\lambda)=e\) | \(-\nabla u\cdot\nabla\lambda\) in \(L^2\) |
For one scalar objective, the adjoint needs one additional linear solve after the forward state is available. This objective may combine many sensor measurements. Separate objective gradients can require separate adjoints, and total work still depends on the state and parameter dimensions.
For a nonlinear residual, the forward state may require several nonlinear iterations. The adjoint then uses the linearized state Jacobian at the converged state. The number of adjoint solves does not establish inverse uniqueness, optimizer convergence, or model accuracy.
Time-dependent simulators apply the same chain rule to a sequence of state updates. The adjoint recurrence propagates objective derivatives through the transposed update Jacobians in reverse time order. This connects the steady examples to reverse-mode automatic differentiation and the neural ODE lesson.
9. Verify the derivatives¶
The code below compares direct sensitivities, adjoints, and central finite differences for the room and discrete-rod examples. It also checks the updated losses. The figure-generation script additionally verifies the continuous example and every conductivity derivative in the square-grid figure, with values recorded in its report.
import numpy as np
def room_matrix(k):
k1, k2, k3 = k
return np.array([[k1 + k2, -k2], [-k2, k2 + k3]])
def central_difference(loss, p, eps=1e-5):
basis = np.eye(len(p))
return np.array([
(loss(p + eps * v) - loss(p - eps * v)) / (2 * eps)
for v in basis
])
k = np.ones(3)
K = room_matrix(k)
u = np.linalg.solve(K, [30., 0.])
e = np.array([0., u[1] - 15.])
K_derivatives = np.array([
[[1., 0.], [0., 0.]],
[[1., -1.], [-1., 1.]],
[[0., 0.], [0., 1.]],
])
# Each direct state sensitivity has its own right-hand side.
g_direct = np.array([
e @ np.linalg.solve(K, -Ki @ u) for Ki in K_derivatives
])
# One adjoint solve supplies every conductance derivative.
lam = np.linalg.solve(K.T, e)
g_adjoint = np.array([-lam @ Ki @ u for Ki in K_derivatives])
def room_loss(p):
state = np.linalg.solve(room_matrix(p), [30., 0.])
return 0.5 * (state[1] - 15.)**2
g_fd = central_difference(room_loss, k)
np.testing.assert_allclose(g_direct, g_adjoint)
np.testing.assert_allclose(g_fd, g_adjoint, rtol=1e-7)
np.testing.assert_allclose(room_loss(k - 0.005 * g_adjoint), 2.)
print("Room gradient:", g_adjoint)
# The rod reuses this K but places the unknowns on the right-hand side.
b = np.array([3., 0.])
u = np.linalg.solve(K, b)
e = np.array([0., u[1] - 4.])
g_adjoint = np.linalg.solve(K.T, e)
g_direct = np.linalg.solve(K, np.eye(2)).T @ e
def rod_loss(p):
return 0.5 * (np.linalg.solve(K, p)[1] - 4.)**2
g_fd = central_difference(rod_loss, b)
np.testing.assert_allclose(g_direct, g_adjoint)
np.testing.assert_allclose(g_fd, g_adjoint, rtol=1e-7)
np.testing.assert_allclose(rod_loss(b - 0.5 * g_adjoint), 169 / 72)
print("Rod gradient:", g_adjoint)