| 1 |
.. Documentation for the Cahn-Hilliard demo from DOLFIN. |
| 2 |
|
| 3 |
.. _demo_pde_cahn_hilliard_cpp_documentation: |
| 4 |
|
| 5 |
Cahn-Hilliard equation |
| 6 |
====================== |
| 7 |
|
| 8 |
.. include:: ../common.txt |
| 9 |
|
| 10 |
Implementation |
| 11 |
-------------- |
| 12 |
|
| 13 |
The implementation is split in three files: two form files containing the |
| 14 |
definition of the variational forms expressed in UFL and a C++ file |
| 15 |
containing the actual solver. |
| 16 |
|
| 17 |
Running this demo requires the files: :download:`main.cpp`, |
| 18 |
:download:`CahnHilliard2D.ufl`, :download:`CahnHilliard3D.ufl` and |
| 19 |
:download:`CMakeLists.txt`. |
| 20 |
|
| 21 |
UFL form files |
| 22 |
^^^^^^^^^^^^^^ |
| 23 |
|
| 24 |
The UFL code for this problem in two and three dimensions are in |
| 25 |
:download:`CahnHilliard2D.ufl` and :download:`CahnHilliard3D.ufl` respectively. |
| 26 |
They differ only in the first line setting the cell: |
| 27 |
|
| 28 |
.. code-block:: python |
| 29 |
|
| 30 |
cell = quadrilateral |
| 31 |
|
| 32 |
First, a mixed function spaces of linear Lagrange functions on quadrilaterals |
| 33 |
is created: |
| 34 |
|
| 35 |
.. code-block:: python |
| 36 |
|
| 37 |
P1 = FiniteElement("Lagrange", cell, 1) |
| 38 |
ME = P1*P1 |
| 39 |
|
| 40 |
On the mixed space, trial and test functions are defined: |
| 41 |
|
| 42 |
.. code-block:: python |
| 43 |
|
| 44 |
du = TrialFunction(ME) |
| 45 |
q, v = TestFunctions(ME) |
| 46 |
|
| 47 |
The test functions have been split into components. |
| 48 |
|
| 49 |
Coefficient functions are now defined for the current solution (the |
| 50 |
most recent guess) and the solution from the beginning of the time |
| 51 |
step. Further, these functions (and the trial function) are split into |
| 52 |
their components: |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
u = Coefficient(ME) # current solution |
| 57 |
u0 = Coefficient(ME) # solution from previous converged step |
| 58 |
|
| 59 |
# Split mixed functions |
| 60 |
dc, dmu = split(du) |
| 61 |
c, mu = split(u) |
| 62 |
c0, mu0 = split(u0) |
| 63 |
|
| 64 |
Various model parameters can be specified using the class |
| 65 |
:py:class:`Constant`. This means that their value can be changed |
| 66 |
without recompiling the UFL file. Lastly, the value of |
| 67 |
:math:`\mu_{n+\theta}` is computed. |
| 68 |
|
| 69 |
.. code-block:: python |
| 70 |
|
| 71 |
lmbda = Constant(cell) # surface energy parameter |
| 72 |
dt = Constant(cell) # time step |
| 73 |
theta = Constant(cell) # time stepping parameter |
| 74 |
|
| 75 |
# mu_(n+theta) |
| 76 |
mu_mid = (1-theta)*mu0 + theta*mu |
| 77 |
|
| 78 |
.. index:: automatic differentiation |
| 79 |
|
| 80 |
The chemical potential :math:`df/dc` will be computed using automated |
| 81 |
differentiation: |
| 82 |
|
| 83 |
.. code-block:: python |
| 84 |
|
| 85 |
# Compute the chemical potential df/dc |
| 86 |
c = variable(c) |
| 87 |
f = 100*c**2*(1-c)**2 |
| 88 |
dfdc = diff(f, c) |
| 89 |
|
| 90 |
Here, the first line declares that ``c`` is a variable that some |
| 91 |
function can be differentiated with respect to. The next line is the |
| 92 |
function :math:`f` defined in the problem statement, and the third |
| 93 |
line performs the differentiation of ``f`` with respect to the |
| 94 |
variable ``c``. |
| 95 |
|
| 96 |
The linear forms for the two equations can be summed into one form |
| 97 |
``L``. We wish to drive the residual of this form to zero during the |
| 98 |
solution process. The directional derivative of ``L`` can be computed |
| 99 |
automatically, by calling ``derivative``, to form the bilinear form |
| 100 |
``a`` representing the Jacobian matrix: |
| 101 |
|
| 102 |
.. code-block:: python |
| 103 |
|
| 104 |
F0 = c*q*dx - c0*q*dx + dt*dot(grad(mu_mid), grad(q))*dx |
| 105 |
F1 = mu*v*dx - dfdc*v*dx - lmbda*dot(grad(c), grad(v))*dx |
| 106 |
F = F0 + F1 |
| 107 |
|
| 108 |
J = derivative(F, u, du) |
| 109 |
|
| 110 |
C++ program |
| 111 |
^^^^^^^^^^^ |
| 112 |
|
| 113 |
The first lines of this solver include the ``DOLFIN`` header files |
| 114 |
and the two files generated by the form compiler, and the ``DOLFIN`` |
| 115 |
namespace is used: |
| 116 |
|
| 117 |
.. code-block:: c++ |
| 118 |
|
| 119 |
#include <dolfin.h> |
| 120 |
#include "CahnHilliard2D.h" |
| 121 |
#include "CahnHilliard3D.h" |
| 122 |
|
| 123 |
using namespace dolfin; |
| 124 |
|
| 125 |
|
| 126 |
The class ``InitialConditions`` defines the initial conditions for the |
| 127 |
solver. In the constructor, the random number generator is seeded |
| 128 |
using the rank (process number) so that different processes will |
| 129 |
generate different sequences when running in parallel. The ``eval`` |
| 130 |
function evaluates the initial condition. The first value (``[0]``) |
| 131 |
corresponds to :math:`c` and the second value (``[1]``) corresponds to |
| 132 |
:math:`\mu`: |
| 133 |
|
| 134 |
.. code-block:: c++ |
| 135 |
|
| 136 |
// Initial conditions |
| 137 |
class InitialConditions : public Expression |
| 138 |
{ |
| 139 |
public: |
| 140 |
|
| 141 |
InitialConditions() : Expression(2) |
| 142 |
{ |
| 143 |
dolfin::seed(2 + dolfin::MPI::rank(MPI_COMM_WORLD)); |
| 144 |
} |
| 145 |
|
| 146 |
void eval(Array<double>& values, const Array<double>& x) const |
| 147 |
{ |
| 148 |
values[0]= 0.63 + 0.02*(0.5 - dolfin::rand()); |
| 149 |
values[1]= 0.0; |
| 150 |
} |
| 151 |
}; |
| 152 |
|
| 153 |
|
| 154 |
The next class is a subclass of :cpp:class:`NonlinearProblem`. A |
| 155 |
:cpp:class:`NonlinearProblem` object can be passed to a |
| 156 |
:cpp:class:`NewtonSolver` to be solved. The requirements of a |
| 157 |
:cpp:class:`NonlinearProblem` subclass are that it provides the |
| 158 |
function ``void F(GenericVector& b, const GenericVector& x)`` for |
| 159 |
computing the residual vector and the function ``void J(GenericMatrix& |
| 160 |
A, const GenericVector& x)`` for computing the Jacobian matrix. The |
| 161 |
below class is designed to work for two different generated forms (2D |
| 162 |
and 3D), with the appropriate form chosen based on the geometric |
| 163 |
dimension of the mesh. The makes the class more complicated than would |
| 164 |
be the case if it supported a single form type. The class is first |
| 165 |
declared as a subclass of cpp:class:`NonlinearProblem`: |
| 166 |
|
| 167 |
.. code-block:: c++ |
| 168 |
|
| 169 |
// User defined nonlinear problem |
| 170 |
class CahnHilliardEquation : public NonlinearProblem |
| 171 |
{ |
| 172 |
public: |
| 173 |
|
| 174 |
Its constructor takes the various arguments which are required |
| 175 |
to create the forms, and it calls a the templated private member |
| 176 |
function ``init``: |
| 177 |
|
| 178 |
.. code-block:: c++ |
| 179 |
|
| 180 |
// Constructor |
| 181 |
CahnHilliardEquation(std::shared_ptr<const Mesh> mesh, |
| 182 |
std::shared_ptr<const Constant> dt, |
| 183 |
std::shared_ptr<const Constant> theta, |
| 184 |
std::shared_ptr<const Constant> lambda) |
| 185 |
{ |
| 186 |
// Initialize class (depending on geometric dimension of the mesh). |
| 187 |
// Unfortunately C++ does not allow namespaces as template arguments |
| 188 |
dolfin_assert(mesh); |
| 189 |
if (mesh->geometry().dim() == 2) |
| 190 |
{ |
| 191 |
init<CahnHilliard2D::FunctionSpace, CahnHilliard2D::JacobianForm, |
| 192 |
CahnHilliard2D::ResidualForm>(mesh, dt, theta, lambda); |
| 193 |
} |
| 194 |
else if (mesh->geometry().dim() == 3) |
| 195 |
{ |
| 196 |
init<CahnHilliard3D::FunctionSpace, CahnHilliard3D::JacobianForm, |
| 197 |
CahnHilliard3D::ResidualForm>(mesh, dt, theta, lambda); |
| 198 |
} |
| 199 |
else |
| 200 |
error("Cahn-Hilliard model is programmed for 2D and 3D only."); |
| 201 |
} |
| 202 |
|
| 203 |
The function ``F`` computes the residual vector, which corresponds to |
| 204 |
assembly of the form ``L``: |
| 205 |
|
| 206 |
.. code-block:: c++ |
| 207 |
|
| 208 |
// User defined residual vector |
| 209 |
void F(GenericVector& b, const GenericVector& x) |
| 210 |
{ |
| 211 |
// Assemble RHS (Neumann boundary conditions) |
| 212 |
Assembler assembler; |
| 213 |
assembler.assemble(b, *L); |
| 214 |
} |
| 215 |
|
| 216 |
The function ``J`` computes the Jacobian matrix, which corresponds to |
| 217 |
the assembly of the form ``a``. |
| 218 |
|
| 219 |
.. code-block:: c++ |
| 220 |
|
| 221 |
// User defined assemble of Jacobian |
| 222 |
void J(GenericMatrix& A, const GenericVector& x) |
| 223 |
{ |
| 224 |
// Assemble system |
| 225 |
Assembler assembler; |
| 226 |
assembler.assemble(A, *a); |
| 227 |
} |
| 228 |
|
| 229 |
The following two functions are helper functions which allow access to |
| 230 |
the solution vectors: |
| 231 |
|
| 232 |
.. code-block:: c++ |
| 233 |
|
| 234 |
// Return solution function |
| 235 |
Function& u() |
| 236 |
{ return *_u; } |
| 237 |
|
| 238 |
// Return solution function |
| 239 |
Function& u0() |
| 240 |
{ return *_u0; } |
| 241 |
|
| 242 |
The private ``init`` function is responsible for creating the forms |
| 243 |
and functions associated with the problem. It is a templated function |
| 244 |
so that the 2D and 3D cases can be handled with the same code. |
| 245 |
Firstly, a shared pointer to a :cpp:class:`FunctionSpace` (``X``) is |
| 246 |
created. Then two shared pointers ``_u`` and ``_u0`` are set to point |
| 247 |
to :cpp:class:`Function` s from the space ``V``. A shared pointer is |
| 248 |
used so that the function space is not destroyed when the constructor |
| 249 |
exits. (The function space will not be destroyed until there are no |
| 250 |
more Functions or Forms that point to it.) Using the function space |
| 251 |
``V``, bilinear and linear forms are created using ``new``, and the |
| 252 |
coefficient functions are attached. These forms are then wrapped in a |
| 253 |
shared pointer (using the ``reset`` function) which will take care of |
| 254 |
eventually destroying the forms. Finally, ``_u`` is set equal to the |
| 255 |
initial condition (by interpolation). |
| 256 |
|
| 257 |
.. code-block:: c++ |
| 258 |
|
| 259 |
private: |
| 260 |
|
| 261 |
template<class X, class Y, class Z> |
| 262 |
void init(std::shared_ptr<const Mesh> mesh, |
| 263 |
std::shared_ptr<const Constant> dt, |
| 264 |
std::shared_ptr<const Constant> theta, |
| 265 |
std::shared_ptr<const Constant> lambda) |
| 266 |
{ |
| 267 |
// Create function space and functions |
| 268 |
std::shared_ptr<X> V(new X(mesh)); |
| 269 |
_u.reset(new Function(V)); |
| 270 |
_u0.reset(new Function(V)); |
| 271 |
|
| 272 |
// Create forms and attach functions |
| 273 |
Y* _a = new Y(V, V); |
| 274 |
Z* _L = new Z(V); |
| 275 |
_a->u = _u; |
| 276 |
_a->lmbda = lambda; _a->dt = dt; _a->theta = theta; |
| 277 |
_L->u = _u; _L->u0 = _u0; |
| 278 |
_L->lmbda = lambda; _L->dt = dt; _L->theta = theta; |
| 279 |
|
| 280 |
// Wrap pointers in a smart pointer |
| 281 |
a.reset(_a); |
| 282 |
L.reset(_L); |
| 283 |
|
| 284 |
// Set solution to intitial condition |
| 285 |
InitialConditions u_initial; |
| 286 |
*_u = u_initial; |
| 287 |
} |
| 288 |
|
| 289 |
The ``CahnHilliardEquation`` class stores the data required for |
| 290 |
computing the residual vector and the Jacobian matrix as private data: |
| 291 |
|
| 292 |
.. code-block:: c++ |
| 293 |
|
| 294 |
// Function space, forms and functions |
| 295 |
std::unique_ptr<Form> a; |
| 296 |
std::unique_ptr<Form> L; |
| 297 |
std::shared_ptr<Function> _u; |
| 298 |
std::shared_ptr<Function> _u0; |
| 299 |
}; |
| 300 |
|
| 301 |
The main program is started, and declared such that it can accept |
| 302 |
command line arguments. Such are parsed to ``init``: |
| 303 |
|
| 304 |
.. code-block:: c++ |
| 305 |
|
| 306 |
int main(int argc, char* argv[]) |
| 307 |
{ |
| 308 |
init(argc, argv); |
| 309 |
|
| 310 |
|
| 311 |
A mesh is then created with 97 (96 + 1) vertices in each direction: |
| 312 |
|
| 313 |
.. code-block:: c++ |
| 314 |
|
| 315 |
// Mesh |
| 316 |
auto mesh = std::make_shared<Mesh>( |
| 317 |
UnitSquareMesh::create({{96, 96}}, CellType::Type::quadrilateral)); |
| 318 |
|
| 319 |
A set of constants (required for the assembling of the forms) and two |
| 320 |
scalars (to be used in the time stepping) are then declared: |
| 321 |
|
| 322 |
.. code-block:: c++ |
| 323 |
|
| 324 |
// Time stepping and model parameters |
| 325 |
auto dt = std::make_shared<Constant>(5.0e-6); |
| 326 |
auto theta = std::make_shared<Constant>(0.5); |
| 327 |
auto lambda = std::make_shared<Constant>(1.0e-2); |
| 328 |
|
| 329 |
double t = 0.0; |
| 330 |
double T = 50*(*dt); |
| 331 |
|
| 332 |
A ``CahnHilliardEquation`` object is created, which will be used in conjunction |
| 333 |
with a Newton solver, and references to solution functions are |
| 334 |
declared: |
| 335 |
|
| 336 |
.. code-block:: c++ |
| 337 |
|
| 338 |
// Create user-defined nonlinear problem |
| 339 |
CahnHilliardEquation cahn_hilliard(mesh, dt, theta, lambda); |
| 340 |
|
| 341 |
// Solution functions |
| 342 |
Function& u = cahn_hilliard.u(); |
| 343 |
Function& u0 = cahn_hilliard.u0(); |
| 344 |
|
| 345 |
|
| 346 |
A Newton solver is created which will use a LU linear solver, and various |
| 347 |
solver parameters are set: |
| 348 |
|
| 349 |
.. code-block:: c++ |
| 350 |
|
| 351 |
// Create nonlinear solver and set parameters |
| 352 |
NewtonSolver newton_solver; |
| 353 |
newton_solver.parameters["linear_solver"] = "lu"; |
| 354 |
newton_solver.parameters["convergence_criterion"] = "incremental"; |
| 355 |
newton_solver.parameters["maximum_iterations"] = 10; |
| 356 |
newton_solver.parameters["relative_tolerance"] = 1e-6; |
| 357 |
newton_solver.parameters["absolute_tolerance"] = 1e-15; |
| 358 |
|
| 359 |
A file is created for saving the solution at each time step in VTK |
| 360 |
format. The data will be compressed to reduce the file size. |
| 361 |
|
| 362 |
.. code-block:: c++ |
| 363 |
|
| 364 |
// Save initial condition to file |
| 365 |
File file("cahn_hilliard.pvd", "compressed"); |
| 366 |
file << u[0]; |
| 367 |
|
| 368 |
The solution process is based on stepping forward in time. At the |
| 369 |
beginning of each time step, time is incremented and :math:`u_{n} |
| 370 |
\leftarrow u_{n+1}`. The Newton solver is then used to solve the |
| 371 |
nonlinear equation and the first component of the solution (``u[0]``) |
| 372 |
is saved to a file, along with the time ``t``. |
| 373 |
|
| 374 |
.. code-block:: c++ |
| 375 |
|
| 376 |
// Solve |
| 377 |
while (t < T) |
| 378 |
{ |
| 379 |
// Update for next time step |
| 380 |
t += *dt; |
| 381 |
*u0.vector() = *u.vector(); |
| 382 |
|
| 383 |
// Solve |
| 384 |
newton_solver.solve(cahn_hilliard, *u.vector()); |
| 385 |
|
| 386 |
// Save function to file |
| 387 |
file << std::pair<const Function*, double>(&(u[0]), t); |
| 388 |
} |
| 389 |
|
| 390 |
return 0; |
| 391 |
} |
| 392 |
|
| 393 |
|
| 394 |
Complete code |
| 395 |
------------- |
| 396 |
|
| 397 |
Complete UFL files |
| 398 |
^^^^^^^^^^^^^^^^^^ |
| 399 |
|
| 400 |
.. literalinclude:: CahnHilliard2D.ufl |
| 401 |
:start-after: # Compile |
| 402 |
:language: python |
| 403 |
|
| 404 |
.. literalinclude:: CahnHilliard3D.ufl |
| 405 |
:start-after: # Compile |
| 406 |
:language: python |
| 407 |
|
| 408 |
|
| 409 |
Complete main file |
| 410 |
^^^^^^^^^^^^^^^^^^ |
| 411 |
|
| 412 |
.. literalinclude:: main.cpp |
| 413 |
:start-after: // Begin demo |
| 414 |
:language: c++ |