Implementation

Implementation

Author: Jørgen S. Dokken

Test problem

To solve a test problem, we need to choose the right hand side \(f\) and the coefficient \(q(u)\) and the boundary \(u_D\). Previously, we have worked with manufactured solutions that can be reproduced without approximation errors. This is more difficult in non-linear porblems, and the algebra is more tedious. Howeve, we will utilize UFLs differentiation capabilities to obtain a manufactured solution.

For this problem, we will choose \(q(u) = 1 + u^2\) and define a two dimensional manufactured solution that is linear in \(x\) and \(y\):

import ufl
from mpi4py import MPI

from dolfinx.fem import (dirichletbc, Function, FunctionSpace, NonlinearProblem,
                         assemble_scalar, form, locate_dofs_topological)
from dolfinx.log import set_log_level, LogLevel
from dolfinx.mesh import create_unit_square, locate_entities_boundary
from dolfinx.nls import NewtonSolver

def q(u):
    return 1 + u**2

mesh = create_unit_square(MPI.COMM_WORLD, 10, 10)
x = ufl.SpatialCoordinate(mesh)
u_ufl = 1 + x[0] + 2*x[1]
f = - ufl.div(q(u_ufl)*ufl.grad(u_ufl))

Note that since x is a 2D vector, the first component (index 0) resemble \(x\), while the second component (index 1) resemble \(y\). The resulting function f can be directly used in variational formulations in DOLFINx.

As we now have defined our source term and exact solution, we can create the appropriate function space and boundary conditions. Note that as we have already defined the exact solution, we only have to convert it to a python function that can be evaluated in the interpolation function. We do this by employing the Python eval and lambda-functions.

from petsc4py import PETSc
import numpy
V = FunctionSpace(mesh, ("CG", 1))
u_exact = lambda x: eval(str(u_ufl))
u_D = Function(V)
u_D.interpolate(u_exact)
u_D.x.scatter_forward()
fdim = mesh.topology.dim - 1
boundary_facets = locate_entities_boundary(mesh, fdim, lambda x: numpy.full(x.shape[1], True, dtype=bool))
bc = dirichletbc(u_D, locate_dofs_topological(V, fdim, boundary_facets))

We are now ready to define the variational formulation. Note that as the problem is non-linear, we have replace the TrialFunction with a Function, which serves as the unknown of our problem.

uh = Function(V)
v = ufl.TestFunction(V)
F = q(uh)*ufl.dot(ufl.grad(uh), ufl.grad(v))*ufl.dx - f*v*ufl.dx

The next step is to define the non-linear problem. As it is non-linear we will use Newtons method. Newton’s method requires methods for evaluating the residual F (including application of boundary conditions), as well as a method for computing the Jacobian matrix. DOLFINx provides the function NonlinearProblem that implements these methods. In addition to the boundary conditions, you can supply the variational form for the Jacobian (computed if not supplied), and form and jit parameters, see the JIT parameters section.

problem = NonlinearProblem(F, uh, bcs=[bc])

Next, we use the dolfinx Newton solver. We can set the convergence criterions for the solver by changing the absolute tolerance (atol), relative tolerance (rtol) or the convergence criterion (residual or incremental).

solver = NewtonSolver(MPI.COMM_WORLD, problem)
solver.convergence_criterion = "incremental"
solver.rtol = 1e-6
solver.report = True

We can modify the linear solver in each Newton iteration by accessing the underlying PETSc object.

ksp = solver.krylov_solver
opts = PETSc.Options()
option_prefix = ksp.getOptionsPrefix()
opts[f"{option_prefix}ksp_type"] = "cg"
opts[f"{option_prefix}pc_type"] = "gamg"
opts[f"{option_prefix}pc_factor_mat_solver_type"] = "mumps"
ksp.setFromOptions()

We are now ready to solve the non-linear problem. We assert that the solver has converged and print the number of iterations.

