Type at least 2 letters. Enter opens the first result, Esc closes.

    Calculus for ML · Lesson 13 · Gradients of expectations and functionals

    Calculus of variations, Euler–Lagrange and physics-informed losses

    Advanced 80 min 4 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 02 (the directional derivative), lesson 03 (critical points and second-order conditions), lesson 10 (integration by parts). For section 3 it helps to know positive definite matrices (linear algebra lesson 07) and condition numbers (linear algebra lesson 13). Time: about 80 minutes, plus the notebook.


    Why this matters #

    Many laws of physics say that some integral is as small as possible, or at least stationary. An elastic body at rest minimizes its potential energy. The Poisson equation is the condition for the minimum of the Dirichlet energy. Newton's law and the wave equation make an "action" stationary (Hamilton's principle). The calculus of variations gives the derivative of a number J[u]J[u] with respect to a whole function uu, and the rule that turns "JJ is stationary" into a differential equation.

    For ML for science this gives two kinds of physics losses for a network uθu_\theta:

    • an energy (Ritz) loss minimizes the integral itself (the Deep Ritz method);
    • a residual (PINN) loss penalizes the squared residual of the differential equation (physics-informed neural networks).

    They need different derivatives, treat boundary conditions differently and fail in different ways. The same "gradient of a functional" also gives maximum-entropy distributions, the mean-field update of variational inference, gradient flows, and the adjoint equations of weather data assimilation (4D-Var) and seismic full-waveform inversion.

    1. Predict first #

    2. The picture #

    A functional maps a function to a number. Two examples on [a,b][a, b]:

    • the length of the graph of uu:   J[u]=∫ab1+u′(x)2 dx\;J[u] = \int_a^b \sqrt{1 + u'(x)^2}\,dx;
    • the Dirichlet energy with a load ff:   J[u]=∫ab(12u′(x)2−f(x) u(x)) dx\;J[u] = \int_a^b \big(\tfrac12 u'(x)^2 - f(x)\,u(x)\big)\,dx. For an elastic string, 12u′2\tfrac12 u'^2 is the stored energy of the stretch and −fu-fu is the work of the load.

    The general form is J[u]=∫abL(x,u,u′) dxJ[u] = \int_a^b L(x, u, u')\,dx. The function L(x,u,p)L(x, u, p) is the Lagrangian; pp stands for the slope u′u'.

    A functional on a grid is a function of many variables #

    Put uu on a grid to see JJ as an ordinary function. Take xi=a+ihx_i = a + ih for i=0,…,Ni = 0, \dots, N, with h=(b−a)/Nh = (b - a)/N, and values Ui≈u(xi)U_i \approx u(x_i). For the Dirichlet energy a simple discretization is

    Jh(U)=∑i=0N−1h⋅12(Ui+1−Uih)2  −  ∑i=1N−1h f(xi) Ui,J_h(U) = \sum_{i=0}^{N-1} h \cdot \tfrac12 \Big(\frac{U_{i+1} - U_i}{h}\Big)^2 \;-\; \sum_{i=1}^{N-1} h\, f(x_i)\, U_i ,

    with the boundary values U0U_0 and UNU_N fixed. A minimizer has ∂Jh/∂Ui=0\partial J_h/\partial U_i = 0 at every interior point. Let us compute this partial derivative step by step.

    1. UiU_i appears in two slopes: pi−1/2=(Ui−Ui−1)/hp_{i-1/2} = (U_i - U_{i-1})/h (the cell on its left) and pi+1/2=(Ui+1−Ui)/hp_{i+1/2} = (U_{i+1} - U_i)/h (the cell on its right).
    2. The left term h⋅12pi−1/22h \cdot \tfrac12 p_{i-1/2}^2 has derivative h⋅pi−1/2⋅1h=pi−1/2h \cdot p_{i-1/2} \cdot \frac1h = p_{i-1/2}.
    3. The right term h⋅12pi+1/22h \cdot \tfrac12 p_{i+1/2}^2 has derivative h⋅pi+1/2⋅(−1h)=−pi+1/2h \cdot p_{i+1/2} \cdot \big(-\frac1h\big) = -p_{i+1/2}.
    4. The load term gives −hf(xi)-h f(x_i). Together:
    ∂Jh∂Ui=pi−1/2−pi+1/2−hf(xi)=−h[Ui+1−2Ui+Ui−1h2+f(xi)]≈−h [u′′(xi)+f(xi)].\frac{\partial J_h}{\partial U_i} = p_{i-1/2} - p_{i+1/2} - h f(x_i) = -h\Big[\frac{U_{i+1} - 2U_i + U_{i-1}}{h^2} + f(x_i)\Big] \approx -h\,\big[u''(x_i) + f(x_i)\big].

    The last step uses the second difference (lesson 07): (Ui+1−2Ui+Ui−1)/h2≈u′′(xi)(U_{i+1} - 2U_i + U_{i-1})/h^2 \approx u''(x_i). Three things to see here.

    • The factor hh. UiU_i controls a piece of length hh of the integral, so its partial derivative is hh times a density. Divided by hh, the gradient becomes a function of xx: the functional derivative δJ/δu=−u′′−f\delta J/\delta u = -u'' - f.
    • Where d/dxd/dx comes from. UiU_i sits in two neighbouring slopes, so the gradient contains the difference of ∂L/∂p=p\partial L/\partial p = p across the cell. That difference, divided by hh, is −ddx∂L/∂p-\frac{d}{dx}\partial L/\partial p. This is integration by parts on a grid.
    • The equation. Setting the gradient to zero gives −u′′=f-u'' = f, the Poisson equation, with the fixed boundary values. The minimum of a functional is the solution of a differential equation.
    Interactive figure: loading…

    Change N in both views. For J[u]=∫01(12u′2−u) dxJ[u] = \int_0^1 (\tfrac12 u'^2 - u)\,dx and a fixed function uu, the raw gradient ∂Jh/∂Ui\partial J_h/\partial U_i gets smaller as the grid gets finer. Switch to "(1/h) ∂Jh/∂Ui(1/h)\,\partial J_h/\partial U_i": the dots now lie on the curve δJ/δu=−u′′−1\delta J/\delta u = -u'' - 1 (black). For the minimizer u=x(1−x)/2u = x(1 - x)/2 the gradient is zero at every grid point.

    Variations are directions in function space #

    In the continuous version, we perturb uu in a direction η\eta. The direction is itself a function, and it must be zero where uu is fixed (here at both ends), so that u+ϵηu + \epsilon\eta still has the right boundary values. Then φ(ϵ)=J[u+ϵη]\varphi(\epsilon) = J[u + \epsilon\eta] is an ordinary function of one number ϵ\epsilon. If uu is a minimizer, φ\varphi has its minimum at ϵ=0\epsilon = 0, so φ′(0)=0\varphi'(0) = 0. This is the directional derivative ∇f(x)⊤v\nabla f(x)^\top v of lesson 02, with a function η\eta in place of the vector vv.

    Interactive figure: loading…

    Drag the violet handle. It moves a smooth bump η\eta (dashed) along the curve and changes ϵ\epsilon. The functional is J[u]=∫01u′2 dxJ[u] = \int_0^1 u'^2\,dx with u(0)=0u(0) = 0 and u(1)=1u(1) = 1. The chart shows φ(ϵ)=J[u+ϵη]\varphi(\epsilon) = J[u + \epsilon\eta], a parabola, and its tangent at ϵ=0\epsilon = 0. For u=x2u = x^2 the slope at 00 is not zero, so u=x2u = x^2 is not a minimizer. Switch to u=xu = x: the slope is 00 for every bump you try.

    Quick check

    In the figure, J[u]=∫01u′2 dxJ[u] = \int_0^1 u'^2\,dx with u(0)=0u(0) = 0, u(1)=1u(1) = 1. For which curve is the slope of φ(ϵ)=J[u+ϵη]\varphi(\epsilon) = J[u + \epsilon\eta] at ϵ=0\epsilon = 0 zero for every bump η\eta?

    Quick check

    On a grid with spacing hh, how is the partial derivative ∂Jh/∂Ui\partial J_h/\partial U_i of the discretized functional related to the functional derivative δJ/δu\delta J/\delta u?

    3. Definitions and main results #

    Setup. L(x,u,p)L(x, u, p) is a twice continuously differentiable (C2C^2) function of three real variables. The functional is J[u]=∫abL(x,u(x),u′(x)) dxJ[u] = \int_a^b L(x, u(x), u'(x))\,dx. The admissible functions are u∈C2[a,b]u \in C^2[a, b] with u(a)=αu(a) = \alpha and u(b)=βu(b) = \beta. We write Lu=∂L/∂uL_u = \partial L/\partial u, Lp=∂L/∂pL_p = \partial L/\partial p, Lpp=∂2L/∂p2L_{pp} = \partial^2 L/\partial p^2, and so on, always evaluated along (x,u(x),u′(x))(x, u(x), u'(x)).

    First variation. For η∈C2[a,b]\eta \in C^2[a, b] with η(a)=η(b)=0\eta(a) = \eta(b) = 0, the function u+ϵηu + \epsilon\eta is admissible for every ϵ\epsilon. The first variation is

    δJ[u;η]=ddϵJ[u+ϵη]∣ϵ=0=∫ab(Lu η+Lp η′) dx.\delta J[u; \eta] = \frac{d}{d\epsilon} J[u + \epsilon\eta]\Big|_{\epsilon = 0} = \int_a^b \big(L_u\, \eta + L_p\, \eta'\big)\,dx .

    To get the integral, differentiate under the integral sign and use the chain rule: ddϵL(x,u+ϵη,u′+ϵη′)=Lu η+Lp η′\frac{d}{d\epsilon} L(x, u + \epsilon\eta, u' + \epsilon\eta') = L_u\,\eta + L_p\,\eta'.

    Functional derivative. If a function δJ/δu\delta J/\delta u satisfies δJ[u;η]=∫abδJδu(x) η(x) dx\delta J[u; \eta] = \int_a^b \frac{\delta J}{\delta u}(x)\, \eta(x)\,dx for every such η\eta, it is the functional derivative of JJ at uu. It is the gradient of JJ for the L2L^2 inner product ⟨g,η⟩=∫g η dx\langle g, \eta \rangle = \int g\,\eta\,dx, in the same way as ∇f\nabla f satisfies Df(x) v=∇f(x)⊤vDf(x)\,v = \nabla f(x)^\top v. On a grid of spacing hh: ∂Jh/∂Ui≈h δJδu(xi)\partial J_h/\partial U_i \approx h\, \frac{\delta J}{\delta u}(x_i).

    The fundamental lemma #

    Lemma (fundamental lemma of the calculus of variations). Let gg be continuous on [a,b][a, b], and let ∫abg η dx=0\int_a^b g\,\eta\,dx = 0 for every smooth η\eta that is zero outside some closed interval inside (a,b)(a, b). Then g(x)=0g(x) = 0 for every x∈[a,b]x \in [a, b].

    The idea: if gg were positive somewhere, a bump η\eta placed exactly there would make ∫gη>0\int g\eta > 0.

    Proof of the fundamental lemma
    1. Suppose g(x0)≠0g(x_0) \ne 0 for some x0∈(a,b)x_0 \in (a, b). Replacing gg by −g-g if needed, g(x0)>0g(x_0) > 0.
    2. By continuity, g>0g > 0 on a closed interval [x0−δ,x0+δ]⊂(a,b)[x_0 - \delta, x_0 + \delta] \subset (a, b) for some δ>0\delta > 0.
    3. Take the smooth bump η(x)=exp⁡(−1/(δ2−(x−x0)2))\eta(x) = \exp\big(-1/(\delta^2 - (x - x_0)^2)\big) inside this interval and η=0\eta = 0 outside. It is smooth, positive inside and zero outside.
    4. Then gη>0g\eta > 0 inside the interval and gη=0g\eta = 0 outside, so ∫gη dx>0\int g\eta\,dx > 0. This contradicts the assumption.
    5. So g=0g = 0 on (a,b)(a, b), and by continuity also at aa and bb. ■\blacksquare

    The Euler–Lagrange equation #

    Theorem (Euler–Lagrange equation). Let L∈C2L \in C^2, and let the admissible u∈C2u \in C^2 be a local minimizer of JJ: J[u]≤J[v]J[u] \le J[v] for every admissible vv with max⁡∣v−u∣+max⁡∣v′−u′∣\max|v - u| + \max|v' - u'| small enough. Then

    Lu−ddxLp=0on [a,b].L_u - \frac{d}{dx} L_p = 0 \quad \text{on } [a, b].

    The proof uses integration by parts (lesson 10) in this form:

    ∫abLp η′ dx=[Lp η]ab−∫ab(ddxLp)η dx.\int_a^b L_p\,\eta'\,dx = \big[L_p\,\eta\big]_a^b - \int_a^b \Big(\frac{d}{dx}L_p\Big)\eta\,dx .

    Proof.

    1. Fix η∈C2\eta \in C^2 with η(a)=η(b)=0\eta(a) = \eta(b) = 0. For small ∣ϵ∣|\epsilon|, u+ϵηu + \epsilon\eta is admissible and close to uu, so φ(ϵ)=J[u+ϵη]\varphi(\epsilon) = J[u + \epsilon\eta] has a local minimum at ϵ=0\epsilon = 0. Hence φ′(0)=0\varphi'(0) = 0.
    2. φ′(0)=∫ab(Lu η+Lp η′) dx\varphi'(0) = \int_a^b (L_u\,\eta + L_p\,\eta')\,dx. (Differentiation under the integral is allowed: LL is C2C^2 and [a,b][a, b] is a closed bounded interval.)
    3. Integrate the second term by parts (the formula above). The boundary term [Lp η]ab\big[L_p\,\eta\big]_a^b is 00 because η(a)=η(b)=0\eta(a) = \eta(b) = 0. (ddxLp\frac{d}{dx}L_p is continuous because L∈C2L \in C^2 and u∈C2u \in C^2.)
    4. So ∫ab(Lu−ddxLp) η dx=0\int_a^b \big(L_u - \tfrac{d}{dx}L_p\big)\,\eta\,dx = 0 for every such η\eta.
    5. g=Lu−ddxLpg = L_u - \frac{d}{dx}L_p is continuous, so the fundamental lemma gives g=0g = 0. ■\blacksquare

    Step 4 also shows that

    δJδu=Lu−ddxLp.\frac{\delta J}{\delta u} = L_u - \frac{d}{dx} L_p .

    The derivative ddx\frac{d}{dx} is a total derivative along the curve: LpL_p depends on xx directly and through u(x)u(x) and u′(x)u'(x). By the chain rule,

    ddxLp(x,u,u′)=Lpx+Lpu u′+Lpp u′′.\frac{d}{dx} L_p(x, u, u') = L_{px} + L_{pu}\, u' + L_{pp}\, u'' .

    So the Euler–Lagrange equation Lu−Lpx−Lpuu′−Lppu′′=0L_u - L_{px} - L_{pu}u' - L_{pp}u'' = 0 is a second-order ODE when Lpp≠0L_{pp} \ne 0. It comes with two boundary conditions. Example: for L=12x u′2L = \tfrac12 x\,u'^2 we have Lp=xu′L_p = xu', so ddxLp=u′+xu′′\frac{d}{dx}L_p = u' + xu'', not only xu′′xu''.

    Natural boundary conditions #

    Now fix only u(a)=αu(a) = \alpha and leave u(b)u(b) free. Then the directions η\eta must have η(a)=0\eta(a) = 0, but η(b)\eta(b) can be anything. Step 3 of the proof now keeps one boundary term, at x=bx = b:

    0=Lp(b,u(b),u′(b)) η(b)+∫ab(Lu−ddxLp)η dx.0 = L_p\big(b, u(b), u'(b)\big)\,\eta(b) + \int_a^b \Big(L_u - \frac{d}{dx}L_p\Big)\eta\,dx .
    1. First take all η\eta with η(b)=0\eta(b) = 0. As before, the Euler–Lagrange equation holds, so the integral is 00 for every η\eta.
    2. Then take an η\eta with η(b)=1\eta(b) = 1. The equation above becomes Lp(b,u(b),u′(b))=0L_p\big(b, u(b), u'(b)\big) = 0.

    This is the natural boundary condition. You do not impose it; the minimization produces it. For L=12u′2+…L = \tfrac12 u'^2 + \dots it is u′(b)=0u'(b) = 0, a Neumann condition. Prescribed values such as u(a)=αu(a) = \alpha are called essential (Dirichlet) conditions.

    Quick check

    Minimize J[u]=∫01(12u′2−fu) dxJ[u] = \int_0^1 \big(\tfrac12 u'^2 - f u\big)\,dx with u(0)=0u(0) = 0 fixed and u(1)u(1) free. Which condition holds at x=1x = 1?

    When is a solution a minimum? #

    The Euler–Lagrange equation is a necessary condition: maxima and saddle points of JJ satisfy it too. A sufficient condition:

    Theorem. If L(x,u,p)L(x, u, p) is convex in (u,p)(u, p) for every xx, then every admissible solution of the Euler–Lagrange equation is a global minimizer.

    Proof. Let vv be admissible and η=v−u\eta = v - u, so η(a)=η(b)=0\eta(a) = \eta(b) = 0. Convexity says that LL lies above its tangent plane: L(x,v,v′)≥L(x,u,u′)+Lu η+Lp η′L(x, v, v') \ge L(x, u, u') + L_u\,\eta + L_p\,\eta' at every xx. Integrate:

    J[v]≥J[u]+δJ[u;η]=J[u]+∫ab(Lu−ddxLp)η dx=J[u].■J[v] \ge J[u] + \delta J[u; \eta] = J[u] + \int_a^b \Big(L_u - \frac{d}{dx}L_p\Big)\eta\,dx = J[u]. \qquad \blacksquare

    Without convexity, the second variation φ′′(0)\varphi''(0) decides, like the Hessian in lesson 03. A necessary condition for a minimum is Lpp≥0L_{pp} \ge 0 along uu (the Legendre condition).

    Several variables #

    For u:Ω⊂Rd→Ru: \Omega \subset \R^d \to \R and J[u]=∫ΩL(x,u,∇u) dxJ[u] = \int_\Omega L(x, u, \nabla u)\,dx, write p=∇u∈Rdp = \nabla u \in \R^d and let ∇pL\nabla_p L be the vector of partial derivatives of LL in pp. The same steps work with the divergence theorem in place of integration by parts:

    ∫Ω∇pL⋅∇η dx=∫∂Ωη (∇pL⋅n) dS−∫Ω(∇⋅∇pL) η dx,\int_\Omega \nabla_p L \cdot \nabla\eta\,dx = \int_{\partial\Omega} \eta\,(\nabla_p L \cdot n)\,dS - \int_\Omega (\nabla \cdot \nabla_p L)\,\eta\,dx ,

    with nn the outward unit normal. The Euler–Lagrange equation is

    Lu−∇⋅(∇pL)=0in Ω,L_u - \nabla \cdot (\nabla_p L) = 0 \quad \text{in } \Omega ,

    and on a part of the boundary ∂Ω\partial\Omega where uu is free, the natural condition is ∇pL⋅n=0\nabla_p L \cdot n = 0.

    Classic cases #

    1. Shortest path. Arc length: L=1+p2L = \sqrt{1 + p^2}. Lu=0L_u = 0, so the equation says ddxLp=0\frac{d}{dx}L_p = 0, that is, Lp=u′/1+u′2=CL_p = u'/\sqrt{1 + u'^2} = C, a constant. The map p↦p/1+p2p \mapsto p/\sqrt{1 + p^2} is strictly increasing, so u′u' is constant: a straight line. LL is convex in pp (Lpp=(1+p2)−3/2>0L_{pp} = (1 + p^2)^{-3/2} > 0) and does not depend on uu, so the line is the global minimizer.
    2. Dirichlet energy and the Poisson equation. E[u]=∫Ω(12∣∇u∣2−fu) dxE[u] = \int_\Omega \big(\tfrac12|\nabla u|^2 - f u\big)\,dx with u=0u = 0 on ∂Ω\partial\Omega. Here Lu=−fL_u = -f and ∇pL=p=∇u\nabla_p L = p = \nabla u, so the equation is −f−∇⋅∇u=0-f - \nabla \cdot \nabla u = 0:
    −Δu=f.-\Delta u = f .

    LL is convex in (u,p)(u, p), so the solution is the minimizer (Dirichlet's principle). Where no boundary value is imposed, the natural condition is ∂u/∂n=0\partial u/\partial n = 0. In 1-D: −u′′=f-u'' = f.

    Hamilton's principle: stationary, not minimal

    In mechanics the integral runs over time. The action S[q]=∫(12mq˙2−V(q)) dtS[q] = \int \big(\tfrac12 m\dot q^2 - V(q)\big)\,dt has Lq=−V′(q)L_q = -V'(q) and Lq˙=mq˙L_{\dot q} = m\dot q, so the Euler–Lagrange equation is Newton's law mq¨=−V′(q)m\ddot q = -V'(q). For a 1-D elastic medium with density ρ\rho and stiffness μ\mu, S[u]=∬(12ρut2−12μux2) dx dtS[u] = \iint \big(\tfrac12\rho u_t^2 - \tfrac12\mu u_x^2\big)\,dx\,dt gives the wave equation ρutt=μuxx\rho u_{tt} = \mu u_{xx} (the elastic wave equation of seismology is the 3-D version). This LL is not convex in (ut,ux)(u_t, u_x): the motion makes the action stationary, not minimal.

    Energy (Ritz) losses and residual (PINN) losses #

    Take −Δu=f-\Delta u = f in Ω\Omega, u=0u = 0 on ∂Ω\partial\Omega, and a neural network uθu_\theta.

    Ritz (energy) loss. Minimize E[uθ]E[u_\theta] over θ\theta. The Deep Ritz method estimates the integral by Monte Carlo, with new uniform points xj∈Ωx_j \in \Omega at every step:

    E^(θ)=∣Ω∣ 1M∑j=1M(12∣∇uθ(xj)∣2−f(xj) uθ(xj)).\hat E(\theta) = |\Omega|\,\frac1M \sum_{j=1}^M \Big(\tfrac12|\nabla u_\theta(x_j)|^2 - f(x_j)\,u_\theta(x_j)\Big).

    The Dirichlet condition is either a penalty β∫∂Ωuθ2 dS\beta\int_{\partial\Omega} u_\theta^2\,dS, or it is built into the network, uθ(x)=d(x) Nθ(x)u_\theta(x) = d(x)\,N_\theta(x) with a function dd that is 00 on ∂Ω\partial\Omega. The classical Ritz method uses uc=∑kckφku_c = \sum_k c_k \varphi_k with fixed basis functions φk\varphi_k; the finite element method is this method with piecewise polynomials.

    Upper bound. If the trial functions are admissible (essential conditions exact) and the integral is exact, they form a subset of the admissible set. So min⁡θE[uθ]≥min⁡uE[u]\min_\theta E[u_\theta] \ge \min_u E[u]: the Ritz value approaches the true minimum from above. For the Dirichlet energy the gap is exactly an error: E[uθ]−E[u∗]=12∫Ω∣∇(uθ−u∗)∣2 dxE[u_\theta] - E[u^*] = \tfrac12\int_\Omega |\nabla(u_\theta - u^*)|^2\,dx, because δE[u∗;⋅]=0\delta E[u^*; \cdot] = 0 and EE is quadratic.

    PINN (strong-form residual) loss. With collocation points xj∈Ωx_j \in \Omega and boundary points yk∈∂Ωy_k \in \partial\Omega:

    L(θ)=1M∑j=1M(−Δuθ(xj)−f(xj))2+λ 1Mb∑k=1Mbuθ(yk)2.\mathcal L(\theta) = \frac1M \sum_{j=1}^M \big(-\Delta u_\theta(x_j) - f(x_j)\big)^2 + \lambda\,\frac{1}{M_b}\sum_{k=1}^{M_b} u_\theta(y_k)^2 .
    Energy loss (Ritz, Deep Ritz) Residual loss (PINN)
    Applies to PDEs that are Euler–Lagrange equations of a functional (symmetric problems: Poisson, elasticity) any PDE, also non-variational ones (advection, Navier–Stokes)
    Derivatives of uθu_\theta half the order: first derivatives for Poisson full order: second derivatives for Poisson
    Loss at the solution the minimum energy, not 00 00; the residual is an error indicator
    Boundary conditions essential ones must be imposed; natural ones come free every condition needs a loss term (or must be built in)
    Regularity weak solutions; kinks and corner singularities are fine needs a smooth uθu_\theta (strong solution)
    Conditioning like AA: condition number κ\kappa like A⊤AA^\top A: condition number κ2\kappa^2

    Why the residual loss is worse conditioned. Discretize −u′′-u'' on N=100N = 100 interior points to get the matrix A=tridiag(−1,2,−1)/h2A = \mathrm{tridiag}(-1, 2, -1)/h^2. It is symmetric positive definite.

    1. The energy 12U⊤AU−F⊤U\tfrac12 U^\top A U - F^\top U has gradient AU−FAU - F and Hessian AA, with κ(A)≈4.1⋅103\kappa(A) \approx 4.1 \cdot 10^3.
    2. The residual loss 12∥AU−F∥2\tfrac12\|AU - F\|^2 has gradient A⊤(AU−F)A^\top(AU - F) and Hessian A⊤AA^\top A. Its eigenvalues are the squares of those of AA, so κ(A⊤A)=κ(A)2≈1.7⋅107\kappa(A^\top A) = \kappa(A)^2 \approx 1.7 \cdot 10^7.
    3. Plain gradient descent needs a number of steps proportional to κ\kappa (linear algebra lesson 14 shows how CG reduces this to κ\sqrt\kappa).

    Both losses have the same minimizer U∗=A−1FU^* = A^{-1}F. Only the speed differs. For neural networks the picture is less simple, but Krishnapriyan et al. (see "Watch and read") show that the differential operator in the loss makes PINN training hard.

    Interactive figure: loading…

    Move k to the right. Plain gradient descent on the energy loss and on the residual loss of the same discrete Poisson problem, each with the step 1/λmax⁡1/\lambda_{\max} of its Hessian. Both start at U=0U = 0 and have the same solution (dashed). The right chart shows the error against the number of steps. Change NN: κ(A)\kappa(A) grows like N2N^2 and κ(A⊤A)\kappa(A^\top A) like N4N^4.

    Two more facts. A linear problem Au=f\mathcal A u = f is the Euler–Lagrange equation of 12⟨u,Au⟩−⟨f,u⟩\tfrac12\langle u, \mathcal A u\rangle - \langle f, u\rangle only if A\mathcal A is symmetric (self-adjoint) in L2L^2; an advection term b⋅∇ub \cdot \nabla u is not, so such problems have no energy of this form. And a ReLU network is piecewise linear, so Δuθ=0\Delta u_\theta = 0 almost everywhere: a PINN for a second-order PDE needs smooth activations (tanh, SiLU, sine). Deep Ritz needs only first derivatives, but E and Yu still use a smoother activation, max⁡(x3,0)\max(x^3, 0), for accuracy.

    Quick check

    You train a network uθu_\theta for −u′′=f-u'' = f on (0,1)(0, 1) with u(0)=0u(0) = 0 and the free-end condition u′(1)=0u'(1) = 0. Which statement is right?

    The functional derivative and gradient descent #

    Since ∂Jh/∂Ui≈h δJ/δu(xi)\partial J_h/\partial U_i \approx h\,\delta J/\delta u(x_i), a gradient-descent step U←U−τ ∇JhU \leftarrow U - \tau\,\nabla J_h is Ui←Ui−τh δJδu(xi)U_i \leftarrow U_i - \tau h\,\frac{\delta J}{\delta u}(x_i). This is an explicit Euler step of length τh\tau h for the gradient flow

    ut=−δJδu.u_t = -\frac{\delta J}{\delta u} .

    For the Dirichlet energy δJ/δu=−u′′−f\delta J/\delta u = -u'' - f, so this flow is the heat equation ut=u′′+fu_t = u'' + f. Gradient descent smooths uu the way heat spreads. Explicit Euler for the heat equation is stable only for time steps up to h2/2h^2/2, so τh≤h2/2\tau h \le h^2/2, that is τ≤h/2\tau \le h/2. The number of steps to reach a fixed time grows like 1/h21/h^2. This is the conditioning problem again: plain gradient descent on a fine grid is slow.

    Interactive figure: loading…

    Press Play. Each step is one gradient-descent step on the discretized Dirichlet energy, with step size τ=r⋅h/2\tau = r \cdot h/2. The curve becomes smooth: the fast wiggles disappear first, the slow bump last. Now set rr slightly above 11, press Reset and Play: the fastest mode grows at every step. This is the stability limit τ=h/2\tau = h/2.

    Answers to section 1. (1) L=p2L = p^2 gives Lu=0L_u = 0 and Lp=2u′L_p = 2u', so the equation is 2u′′=02u'' = 0. With the boundary values, u=xu = x, and the minimum is ∫011 dx=1\int_0^1 1\,dx = 1. No other admissible uu does better: by the Cauchy–Schwarz inequality, 1=(∫01u′ dx)2≤∫01u′2 dx1 = \big(\int_0^1 u'\,dx\big)^2 \le \int_0^1 u'^2\,dx. (2) Yes: the Dirichlet energy ∫(12u′2−fu) dx\int\big(\tfrac12 u'^2 - f u\big)\,dx. Its Euler–Lagrange equation is −u′′=f-u'' = f, and it needs only u′u'. This is the Ritz loss.

    4. Worked example #

    Minimize J[u]=∫01(12u′2−u) dxJ[u] = \int_0^1 \big(\tfrac12 u'^2 - u\big)\,dx with u(0)=0u(0) = 0 and u(1)u(1) free.

    Step 1: Euler–Lagrange. L=12p2−uL = \tfrac12 p^2 - u, so Lu=−1L_u = -1 and Lp=pL_p = p. The equation Lu−ddxLp=−1−u′′=0L_u - \frac{d}{dx}L_p = -1 - u'' = 0 gives u′′=−1u'' = -1. This is the Poisson equation −u′′=f-u'' = f with f=1f = 1.

    Step 2: boundary conditions. Essential: u(0)=0u(0) = 0. Natural, at the free end: Lp=u′(1)=0L_p = u'(1) = 0.

    Step 3: solve. Integrate twice: u=−x2/2+Ax+Bu = -x^2/2 + Ax + B. From u(0)=0u(0) = 0: B=0B = 0. From u′(1)=−1+A=0u'(1) = -1 + A = 0: A=1A = 1. So u∗(x)=x−x2/2u^*(x) = x - x^2/2.

    Step 4: value. u∗′=1−xu^{*\prime} = 1 - x. The two parts are ∫0112(1−x)2 dx=16\int_0^1 \tfrac12(1 - x)^2\,dx = \tfrac16 and ∫01(x−x2/2) dx=12−16=13\int_0^1 (x - x^2/2)\,dx = \tfrac12 - \tfrac16 = \tfrac13. So J[u∗]=16−13=−16J[u^*] = \tfrac16 - \tfrac13 = -\tfrac16. LL is convex in (u,p)(u, p), so this is the global minimum.

    Step 5: Ritz with one trial function, u=cxu = cx. It satisfies u(0)=0u(0) = 0, but not u′(1)=0u'(1) = 0. J(c)=∫01(12c2−cx) dx=c2/2−c/2J(c) = \int_0^1 (\tfrac12 c^2 - cx)\,dx = c^2/2 - c/2. The minimum is at c=12c = \tfrac12, with J=18−14=−18=−0.125J = \tfrac18 - \tfrac14 = -\tfrac18 = -0.125. This is above −16≈−0.1667-\tfrac16 \approx -0.1667, as the upper bound says. The slope at x=1x = 1 is 12\tfrac12, not 00: the natural condition holds only approximately.

    Step 6: Ritz with two trial functions, u=c1x+c2x2u = c_1 x + c_2 x^2. Then u′=c1+2c2xu' = c_1 + 2c_2 x and

    J(c1,c2)=12c12+c1c2+23c22−12c1−13c2.J(c_1, c_2) = \tfrac12 c_1^2 + c_1 c_2 + \tfrac23 c_2^2 - \tfrac12 c_1 - \tfrac13 c_2 .

    Setting both partial derivatives to zero gives c1+c2=12c_1 + c_2 = \tfrac12 and c1+43c2=13c_1 + \tfrac43 c_2 = \tfrac13. Subtract: 13c2=−16\tfrac13 c_2 = -\tfrac16, so c2=−12c_2 = -\tfrac12 and c1=1c_1 = 1. This is exactly u∗u^*, with J=−16J = -\tfrac16, and u′(1)=0u'(1) = 0 holds although nobody imposed it. The trial space contains the solution, so Ritz finds it.

    Step 7: the PINN loss for the same problem is

    1M∑j(uθ′′(xj)+1)2+λ0 uθ(0)2+λ1 uθ′(1)2.\frac1M\sum_j \big(u_\theta''(x_j) + 1\big)^2 + \lambda_0\,u_\theta(0)^2 + \lambda_1\,u_\theta'(1)^2 .

    The condition u′(1)=0u'(1) = 0 needs its own term and its own weight λ1\lambda_1. The Ritz loss contains it already; only u(0)=0u(0) = 0 must be imposed, for example with uθ(x)=x Nθ(x)u_\theta(x) = x\,N_\theta(x).

    Quick check

    In step 5, Ritz with u=cxu = cx gives J=−0.125J = -0.125, while the true minimum is −1/6≈−0.1667-1/6 \approx -0.1667. What does the gap −0.125−(−1/6)≈0.042-0.125 - (-1/6) \approx 0.042 measure?

    5. In code #

    NumPy and SciPy check the worked example: an Euler–Lagrange residual by finite differences (with the total derivative), the Ritz coefficients, the natural boundary condition on a grid, and the two condition numbers.

    import numpy as np
    from scipy import integrate
    
    # (a) Euler-Lagrange residual L_u - d/dx L_p, with the total derivative d/dx by central differences
    def el_residual(Lu, Lp, u, du, x, h=1e-4):
        dLp = (Lp(x + h, u(x + h), du(x + h)) - Lp(x - h, u(x - h), du(x - h))) / (2 * h)
        return Lu(x, u(x), du(x)) - dLp
    
    Lu = lambda x, u, p: 0.0 * x            # L = x p^2 / 2: L_u = 0, L_p = x p
    Lp = lambda x, u, p: x * p
    xs = np.array([1.5, 2.0, 2.5])
    print(el_residual(Lu, Lp, np.log, lambda x: 1 / x, xs).round(6))           # [0. 0. 0.]: u = log x solves it
    print(el_residual(Lu, Lp, lambda x: x, lambda x: 1 + 0 * x, xs).round(6))  # [-1. -1. -1.]: u = x does not
    
    # (b) worked example: J[u] = int_0^1 (u'^2/2 - u) dx, u(0) = 0, u(1) free
    J = lambda u, du: integrate.quad(lambda x: 0.5 * du(x) ** 2 - u(x), 0, 1)[0]
    print(round(J(lambda x: x - x**2 / 2, lambda x: 1 - x), 6))   # -0.166667
    
    # Ritz with phi_1 = x, phi_2 = x^2: J(c) = c^T K c / 2 - b^T c, K_jk = int phi_j' phi_k', b_j = int phi_j
    phi = [lambda x: x, lambda x: x**2]
    dphi = [lambda x: 1.0, lambda x: 2 * x]
    K = np.array([[integrate.quad(lambda x: dphi[j](x) * dphi[k](x), 0, 1)[0] for k in range(2)] for j in range(2)])
    b = np.array([integrate.quad(phi[j], 0, 1)[0] for j in range(2)])
    c1 = b[0] / K[0, 0]
    print(c1, round(-0.5 * c1 * b[0], 6))     # 0.5 -0.125   (one trial function)
    c = np.linalg.solve(K, b)
    print(c, round(-0.5 * c @ b, 6))         # [ 1.  -0.5] -0.166667   (two: exactly u*)
    
    # (c) discrete energy with a free right end: unknowns U_1..U_N, U_0 = 0, trapezoid weights for f = 1
    N = 100; h = 1 / N
    A = (np.diag(np.full(N, 2.0)) - np.eye(N, k=1) - np.eye(N, k=-1)) / h
    A[-1, -1] = 1 / h                        # the last unknown sits in one cell only
    F = np.full(N, h); F[-1] = h / 2
    U = np.linalg.solve(A, F)                # gradient of J_h = 0
    x = np.arange(1, N + 1) * h
    print(np.abs(U - (x - x**2 / 2)).max().round(6), round((U[-1] - U[-2]) / h, 4))   # 0.0 0.005 (= h/2 -> 0)
    
    # (d) conditioning: energy loss (Hessian A) vs residual loss (Hessian A^T A), N = 100
    n = 100; hh = 1 / (n + 1)
    A1 = (2 * np.eye(n) - np.eye(n, k=1) - np.eye(n, k=-1)) / hh**2
    print(f"{np.linalg.cond(A1):.0f} {np.linalg.cond(A1.T @ A1):.3g}")   # 4134 1.71e+07
    

    In (a), the term −u′-u' in −ddx(xu′)=−u′−xu′′-\frac{d}{dx}(xu') = -u' - xu'' is the LpxL_{px} part of the total derivative. A code that uses only Lppu′′L_{pp}u'' would report a wrong residual. In (c) nobody imposed u′(1)=0u'(1) = 0; the discrete slope at the free end is h/2h/2, which goes to 00 with hh.

    6. Where it shows up #

    • Physics-informed ML. PINNs, Deep Ritz, energy-based losses for elasticity, and weak-form ("variational") PINNs. Weak-form PINNs test the residual against a finite set of functions η\eta after an integration by parts; for a problem with an energy, this is the first variation set to zero. Finite elements use the same weak form with piecewise polynomials. See the ML for science track.
    • Seismic and weather models. The elastic wave equation follows from Hamilton's principle. Full-waveform inversion and 4D-Var minimize a misfit functional over an Earth model or an initial state. Their adjoint equations come from the first variation of a Lagrangian with a multiplier.
    • Regularization of inverse problems and images. Tikhonov smoothing 12∫∣∇m∣2\tfrac12\int|\nabla m|^2 adds −Δm-\Delta m to the Euler–Lagrange equation and smooths everything. Total variation ∫∣∇m∣\int|\nabla m| adds −∇⋅(∇m/∣∇m∣)-\nabla\cdot(\nabla m/|\nabla m|) and keeps sharp edges (faults, fronts).
    • Probability and information theory. Maximum-entropy distributions (the Gaussian for a given mean and variance) come from setting the functional derivative of the entropy −∫plog⁡p-\int p\log p, plus Lagrange multipliers for the constraints, to zero. The mean-field variational inference update qj∝exp⁡(E−j[log⁡p(x,z)])q_j \propto \exp\big(\mathbb E_{-j}[\log p(x, z)]\big) comes from the functional derivative of the ELBO in qjq_j.
    • Gradient flows. Besides the heat equation (section 3), the Fokker–Planck equation of Langevin dynamics is the gradient flow of the KL divergence in the Wasserstein metric (not derived here).

    7. Common mistakes #

    • A partial instead of a total derivative. ddxLp\frac{d}{dx}L_p includes LpxL_{px}, Lpuu′L_{pu}u' and Lppu′′L_{pp}u''. For L=12xu′2L = \tfrac12 x u'^2: ddx(xu′)=u′+xu′′\frac{d}{dx}(xu') = u' + xu'', not xu′′xu''.
    • Wrong variations. η\eta must be zero exactly where uu is prescribed. Imposing both u(b)=βu(b) = \beta and the natural condition Lp(b)=0L_p(b) = 0 asks for too much: the problem usually has no solution.
    • "Euler–Lagrange means minimum." It is necessary only. Check convexity, or the second variation. Actions in mechanics are stationary, not minimal.
    • Reading the Ritz loss as an error. Its optimum is the minimum energy (−16-\tfrac16 in the worked example), not 00. Measure the error against a reference solution, or look at the residual.
    • Boundary conditions in Ritz. Essential conditions must be imposed. A penalty weight that is too small leaves them violated; one that is too large makes the loss ill-conditioned. Natural conditions need no term.
    • Fixed quadrature points. The network can make the integrand small at those points only. Resample the points at every step (as in Deep Ritz) or use enough of them.
    • ReLU networks in a PINN for a second-order PDE. Δuθ=0\Delta u_\theta = 0 almost everywhere.
    • Forgetting the 1/h1/h. ∂Jh/∂Ui≈h δJ/δu(xi)\partial J_h/\partial U_i \approx h\,\delta J/\delta u(x_i). Comparisons with the functional derivative, step sizes and convergence tests must use (1/h) ∂Jh/∂U(1/h)\,\partial J_h/\partial U.

    8. Check yourself #

    1. Give the Euler–Lagrange equation for L=12u′2+12k2u2−f(x) uL = \tfrac12 u'^2 + \tfrac12 k^2 u^2 - f(x)\,u.
      AnswerLu=k2u−fL_u = k^2 u - f and Lp=u′L_p = u', so k2u−f−u′′=0k^2 u - f - u'' = 0, that is, −u′′+k2u=f-u'' + k^2 u = f (a screened Poisson equation).
    2. Minimize J[u]=∫01(u′2+u2) dxJ[u] = \int_0^1 (u'^2 + u^2)\,dx with u(0)=0u(0) = 0 and u(1)=1u(1) = 1. Give the minimizer and JJ, and compare with u=xu = x.
      AnswerLu=2uL_u = 2u and Lp=2u′L_p = 2u', so 2u−2u′′=02u - 2u'' = 0, that is, u′′=uu'' = u. With the boundary values, u=sinh⁡x/sinh⁡1u = \sinh x/\sinh 1. Integration by parts with u′′=uu'' = u gives JJ =∫(u′2+uu′′) dx= \int(u'^2 + uu'')\,dx =[uu′]01= [uu']_0^1 =u(1) u′(1)= u(1)\,u'(1) =cosh⁡1/sinh⁡1= \cosh 1/\sinh 1 =coth⁡1= \coth 1 ≈1.3130\approx 1.3130. For u=xu = x: J=1+13≈1.3333J = 1 + \tfrac13 \approx 1.3333, which is larger, as it must be (LL is convex).
    3. L=12xu′2L = \tfrac12 x u'^2 on [1,e][1, e] with u(1)=0u(1) = 0 and u(e)=1u(e) = 1. Give the Euler–Lagrange equation and its solution.
      AnswerLu=0L_u = 0 and Lp=xu′L_p = xu', so −ddx(xu′)=0-\frac{d}{dx}(xu') = 0, that is, −u′−xu′′=0-u' - xu'' = 0. Then xu′=Cxu' = C, u=Clog⁡x+Du = C\log x + D, and the boundary values give u=log⁡xu = \log x.
    4. J[u]=∫01(12u′2−fu) dxJ[u] = \int_0^1 \big(\tfrac12 u'^2 - f u\big)\,dx with no boundary conditions at all. Which conditions does a minimizer satisfy, and what must ff satisfy for a minimizer to exist?
      Answer−u′′=f-u'' = f with the natural conditions u′(0)=u′(1)=0u'(0) = u'(1) = 0 at both ends. Integrating the equation, ∫01f dx=−[u′]01=0\int_0^1 f\,dx = -[u']_0^1 = 0. If ∫f≠0\int f \ne 0, the constants u=cu = c give J=−c∫fJ = -c\int f, which goes to −∞-\infty for a suitable sign of cc, so there is no minimizer. If ∫f=0\int f = 0, the minimizer is unique up to an added constant.
    5. The 1-D Laplacian matrix on a grid has κ(A)≈4.1⋅103\kappa(A) \approx 4.1 \cdot 10^3. Plain gradient descent on the energy loss needs about kk steps. About how many does it need on the residual loss 12∥AU−F∥2\tfrac12\|AU - F\|^2, and why?
      AnswerAbout κ(A)\kappa(A) times more, so roughly 4⋅103 k4 \cdot 10^3\,k. The residual loss has Hessian A⊤AA^\top A with κ(A⊤A)=κ(A)2≈1.7⋅107\kappa(A^\top A) = \kappa(A)^2 \approx 1.7 \cdot 10^7, and the number of gradient-descent steps grows like the condition number.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is a functional? Give one example.

    2. Define the first variation δJ[u;η]\delta J[u; \eta].

    3. State the fundamental lemma of the calculus of variations.

    4. Write the Euler–Lagrange equation for J[u]=∫abL(x,u,u′) dxJ[u] = \int_a^b L(x, u, u')\,dx.

    5. What condition does a minimizer satisfy at a free end x=bx = b?

    6. Which PDE is the Euler–Lagrange equation of the Dirichlet energy ∫Ω(12∣∇u∣2−fu) dx\int_\Omega (\tfrac12|\nabla u|^2 - fu)\,dx?

    7. On a grid with spacing hh, how is ∂Jh/∂Ui\partial J_h/\partial U_i related to δJ/δu\delta J/\delta u?

    8. For −u′′=f-u'' = f, which derivatives of the network does a Ritz loss need, and which does a PINN loss need?

    9. Why is the residual loss 12∥AU−F∥2\tfrac12\|AU - F\|^2 worse conditioned than the energy 12U⊤AU−F⊤U\tfrac12U^\top AU - F^\top U?

    10. Gradient descent on the discretized Dirichlet energy is a time step of which equation?

    Open the review →

    9. Interview angle #

    • "Derive the Euler–Lagrange equation." Take the first variation, integrate by parts with η(a)=η(b)=0\eta(a) = \eta(b) = 0, and apply the fundamental lemma. Add the natural boundary condition at a free end.
    • "Prove that the shortest curve between two points is a straight line." Lp=u′/1+u′2L_p = u'/\sqrt{1 + u'^2} is constant, so u′u' is constant; convexity of LL makes the line the global minimum.
    • "You must solve a Poisson equation with a neural network. Which loss do you use?" Ritz: first derivatives only, Neumann conditions for free, but it needs an energy and imposed Dirichlet conditions. PINN: any PDE, but second derivatives, a term for every condition, and worse conditioning.
    • "Why do PINNs often fail to train?" The differential operator in the loss makes it ill-conditioned, the loss terms need weights, and networks fit low frequencies first. Remedies include curriculum training, causal (time-ordered) weighting, and boundary conditions built into the network.
    • "What is the functional derivative of ∫plog⁡p dx\int p\log p\,dx? Find the maximum-entropy density with a given mean and variance." log⁡p+1\log p + 1. With Lagrange multipliers for ∫p=1\int p = 1, the mean and the variance, log⁡p\log p is a quadratic in xx: the density is a Gaussian.

    10. Practice #

    The notebook for this lesson runs in Colab. It has four exercises, each with a check cell and a folded solution:

    1. Write euler_lagrange_residual with a finite-difference total derivative and use it to test candidate solutions, including L=12xu′2L = \tfrac12 x u'^2.
    2. Write discrete_functional_gradient for the Dirichlet energy on a grid and compare (1/h) ∂Jh/∂U(1/h)\,\partial J_h/\partial U with δJ/δu\delta J/\delta u for several NN.
    3. Solve the 1-D Poisson problem by minimizing the discrete energy and the discrete residual, with gradient descent and with conjugate gradients, and count the iterations.
    4. Ritz with polynomial trial functions x,x2,…,xKx, x^2, \dots, x^K for a problem with a free end: watch the natural condition u′(1)=0u'(1) = 0 appear without being imposed.

    11. Watch and read #

    Functionals, the variation u+ϵηu + \epsilon\eta, and a step-by-step derivation of the Euler–Lagrange equation with integration by parts.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A visual introduction: functionals, variations as small bumps, and the shortest path between two points.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The Ritz method on a beam: pick trial functions, write the potential energy, and minimize over the coefficients.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    How a PINN puts the PDE residual and the boundary conditions into the loss, and where it struggles.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    • Peter Olver, The Calculus of Variations, free lecture notes: §3 (the Euler–Lagrange equation; the fundamental lemma is Lemmas 3.3–3.4), §4 (boundary conditions, including natural boundary conditions), §5 (the second variation), §6 (several variables; Example 6.1 is the Dirichlet integral).
    • E and Yu, The Deep Ritz Method: §2 (trial functions and Monte Carlo quadrature inside SGD) and §3.1 (the Poisson equation with a boundary penalty).
    • Raissi, Perdikaris and Karniadakis, Physics Informed Deep Learning (Part I): the residual (PINN) loss with collocation points.
    • Krishnapriyan, Gholami, Zhe, Kirby and Mahoney, Characterizing possible failure modes in physics-informed neural networks (NeurIPS 2021): §3 (failures for convection and reaction-diffusion), §4 (the PDE term makes the loss landscape hard to optimize), §5 (curriculum regularization).