1from mpi4py import MPI
2import ufl
3from dolfinx import mesh
4from dolfinx import fem
5from dolfinx import default_scalar_type
6from dolfinx.fem.petsc import LinearProblem
7
8
9tf = 1.
10alpha = 1.
11
12
13theta = 0.5
14
15
16nt = 10
17ht = tf/nt
18
19
20domain = mesh.create_unit_interval(MPI.COMM_WORLD,
21 nx = 5)
22x = ufl.SpatialCoordinate(domain)
23
24
25V = fem.functionspace(domain, ('P', 1))
26
27
28f = fem.Function(V)
29def f(t,x):
30 return (ufl.pi**2-1.)*ufl.exp(-t)*ufl.sin(ufl.pi*x[0])
31
32
33import numpy as np
34uD = fem.Function(V)
35uD.interpolate(lambda x: np.full(x.shape[1], 0.))
36
37def boundary_D(x):
38 return np.logical_or(np.isclose(x[0], 0.),
39 np.isclose(x[0], 1.))
40
41dofs_D = fem.locate_dofs_geometrical(V, boundary_D)
42bc = fem.dirichletbc(uD, dofs_D)
43
44
45u = ufl.TrialFunction(V)
46v = ufl.TestFunction(V)
47
48
49t = 0.
50u0 = fem.Function(V)
51u0.interpolate(lambda x: np.sin(np.pi*x[0]))
52
53
54def f(t, x):
55 return (ufl.pi**2-1.)*ufl.exp(-t)*ufl.sin(ufl.pi*x[0])
56
57
58from dolfinx import io
59from pathlib import Path
60results_folder = Path("results")
61results_folder.mkdir(exist_ok=True, parents=True)
62
63
64for k in range(nt):
65 t += ht
66
67
68 a = theta * ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx
69 a += u * v / ht * ufl.dx
70
71
72 L = (theta-1.) * ufl.dot(ufl.grad(u0), ufl.grad(v)) * ufl.dx
73 L += u0 * v / ht * ufl.dx
74 L += theta * f(t, x) * v * ufl.dx
75 L += (1.-theta) * f(t-ht, x) * v * ufl.dx
76
77 problem = LinearProblem(a, L, bcs=[bc])
78 uh = problem.solve()
79
80
81 filename = results_folder / f"u_{k:0>6}"
82 with io.XDMFFile(domain.comm, filename.with_suffix(".xdmf"), "w") as xdmf:
83 xdmf.write_mesh(domain)
84 xdmf.write_function(uh, t)
85
86 u0.x.array[:] = uh.x.array[:]