In a boundary value problem (BVP) the conditions are split between the two ends of an interval (for a PDE, they are given on the boundary of the domain), so the solution at every point depends on the data at both ends and has to be computed all at once.
The Heat Equation¶
The Heat Equation is a second-order PDE obeying
where is the Laplacian operator
This equation is in a steady state if (i.e. the solution is not changing with time).
We’ll consider the steady state of the heat equation on a 1-dimensional domain , where we have the ends of the domain set to fixed temperatures. In this case, we can write the solution as a boundary value problem for a second-order ODE:
You might think of this as describing the temperature of a metal bar which is placed between two objects of differing temperatures.
import time
import numpy as np
import scipy.linalg as la
import scipy.optimize as opt
import scipy.sparse as sparse
import scipy.sparse.linalg as spla
from scipy.integrate import solve_bvp, solve_ivp
import matplotlib.pyplot as plt
import sympy as sym
from sympy.solvers import odeWe’ll introduce the variable to obtain a system of first-order ODEs:
with the same boundary conditions. The variable y = [u, p] will be a 2-vector containing the state.
We’ll use boundary conditions and
Finally, we use solve_bvp from scipy.integrate to solve the boundary value problem. Its arguments are:
f(x, y), the right-hand side . It is called on all the mesh points at once, withxof shape(m,)andyof shape(2, m)(one column per point), and it must return an array of the same shape asy.np.vstackstacks rows into such an array, as in the example below.bc(ya, yb), which receives the values ofyat the two ends and returns the residuals of the boundary conditions, which are zero when the conditions hold. There is one condition per component ofy, two here.the initial mesh
x, and an initial guessy0foryon it, of shape(2, m).
np.vstack((np.zeros(3), [3,4,5]))a = 5
b = 1
def f(x, y):
"right hand side of ODE"
return np.vstack([y[1,:], np.zeros(y.shape[1])]) # du/dx = p, dp/dx = 0
def bc(ya, yb): # ya = y[:,0], yb = y[:,-1]
"boundary condition residual"
return np.array([ya[0] - a, yb[0] - b])
n = 100 # number of points
x = np.linspace(0,1,n)
# y0 = np.zeros((2,n))
y0 = np.random.randn(2,n)
# solve bvp
sol = solve_bvp(f, bc, x, y0)
print(sol.message)we can plot the solution value
plt.plot(sol.x, sol.y[0,:])
plt.xlabel('x')
plt.ylabel('u')
plt.show()We see the solution is a linear function from (0,5) to (1,1). You can check that such a linear function solves the BVP mathematically.
The initial guess y0 was random noise. The problem is linear, so Newton’s method inside solve_bvp finds the solution in one step from any initial guess; for nonlinear problems the guess matters, as we will see.
A heat source¶
We also provide a non-zero right hand side. If heat is produced inside the bar at a rate per unit length, the heat equation becomes , and its steady state satisfies
We heat the middle of the bar, with for and elsewhere, and hold both ends at temperature 0. We round off the edges of the source with over a width of about (see below for why), and this time we start from a coarse mesh of 11 points.
w = 0.01 # width of the edges of the source
def f(x, y):
"right hand side of ODE"
src = 0.5 * (np.tanh((x - 0.4) / w) - np.tanh((x - 0.6) / w)) # about 1 on (0.4, 0.6), 0 outside
return np.vstack([y[1,:], -src])
def bc(ya, yb):
"boundary condition residual"
return np.array([ya[0], yb[0]])
n = 11 # number of points in the initial mesh
x = np.linspace(0,1,n)
y0 = np.zeros((2,n))
# solve bvp
sol = solve_bvp(f, bc, x, y0)
print(f"{sol.message} The final mesh has {len(sol.x)} points.")
xs = np.linspace(0, 1, 500)
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
ax[0].plot(xs, sol.sol(xs)[0])
ax[0].plot(sol.x, sol.y[0], 'k.', label='mesh points')
ax[0].set_xlabel('$x$')
ax[0].set_ylabel('temperature $u$')
ax[0].legend()
ax[1].plot(xs, sol.sol(xs)[1])
ax[1].plot(sol.x, sol.y[1], 'k.')
ax[1].set_xlabel('$x$')
ax[1].set_ylabel("$u'$")
plt.show()The temperature is linear where there is no source and curves downward where the bar is heated. By Fourier’s law the heat flux is , and drops by 0.2 across the source, which is the total heat produced in ; half of it flows out through each end.
Finite Differences¶
We can also replace derivatives by finite differences, as in Differentiation. Take interior points , , with spacing , so that and are the ends of the interval. The second difference
has error , which you can check by adding the Taylor series of and . Imposing at each interior point gives linear equations for the unknowns . The boundary values and are known, so they move to the right-hand side of the first and last equations:
The matrix is tridiagonal, so we store it as a sparse matrix, and a sparse direct solve (see Sparse Linear Algebra) takes operations.
def second_difference(N, h):
"""
second difference matrix for N interior points with spacing h
"""
return sparse.diags([1.0, -2.0, 1.0], [-1, 0, 1], shape=(N, N), format='csc') / h**2
def fd_solve(f, a, b, N):
"""
solve u'' = f(x) on [0, 1] with u(0) = a and u(1) = b, using N interior points
returns the grid x and the solution u, both including the end points
"""
h = 1 / (N + 1)
x = np.linspace(0, 1, N + 2)
rhs = f(x[1:-1]).copy()
rhs[0] -= a / h**2 # the boundary values move to the right-hand side
rhs[-1] -= b / h**2
u = np.empty(N + 2)
u[0], u[-1] = a, b
u[1:-1] = spla.spsolve(second_difference(N, h), rhs)
return x, u
second_difference(5, 1).toarray()To check the method we need a problem with a known solution. With the boundary values and from the first example and , the solution is . We measure the largest error on the grid for a sequence of grid sizes, as in Accuracy, Stability, and Stiffness.
f = lambda x: -np.pi**2 * np.sin(np.pi * x)
exact = lambda x: 5 - 4 * x + np.sin(np.pi * x)
Ns = 2**np.arange(3, 18) - 1 # 7, 15, ..., 131071 interior points
errs = []
for N in Ns:
x, u = fd_solve(f, 5, 1, N)
errs.append(np.max(np.abs(u - exact(x))))
hs = 1 / (Ns + 1)
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
x, u = fd_solve(f, 5, 1, 7)
ax[0].plot(xs, exact(xs), 'k--', label='exact')
ax[0].plot(x, u, 'o', label='finite differences, $N = 7$')
ax[0].set_xlabel('$x$')
ax[0].set_ylabel('$u$')
ax[0].legend()
ax[1].loglog(hs, errs, 'o-', label='max error')
ax[1].loglog(hs, hs**2, 'k--', label='$h^2$')
ax[1].set_xlabel('$h$')
ax[1].legend()
plt.show()The error falls like down to about 10-9 at , below which rounding errors take over, as for the difference quotients in Differentiation.
The same discretization turns the Bratu problem into the nonlinear equations
which we can solve with Newton’s method. We do this for the two-dimensional version of the problem at the end of this section.
The Wave Equation¶
The Wave Equation is another second order PDE obeying
One way to solve the wave equation is to use separation of variables. This gives solutions of the form
where satisfies the Helmholtz equation
In other words, is an eigenvector of the Laplacian operator with eigenvalue . The time dependent portion of the solution is simply a sinusoidal oscillation.
In a bounded domain, there is a discrete set of eigenvalues for the Laplacian. We’ll use the construction , where is the forward difference matrix. We take interior points , , with , and hold the values at the two ends at zero, (a Dirichlet boundary condition, like a string with fixed ends). Then maps the interior values to the differences , .
import scipy.sparse as sparse
# create matrix A to apply forward difference scheme
def forward_diff_matrix(n):
data = []
i = []
j = []
for k in range(n - 1):
i.append(k)
j.append(k)
data.append(-1)
i.append(k)
j.append(k+1)
data.append(1)
# incidence matrix of the 1-d mesh
return sparse.coo_matrix((data, (i,j)), shape=(n-1, n)).tocsr()
def Laplacian(n):
"""
Create Laplacian on the n interior nodes of a 1-dimensional grid with n + 2 nodes,
with the values at the two boundary nodes set to 0
"""
B = forward_diff_matrix(n + 2)[:, 1:-1] # the boundary values are 0, so their columns drop out
return -B.T @ Bn = 100
h = 1 / (n + 1)
x = np.arange(1, n + 1) * h # interior points; the values at x = 0 and x = 1 are 0
L = Laplacian(n)
L[:4,:4].todense()Each row of applied to gives the second difference . In the first and last rows one of the two neighbors is a boundary value, which is zero and drops out, so every diagonal entry is -2, and approximates with . It is the same matrix as second_difference(n, h) from the finite difference section, apart from the factor .
We can use the Gershgorin disk theorem to bound the eigenvalues in the range ( is symmetric, so its eigenvalues are real, and each disk is centered at the diagonal entry -2, with radius at most 2, the sum of the off-diagonal entries in that row), or plot them experimentally:
evals, V = la.eigh(L.todense())
k = np.arange(1, n + 1)
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
ax[0].plot(evals, '.')
ax[0].axhline(-4, color='k', lw=0.5)
ax[0].axhline(0, color='k', lw=0.5)
ax[0].set_xlabel('index')
ax[0].set_title('eigenvalues of $L$ (lines: Gershgorin bounds)')
ax[1].plot(k, -evals[::-1] / h**2, '.', label=r'$-\lambda_k / h^2$')
ax[1].plot(k, (k * np.pi)**2, 'k--', label=r'$(k\pi)^2$')
ax[1].set_xlabel('$k$')
ax[1].legend()
plt.show()For small the eigenvalues of , divided by , are close to , the eigenvalues of with , but for large they are too small in magnitude. The second difference applied to gives , which is close to only when is small, i.e., when there are many grid points per wavelength (compare the modified wavenumber in Spectral Methods).
Let’s plot the eigenvectors with the 4 smallest-magnitude eigenvalues:
xb = np.concatenate([[0], x, [1]]) # the grid including the two boundary points
for k in range(1, 5):
v = V[:, -k] # the eigenvalues are sorted, so the one closest to 0 comes last
v = v * np.sign(v[0]) # eigenvectors are only determined up to sign
plt.plot(xb, np.concatenate([[0], v, [0]]), label=f'$k = {k}$')
ref = np.sin(k * np.pi * xb)
plt.plot(xb, ref / np.linalg.norm(ref), 'k:')
plt.legend()
plt.show()The eigenvectors are of the form for (dotted lines, scaled to unit length), and they vanish at both ends. All the eigenvalues are negative, with for small , so each eigenvector gives a solution of the wave equation that oscillates in time without changing its shape, a standing wave of a string with fixed ends.
Now, let’s say we want to solve the boundary value problem
on , which describes a string whose two ends are shaken with amplitudes and at frequency . Again, we can use solve_bvp
a = 5
b = 1
omega = 10
def f(x, y):
"right hand side of ODE"
return np.vstack([y[1,:], -omega**2 * y[0,:]])
def bc(ya, yb):
"boundary condition residual"
return np.array([ya[0] - a, yb[0] - b])
n = 100 # number of points
x = np.linspace(0,1,n)
y0 = np.zeros((2,n))
# solve bvp
sol = solve_bvp(f, bc, x, y0)def helmholtz_exact(x, omega, a=5, b=1):
"""
solution of v'' = -omega^2 v with v(0) = a and v(1) = b
"""
return a * np.cos(omega * x) + (b - a * np.cos(omega)) / np.sin(omega) * np.sin(omega * x)
plt.plot(sol.x, sol.y[0,:], label='solve_bvp')
plt.plot(sol.x, helmholtz_exact(sol.x, omega), 'k--', label='exact')
plt.xlabel('x')
plt.ylabel('v')
plt.legend()
plt.show()The general solution of is . The condition at gives , and the condition at gives
which is the dashed line above. This breaks down when , i.e., . Then every solution with has , so the BVP has no solution unless , and infinitely many if it does. These are the natural frequencies of the string, the frequencies of the standing waves that we computed above, for which is an eigenvalue of with zero boundary values. As approaches one of them, the solution grows like , which is resonance.
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
for freq in [2.0, 2.6, 2.9, 3.05]:
ax[0].plot(xs, helmholtz_exact(xs, freq), label=fr'$\omega = {freq}$')
ax[0].set_xlabel('$x$')
ax[0].set_ylabel('$v$')
ax[0].legend()
omegas = np.linspace(0.5, 10, 2000)
ax[1].semilogy(omegas, [np.abs(helmholtz_exact(xs, freq)).max() for freq in omegas])
for k in range(1, 4):
ax[1].axvline(k * np.pi, color='k', ls=':', lw=1)
ax[1].set_xlabel(r'$\omega$')
ax[1].set_ylabel(r'$\max_x |v(x)|$')
ax[1].set_title(r'resonance at $\omega = \pi, 2\pi, 3\pi$ (dotted)')
plt.show()solve_bvp does not detect the resonance. At there is no solution, since , but the discretized problem is only nearly singular, so solve_bvp reports success and returns a solution of size about 109:
omega = np.pi
sol = solve_bvp(f, bc, x, y0)
print(sol.message)
print(f"largest |v| = {np.abs(sol.y[0]).max():.1e}")Boundary Value Problems in SymPy¶
SymPy offers functionality that can be used to solve BVPs in its sym.solvers.ode.dsolve function
import sympy as sym
from sympy.solvers import odex = sym.symbols('x') # symbol
u = sym.Function('u') # symbolic function
eqn = u(x).diff(x).diff(x) # = 0
eqnode.classify_ode(eqn)ode.dsolve(eqn, hint='nth_linear_constant_coeff_homogeneous')in order to pass in boundary conditions, you can use the ics parameter
f = ode.dsolve(eqn, hint='nth_linear_constant_coeff_homogeneous', ics={u(0): 5, u(1): 1})
fsym.plot(f.rhs, (x, 0, 1));Let’s try the Helmholtz equation now. We declare positive, so that SymPy writes the solution with sines and cosines rather than complex exponentials.
omega = sym.Symbol('omega', positive=True)
eqn = u(x).diff(x).diff(x) + omega**2*u(x) # = 0
eqnode.classify_ode(eqn)ode.dsolve(eqn, hint='nth_linear_constant_coeff_homogeneous')We see that the solution to the Helmholtz equation consists of sinusoidal waves. Let’s try putting in some boundary conditions
f = ode.dsolve(eqn, hint='nth_linear_constant_coeff_homogeneous', ics={u(0): 5, u(1): 1})
fAs we found above, the coefficient of has in the denominator, so the formula breaks down at the resonant frequencies . For it gives the solution we computed with solve_bvp:
sym.plot(f.rhs.subs(omega, 10), (x, 0, 1));Solving BVPs using Optimization¶
You might also consider finding numerical solutions to BVPs using scipy.optimize. Let’s say we have a non-linear equation with boundary conditions
where is the boundary of the domain. We can seek to solve the optimization problem
whose minimum value is zero exactly when solves the BVP.
We’ll use the Bratu nonlinearity on the unit square , which describes the steady temperature of a square plate in which a chemical reaction releases heat at a rate that grows exponentially with temperature, and its edges held at temperature 0. This modifies the example from the SciPy Cookbook, which uses .
With interior points in each direction, at and with , the five-point Laplacian
gives one equation for each of the interior values . The boundary values are zero, so they drop out of these equations, and the constraint holds automatically. If we order the unknowns as np.reshape does for an array, the matrix of the discrete Laplacian is , where is the second_difference matrix from above, is the identity, and is the Kronecker product (sparse.kron, see Differentiation).
import scipy.optimize as opt
def laplacian_2d(n, h):
"""
five-point Laplacian on the n x n interior points of a square grid with spacing h
"""
D = second_difference(n, h)
I = sparse.identity(n)
return (sparse.kron(D, I) + sparse.kron(I, D)).tocsr()
plt.figure(figsize=(4, 4))
plt.spy(laplacian_2d(4, 1), markersize=5)
plt.title(r'$L$ for $n = 4$')
plt.show()Each diagonal block couples a point to its neighbors in the same row of the grid, and the identity blocks next to it couple the point to its neighbors in the rows above and below.
The residual of the discretized equations is , with the exponential applied entrywise, and its Jacobian is
a sparse matrix with the same sparsity pattern as . We pass both to least_squares, starting from , with .
n = 99 # interior points in each direction
h = 1 / (n + 1)
L = laplacian_2d(n, h)
lam = 6
def residual(u):
"residual of the discretized BVP"
return L @ u + lam * np.exp(u)
def jac(u):
"Jacobian of the residual, a sparse matrix"
return L + sparse.diags(lam * np.exp(u))
start = time.perf_counter()
res = opt.least_squares(residual, np.zeros(n**2), jac=jac, verbose=1)
print(f"largest residual: {np.abs(res.fun).max():.1e}, time {time.perf_counter() - start:.2f} s")xsol = np.reshape(res.x, (n, n))
plt.imshow(xsol, extent=[0, 1, 0, 1], origin='lower')
plt.colorbar()
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title(r'steady temperature $u$ for $\lambda = 6$')
plt.show()The final cost is about , so least_squares has found a solution of the equations. If the cost stays well above zero, least_squares has stopped at a local minimum of that does not solve the equations, so this is worth checking every time.
The plate is hottest in the center, where . Note that is larger than the beyond which the slab has no steady state; the plate loses heat through all four edges, so it can balance a stronger reaction.
Since there are as many equations as unknowns, we can also apply Newton’s method from Root Finding directly. Each step solves the sparse linear system with spsolve and updates .
start = time.perf_counter()
u = np.zeros(n**2)
rs = []
for k in range(20):
r = residual(u)
rs.append(np.abs(r).max())
if rs[-1] < 1e-10:
break
u = u - spla.spsolve(jac(u), r)
print(f"{len(rs) - 1} Newton steps, time {time.perf_counter() - start:.2f} s")
print(f"largest difference from the least_squares solution: {np.abs(u - res.x).max():.1e}")
plt.figure(figsize=(6, 4))
plt.semilogy(rs, 'o-')
plt.xlabel('Newton step')
plt.ylabel('largest residual')
plt.show()u = np.reshape(u, (n,n))
plt.imshow(u, extent=[0, 1, 0, 1], origin='lower')
plt.colorbar()
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title(r'steady temperature $u$ for $\lambda = 6$, newtons method')
plt.show()