Time stepping#
This tutorial illustrates how to:
Write a time derivative in UFL with the placeholder
u.dot, and withAccumulationStep in time with a
Simulation, with a backward differentiation formula or a theta scheme: backward Euler, Crank-Nicolson or forward EulerWrite output and metadata, and adapt the time step
The problem#
The heat equation on the unit square \(\Omega\),
has the exact solution
Quadratic Lagrange elements represent the solution exactly in space, so all of the error comes from the time stepping. The modules used are imported:
import json
import pathlib
import tempfile
from mpi4py import MPI
import dolfinx.mesh
import numpy as np
import ufl
from sumfem import discrete, solvers, symbolic
from sumfem.models import Accumulation, Diffusion, Source
from sumfem.post_processing import error
Time derivatives#
The time derivative of a field u is u.dot, a placeholder that a
time-stepping scheme replaces by differences of the solution at the
current and previous steps. The time-derivative term of the weak form of
(3), \((\partial u / \partial t, v)\), is written in UFL
with it like any other term, here as a component, see
A model as a component:
domain = symbolic.Domain("square", "triangle")
u = symbolic.Field("u", domain, ("Lagrange", 2))
class TimeDerivative(symbolic.Residual):
def residual(self) -> ufl.Form:
return ufl.inner(u.dot, u.v) * domain.dx()
Accumulation is this term in
general, for any field, with a weight such as a heat capacity or a
porosity, and on the cells of given markers. Without them it is the same
form:
assert (
TimeDerivative("dudt").form.signature() == Accumulation("dudt", u).form.signature()
)
A Clock holds the time clock.t and the
step clock.dt as parameters, so models can use them in expressions, e.g.
a source or a boundary value that changes in time. UFL derives the source
of (4) from the exact solution: with the time as a
variable, diff
differentiates with respect to it, and the divergence of the gradient is
the Laplacian. The model of (3), with this source and the
exact solution on the boundary:
clock = symbolic.Clock(domain, dt=0.1)
x = ufl.SpatialCoordinate(domain)
t = ufl.variable(clock.t)
spatial = 1 + x[0] ** 2 + 2 * x[1] ** 2
exact = spatial * (1 + ufl.sin(t))
source = ufl.diff(exact, t) - ufl.div(ufl.grad(exact))
model = TimeDerivative("dudt") + Diffusion("diffusion", u, 1.0) + Source("f", u, source)
bcs = [symbolic.DirichletBC(u, "Boundary", exact)]
The mesh, with its whole boundary marked:
mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 8, 8)
marked = discrete.MeshData.from_locators(
mesh, {1: {"Boundary": lambda x: np.full(x.shape[1], True)}}, boundary=True
)
A simulation#
A Simulation builds the system of
one step once and takes the steps. Boundary values that depend on the time
are evaluated again before every step. The clock is declared with the
model, so that its step can be set, and the initial value is set with an
expression of the spatial coordinate. The function below runs to a given
time with a time-stepping scheme and a step, and returns the error in the
\(L^2\) norm:
def run(scheme: solvers.TimeScheme, dt: float, t_end: float = 1.0) -> float:
disc = discrete.discretize([model, clock], discrete.DomainMaps({domain: marked}))
disc.set({clock.dt: dt})
simulation = solvers.Simulation(disc, model, bcs, clock=clock, scheme=scheme)
disc.set({u: spatial})
simulation.run(t_end=t_end)
return error(
disc[u], lambda x: (1 + x[0] ** 2 + 2 * x[1] ** 2) * (1 + np.sin(t_end))
)
The backward differentiation formula BDF
of order \(p\) has an error proportional to \(\Delta t^p\), so halving the
step divides the error by \(2^p\). The observed rates, the base-two
logarithms of the ratios of successive errors, approach the order:
for order in (1, 2):
errors = np.array([run(solvers.BDF(order), dt) for dt in (0.1, 0.05, 0.025)])
rates = np.log2(errors[:-1] / errors[1:])
print(f"BDF{order}: errors {errors}, rates {rates.round(2)}")
assert np.all(rates > order - 0.15)
BDF1: errors [0.00311303 0.00157829 0.00079449], rates [0.98 0.99]
BDF2: errors [1.67856803e-04 4.00685201e-05 9.77328313e-06], rates [2.07 2.04]
Theta schemes#
The Theta method is implemented too.
Writing a model’s residual as \(M(\partial u / \partial t) + F(u, t)\), with
\(M\) linear in the time derivative, one step is
which is backward Euler for \(\theta = 1\), the same step as BDF of order one,
CrankNicolson, of second order,
for \(\theta = 1/2\), and ForwardEuler
for \(\theta = 0\). Every other \(\theta\) is of first order. Forward Euler is
explicit: each step solves with the time-derivative terms alone, and is
stable only for steps far below the ones above. Crank-Nicolson converges at
second order:
errors = np.array([run(solvers.CrankNicolson(), dt) for dt in (0.1, 0.05, 0.025)])
rates = np.log2(errors[:-1] / errors[1:])
print(f"Crank-Nicolson: errors {errors}, rates {rates.round(2)}")
assert np.all(rates > 2 - 0.15)
Crank-Nicolson: errors [3.81163128e-05 9.52769814e-06 2.38149579e-06], rates [2. 2.]
Runs in parts#
A simulation may run in parts, e.g. to change a load or the step between
them. The first run starts the history from the current values, and later
runs continue it, so BDF2 keeps its second order. Its weights follow the
sizes of the latest steps, so the step may change between the runs: here
it is halved halfway, and the errors still fall at second order.
restart starts afresh
instead, e.g. from new initial values:
def run_in_parts(dt: float) -> tuple[float, int]:
disc = discrete.discretize([model, clock], discrete.DomainMaps({domain: marked}))
disc.set({clock.dt: dt})
simulation = solvers.Simulation(
disc, model, bcs, clock=clock, scheme=solvers.BDF(2)
)
disc.set({u: spatial})
simulation.run(t_end=0.5)
disc.set({clock.dt: dt / 2})
simulation.run(t_end=1.0)
e = error(disc[u], lambda x: (1 + x[0] ** 2 + 2 * x[1] ** 2) * (1 + np.sin(1.0)))
return e, simulation.steps_taken
results = [run_in_parts(dt) for dt in (0.1, 0.05, 0.025)]
errors = np.array([e for e, _ in results])
rates = np.log2(errors[:-1] / errors[1:])
print(f"BDF2 in two parts: steps {[n for _, n in results]}, rates {rates.round(2)}")
assert np.all(rates > 2 - 0.15)
BDF2 in two parts: steps [15, 30, 60], rates [2.03 2.02]
Output and metadata#
With an Output, a simulation writes its
fields with ADIOS2 and a metadata.json that records the versions, the
parameters with their units, the model, the time stepping and the meshes.
The output stays open across the runs of a simulation, until it is closed
with close or at the end of a
with block. A callback is called after every step, e.g. to post-process.
The output goes to a temporary directory here, removed at the end:
with tempfile.TemporaryDirectory() as temporary:
directory = pathlib.Path(MPI.COMM_WORLD.bcast(temporary, root=0))
disc = discrete.discretize([model], discrete.DomainMaps({domain: marked}))
with solvers.Simulation(
disc,
model,
bcs,
clock=clock,
scheme=solvers.BDF(2),
output=solvers.Output(directory, every=5),
) as simulation:
disc.set({u: spatial})
simulation.run(
t_end=1.0,
callback=lambda t, step: step % 5 or print(f"t = {t:.1f}, step {step}"),
)
MPI.COMM_WORLD.barrier()
files = sorted(p.name for p in directory.iterdir())
metadata = json.loads((directory / "metadata.json").read_text())
print(files)
print(metadata["time"])
assert files == ["metadata.json", "u.bp"]
assert metadata["time"]["t0"] == 0.0
MPI.COMM_WORLD.barrier()
t = 0.5, step 5
t = 1.0, step 10
['metadata.json', 'u.bp']
{'t0': 0.0, 'dt': 0.1, 'scheme': {'type': 'BDF', 'order': 2}, 'time_scale': 0.1}
Adaptive steps#
An AdaptiveSimulation
grows the step while Newton’s method converges easily and cuts it when it
struggles, retrying failed steps, by the rules of an
AdaptiveTimeStep. Steps end
at milestones, e.g. output times, and at the end time. BDF2 adapts its
weights to the changing steps, as above. This problem is linear, so every
step takes one iteration, and the steps grow up to the largest one
allowed:
disc = discrete.discretize([model], discrete.DomainMaps({domain: marked}))
rules = solvers.AdaptiveTimeStep(
initial=0.01, growth_factor=1.5, target_iterations=4, max_step=0.2, milestones=[0.5]
)
adaptive = solvers.AdaptiveSimulation(
disc, model, rules, clock=clock, scheme=solvers.BDF(2), bcs=bcs
)
disc.set({u: spatial})
times: list[float] = []
adaptive.run(t_end=1.0, callback=lambda t, step: times.append(t))
print("Times:", np.round(times, 3))
steps = np.diff(times)
assert steps[1] > steps[0] and steps.max() <= 0.2 + 1e-12
assert np.isclose(times, 0.5).any() and np.isclose(times[-1], 1.0)
Times: [0.01 0.025 0.048 0.081 0.132 0.208 0.322 0.493 0.5 0.511 0.528 0.553
0.59 0.647 0.731 0.858 1. ]
The steps of a simulation can also be written out by hand, with a
Solver, see the demo
A time loop written by hand.