Debian Codegraph @

python/demo/documented/cahn-hilliard/demo_cahn-hilliard.py.rst

raw
1 Cahn-Hilliard equation
2 ======================
3
4 This demo is implemented in a single Python file,
5 :download:`demo_cahn-hilliard.py`, which contains both the variational
6 forms and the solver.
7
8 This example demonstrates the solution of a particular nonlinear
9 time-dependent fourth-order equation, known as the Cahn-Hilliard
10 equation. In particular it demonstrates the use of
11
12 * The built-in Newton solver
13 * Advanced use of the base class ``NonlinearProblem``
14 * Automatic linearisation
15 * A mixed finite element method
16 * The :math:`\theta`-method for time-dependent equations
17 * User-defined Expressions as Python classes
18 * Form compiler options
19 * Interpolation of functions
20
21
22 Equation and problem definition
23 -------------------------------
24
25 The Cahn-Hilliard equation is a parabolic equation and is typically
26 used to model phase separation in binary mixtures. It involves
27 first-order time derivatives, and second- and fourth-order spatial
28 derivatives. The equation reads:
29
30 .. math::
31 \frac{\partial c}{\partial t} - \nabla \cdot M \left(\nabla\left(\frac{d f}{d c}
32 - \lambda \nabla^{2}c\right)\right) &= 0 \quad {\rm in} \ \Omega, \\
33 M\left(\nabla\left(\frac{d f}{d c} - \lambda \nabla^{2}c\right)\right) \cdot n &= 0 \quad {\rm on} \ \partial\Omega, \\
34 M \lambda \nabla c \cdot n &= 0 \quad {\rm on} \ \partial\Omega.
35
36 where :math:`c` is the unknown field, the function :math:`f` is
37 usually non-convex in :math:`c` (a fourth-order polynomial is commonly
38 used), :math:`n` is the outward directed boundary normal, and
39 :math:`M` is a scalar parameter.
40
41
42 Mixed form
43 ^^^^^^^^^^
44
45 The Cahn-Hilliard equation is a fourth-order equation, so casting it
46 in a weak form would result in the presence of second-order spatial
47 derivatives, and the problem could not be solved using a standard
48 Lagrange finite element basis. A solution is to rephrase the problem
49 as two coupled second-order equations:
50
51 .. math::
52 \frac{\partial c}{\partial t} - \nabla \cdot M \nabla\mu &= 0 \quad {\rm in} \ \Omega, \\
53 \mu - \frac{d f}{d c} + \lambda \nabla^{2}c &= 0 \quad {\rm in} \ \Omega.
54
55 The unknown fields are now :math:`c` and :math:`\mu`. The weak
56 (variational) form of the problem reads: find :math:`(c, \mu) \in V
57 \times V` such that
58
59 .. math::
60 \int_{\Omega} \frac{\partial c}{\partial t} q \, {\rm d} x + \int_{\Omega} M \nabla\mu \cdot \nabla q \, {\rm d} x
61 &= 0 \quad \forall \ q \in V, \\
62 \int_{\Omega} \mu v \, {\rm d} x - \int_{\Omega} \frac{d f}{d c} v \, {\rm d} x - \int_{\Omega} \lambda \nabla c \cdot \nabla v \, {\rm d} x
63 &= 0 \quad \forall \ v \in V.
64
65
66 Time discretisation
67 ^^^^^^^^^^^^^^^^^^^
68
69 Before being able to solve this problem, the time derivative must be
70 dealt with. Apply the :math:`\theta`-method to the mixed weak form of
71 the equation:
72
73 .. math::
74
75 \int_{\Omega} \frac{c_{n+1} - c_{n}}{dt} q \, {\rm d} x + \int_{\Omega} M \nabla \mu_{n+\theta} \cdot \nabla q \, {\rm d} x
76 &= 0 \quad \forall \ q \in V \\
77 \int_{\Omega} \mu_{n+1} v \, {\rm d} x - \int_{\Omega} \frac{d f_{n+1}}{d c} v \, {\rm d} x - \int_{\Omega} \lambda \nabla c_{n+1} \cdot \nabla v \, {\rm d} x
78 &= 0 \quad \forall \ v \in V
79
80 where :math:`dt = t_{n+1} - t_{n}` and :math:`\mu_{n+\theta} =
81 (1-\theta) \mu_{n} + \theta \mu_{n+1}`. The task is: given
82 :math:`c_{n}` and :math:`\mu_{n}`, solve the above equation to find
83 :math:`c_{n+1}` and :math:`\mu_{n+1}`.
84
85
86 Demo parameters
87 ^^^^^^^^^^^^^^^
88
89 The following domains, functions and time stepping parameters are used
90 in this demo:
91
92 * :math:`\Omega = (0, 1) \times (0, 1)` (unit square)
93 * :math:`f = 100 c^{2} (1-c)^{2}`
94 * :math:`\lambda = 1 \times 10^{-2}`
95 * :math:`M = 1`
96 * :math:`dt = 5 \times 10^{-6}`
97 * :math:`\theta = 0.5`
98
99
100 Implementation
101 --------------
102
103 This demo is implemented in the :download:`demo_cahn-hilliard.py`
104 file.
105
106 First, the modules :py:mod:`random` :py:mod:`matplotlib`
107 :py:mod:`dolfin` module are imported::
108
109 import random
110 from dolfin import *
111
112 .. index:: Expression
113
114 A class which will be used to represent the initial conditions is then
115 created::
116
117 # Class representing the intial conditions
118 class InitialConditions(UserExpression):
119 def __init__(self, **kwargs):
120 random.seed(2 + MPI.rank(MPI.comm_world))
121 super().__init__(**kwargs)
122 def eval(self, values, x):
123 values[0] = 0.63 + 0.02*(0.5 - random.random())
124 values[1] = 0.0
125 def value_shape(self):
126 return (2,)
127
128 It is a subclass of :py:class:`Expression
129 <dolfin.functions.expression.Expression>`. In the constructor
130 (``__init__``), the random number generator is seeded. If the program
131 is run in parallel, the random number generator is seeded using the
132 rank (process number) to ensure a different sequence of numbers on
133 each process. The function ``eval`` returns values for a function of
134 dimension two. For the first component of the function, a randomized
135 value is returned. The method ``value_shape`` declares that the
136 :py:class:`Expression <dolfin.functions.expression.Expression>` is
137 vector valued with dimension two.
138
139 .. index::
140 single: NonlinearProblem; (in Cahn-Hilliard demo)
141
142 A class which will represent the Cahn-Hilliard in an abstract from for
143 use in the Newton solver is now defined. It is a subclass of
144 :py:class:`NonlinearProblem <dolfin.cpp.NonlinearProblem>`. ::
145
146 # Class for interfacing with the Newton solver
147 class CahnHilliardEquation(NonlinearProblem):
148 def __init__(self, a, L):
149 NonlinearProblem.__init__(self)
150 self.L = L
151 self.a = a
152 def F(self, b, x):
153 assemble(self.L, tensor=b)
154 def J(self, A, x):
155 assemble(self.a, tensor=A)
156
157 The constructor (``__init__``) stores references to the bilinear
158 (``a``) and linear (``L``) forms. These will used to compute the
159 Jacobian matrix and the residual vector, respectively, for use in a
160 Newton solver. The function ``F`` and ``J`` are virtual member
161 functions of :py:class:`NonlinearProblem
162 <dolfin.cpp.NonlinearProblem>`. The function ``F`` computes the
163 residual vector ``b``, and the function ``J`` computes the Jacobian
164 matrix ``A``.
165
166 Next, various model parameters are defined::
167
168 # Model parameters
169 lmbda = 1.0e-02 # surface parameter
170 dt = 5.0e-06 # time step
171 theta = 0.5 # time stepping family, e.g. theta=1 -> backward Euler, theta=0.5 -> Crank-Nicolson
172
173 .. index::
174 singe: form compiler options; (in Cahn-Hilliard demo)
175
176 It is possible to pass arguments that control aspects of the generated
177 code to the form compiler. The lines ::
178
179 # Form compiler options
180 parameters["form_compiler"]["optimize"] = True
181 parameters["form_compiler"]["cpp_optimize"] = True
182
183 tell the form to apply optimization strategies in the code generation
184 phase and the use compiler optimization flags when compiling the
185 generated C++ code. Using the option ``["optimize"] = True`` will
186 generally result in faster code (sometimes orders of magnitude faster
187 for certain operations, depending on the equation), but it may take
188 considerably longer to generate the code and the generation phase may
189 use considerably more memory).
190
191 A unit square mesh with 97 (= 96 + 1) vertices in each direction is
192 created, and on this mesh a :py:class:`FunctionSpace
193 <dolfin.functions.functionspace.FunctionSpace>` ``ME`` is built using
194 a pair of linear Lagrangian elements. ::
195
196 # Create mesh and build function space
197 mesh = UnitSquareMesh.create(96, 96, CellType.Type.quadrilateral)
198 P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
199 ME = FunctionSpace(mesh, P1*P1)
200
201 Trial and test functions of the space ``ME`` are now defined::
202
203 # Define trial and test functions
204 du = TrialFunction(ME)
205 q, v = TestFunctions(ME)
206
207 .. index:: split functions
208
209 For the test functions, :py:func:`TestFunctions
210 <dolfin.functions.function.TestFunctions>` (note the 's' at the end)
211 is used to define the scalar test functions ``q`` and ``v``. The
212 :py:class:`TrialFunction <dolfin.functions.function.TrialFunction>`
213 ``du`` has dimension two. Some mixed objects of the
214 :py:class:`Function <dolfin.functions.function.Function>` class on
215 ``ME`` are defined to represent :math:`u = (c_{n+1}, \mu_{n+1})` and
216 :math:`u0 = (c_{n}, \mu_{n})`, and these are then split into
217 sub-functions::
218
219 # Define functions
220 u = Function(ME) # current solution
221 u0 = Function(ME) # solution from previous converged step
222
223 # Split mixed functions
224 dc, dmu = split(du)
225 c, mu = split(u)
226 c0, mu0 = split(u0)
227
228 The line ``c, mu = split(u)`` permits direct access to the components
229 of a mixed function. Note that ``c`` and ``mu`` are references for
230 components of ``u``, and not copies.
231
232 .. index::
233 single: interpolating functions; (in Cahn-Hilliard demo)
234
235 Initial conditions are created by using the class defined at the
236 beginning of the demo and then interpolating the initial conditions
237 into a finite element space::
238
239 # Create intial conditions and interpolate
240 u_init = InitialConditions(degree=1)
241 u.interpolate(u_init)
242 u0.interpolate(u_init)
243
244 The first line creates an object of type ``InitialConditions``. The
245 following two lines make ``u`` and ``u0`` interpolants of ``u_init``
246 (since ``u`` and ``u0`` are finite element functions, they may not be
247 able to represent a given function exactly, but the function can be
248 approximated by interpolating it in a finite element space).
249
250 .. index:: automatic differentiation
251
252 The chemical potential :math:`df/dc` is computed using automated
253 differentiation::
254
255 # Compute the chemical potential df/dc
256 c = variable(c)
257 f = 100*c**2*(1-c)**2
258 dfdc = diff(f, c)
259
260 The first line declares that ``c`` is a variable that some function
261 can be differentiated with respect to. The next line is the function
262 :math:`f` defined in the problem statement, and the third line
263 performs the differentiation of ``f`` with respect to the variable
264 ``c``.
265
266 It is convenient to introduce an expression for :math:`\mu_{n+\theta}`::
267
268 # mu_(n+theta)
269 mu_mid = (1.0-theta)*mu0 + theta*mu
270
271 which is then used in the definition of the variational forms::
272
273 # Weak statement of the equations
274 L0 = c*q*dx - c0*q*dx + dt*dot(grad(mu_mid), grad(q))*dx
275 L1 = mu*v*dx - dfdc*v*dx - lmbda*dot(grad(c), grad(v))*dx
276 L = L0 + L1
277
278 This is a statement of the time-discrete equations presented as part
279 of the problem statement, using UFL syntax. The linear forms for the
280 two equations can be summed into one form ``L``, and then the
281 directional derivative of ``L`` can be computed to form the bilinear
282 form which represents the Jacobian matrix::
283
284 # Compute directional derivative about u in the direction of du (Jacobian)
285 a = derivative(L, u, du)
286
287 .. index::
288 single: Newton solver; (in Cahn-Hilliard demo)
289
290 The DOLFIN Newton solver requires a :py:class:`NonlinearProblem
291 <dolfin.cpp.NonlinearProblem>` object to solve a system of nonlinear
292 equations. Here, we are using the class ``CahnHilliardEquation``,
293 which was declared at the beginning of the file, and which is a
294 sub-class of :py:class:`NonlinearProblem
295 <dolfin.cpp.NonlinearProblem>`. We need to instantiate objects of both
296 ``CahnHilliardEquation`` and :py:class:`NewtonSolver
297 <dolfin.cpp.NewtonSolver>`::
298
299 # Create nonlinear problem and Newton solver
300 problem = CahnHilliardEquation(a, L)
301 solver = NewtonSolver()
302 solver.parameters["linear_solver"] = "lu"
303 solver.parameters["convergence_criterion"] = "incremental"
304 solver.parameters["relative_tolerance"] = 1e-6
305
306 The string ``"lu"`` passed to the Newton solver indicated that an LU
307 solver should be used. The setting of
308 ``parameters["convergence_criterion"] = "incremental"`` specifies that
309 the Newton solver should compute a norm of the solution increment to
310 check for convergence (the other possibility is to use ``"residual"``,
311 or to provide a user-defined check). The tolerance for convergence is
312 specified by ``parameters["relative_tolerance"] = 1e-6``.
313
314 To run the solver and save the output to a VTK file for later visualization,
315 the solver is advanced in time from :math:`t_{n}` to :math:`t_{n+1}` until
316 a terminal time :math:`T` is reached::
317
318 # Output file
319 file = File("output.pvd", "compressed")
320
321 # Step in time
322 t = 0.0
323 T = 50*dt
324 while (t < T):
325 t += dt
326 u0.vector()[:] = u.vector()
327 solver.solve(problem, u.vector())
328 file << (u.split()[0], t)
329
330 The string ``"compressed"`` indicates that the output data should be
331 compressed to reduce the file size. Within the time stepping loop, the
332 solution vector associated with ``u`` is copied to ``u0`` at the
333 beginning of each time step, and the nonlinear problem is solved by
334 calling :py:func:`solver.solve(problem, u.vector())
335 <dolfin.cpp.NewtonSolver.solve>`, with the new solution vector
336 returned in :py:func:`u.vector() <dolfin.cpp.Function.vector>`. The
337 ``c`` component of the solution (the first component of ``u``) is then
338 written to file at every time step.