set_log_level(LogLevel.INFO)
n, converged = solver.solve(uh)
uh.x.scatter_forward()
assert(converged)
print(f"Number of interations: {n:d}")
Number of interations: 8
2022-01-17 08:24:29.814 (   0.142s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.816 (   0.144s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.818 (   0.146s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 2: r (abs) = 20.3794 (tol = 1e-10) r (rel) = 0.922544(tol = 1e-06)
2022-01-17 08:24:29.819 (   0.147s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.820 (   0.148s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 3: r (abs) = 6.95285 (tol = 1e-10) r (rel) = 0.314745(tol = 1e-06)
2022-01-17 08:24:29.820 (   0.148s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.822 (   0.150s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 4: r (abs) = 2.93575 (tol = 1e-10) r (rel) = 0.132897(tol = 1e-06)
2022-01-17 08:24:29.822 (   0.150s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.823 (   0.151s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 5: r (abs) = 0.700593 (tol = 1e-10) r (rel) = 0.0317148(tol = 1e-06)
2022-01-17 08:24:29.823 (   0.152s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.826 (   0.154s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 6: r (abs) = 0.0490796 (tol = 1e-10) r (rel) = 0.00222176(tol = 1e-06)
2022-01-17 08:24:29.826 (   0.154s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve system.
2022-01-17 08:24:29.827 (   0.155s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 7: r (abs) = 0.000299464 (tol = 1e-10) r (rel) = 1.35563e-05(tol = 1e-06)
2022-01-17 08:24:29.827 (   0.156s) [main            ]              petsc.cpp:769   INFO| PETSc Krylov solver starting to solve
 system.
2022-01-17 08:24:29.829 (   0.158s) [main            ]       NewtonSolver.cpp:34    INFO| Newton iteration 8: r (abs) = 1.52969e-08 (tol = 1e-10) r (rel) = 6.92466e-10(tol = 1e-06)
2022-01-17 08:24:29.829 (   0.158s) [main            ]       NewtonSolver.cpp:250   INFO| Newton solver finished in 8 iterations and 45 linear solver iterations.

We observe that the solver converges after \(8\) iterations. If we think of the problem in terms of finite differences on a uniform mesh, \(\mathcal{P}_1\) elements mimic standard second-order finite differences, which compute the derivative of a linear or quadratic funtion exactly. Here \(\nabla u\) is a constant vector, which is multiplied by \(1+u^2\), which is a second order polynomial in \(x\) and \(y\), which the finite difference operator would compute exactly. We can therefore, even with \(\mathcal{P}_1\) elements, expect the manufactured solution to be reproduced by the numerical method. However, if we had chosen a nonlinearity, such as \(1+u^4\), this would not be the case, and we would need to verify convergence rates.

# Compute L2 error and error at nodes
V_ex = FunctionSpace(mesh, ("CG", 2))
u_ex = Function(V_ex)
u_ex.interpolate(u_exact)
error_local = assemble_scalar(form((uh - u_ex)**2 * ufl.dx))
error_L2 = numpy.sqrt(mesh.comm.allreduce(error_local, op=MPI.SUM))
if mesh.comm.rank == 0:
    print(f"L2-error: {error_L2:.2e}")

# Compute values at mesh vertices
u_vertex_values = uh.compute_point_values()
u_ex_vertex_values = u_ex.compute_point_values()
error_max = mesh.comm.allreduce(numpy.max(numpy.abs(u_vertex_values - u_ex_vertex_values)), op=MPI.MAX)
if mesh.comm.rank == 0:
    print(f"Error_max: {error_max:.2e}")
L2-error: 1.51e-15
Error_max: 5.55e-15
2022-01-17 08:24:29.846 (   0.174s) [main            ]topologycomputation.cpp:616   INFO| Computing mesh entities of dimension 0
2022-01-17 08:24:29.846 (   0.174s) [main            ]topologycomputation.cpp:616   INFO| Computing mesh entities of dimension 1