Debian Codegraph @

python/demo/documented/tensor-weighted-poisson/documentation.rst

raw
1 .. Documentation for the tensor weighted Poisson demo from DOLFIN.
2
3 .. _demo_pde_tensor-weighted-poisson_python_documentation:
4
5 Tensor-weighted Poisson
6 =======================
7
8 This demo is implemented in two files; one file,
9 :download:`generate_data.py` , for generating data, and one file,
10 :download:`demo_tensor-weighted-poisson.py` , which contains both the
11 vaiational form and the solver.
12
13 .. include:: ../common.txt
14
15 Implementation
16 --------------
17
18 Implementation of generate_data.py
19 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20
21 First, the :py:mod:`dolfin` module is imported:
22
23 .. code-block:: python
24
25 from dolfin import *
26
27 Then, we define a mesh of the domain. We use the built-in mesh,
28 provided by the class :py:class:`UnitSquareMesh
29 <dolfin.cpp.mesh.UnitSquareMesh>`. In order to create a mesh
30 consisting of :math:`32 \times 32` squares with each square divided
31 into two triangles, we do as follows:
32
33 .. code-block:: python
34
35 # Create mesh
36 mesh = UnitSquareMesh(32, 32)
37
38 Now, we create mesh functions to store the values of the conductivity
39 matrix as it varies over the domain. Since the matrix is symmetric,
40 we only create mesh functions for the upper triangular part of the
41 matrix. In :py:class:`MeshFunction <dolfin.cpp.mesh.MeshFunction>`
42 the first argument specifies the type of the mesh function, here we
43 use "double". Other types allowed are "int", "size_t" and "bool".
44 The two following arguments are optional; the first gives the mesh the
45 :py:class:`MeshFunction <dolfin.cpp.mesh.MeshFunction>` is defined on,
46 and the second the topological dimension of the mesh function.
47
48 .. code-block:: python
49
50 # Create mesh functions for c00, c01, c11
51 c00 = MeshFunction("double", mesh, 2)
52 c01 = MeshFunction("double", mesh, 2)
53 c11 = MeshFunction("double", mesh, 2)
54
55 To set the values of the mesh functions, we go through all the cells
56 in the mesh and check whether the midpoint value of the cell in the
57 :math:`x`-direction is less than 0.5 or not (in practice this means
58 that we are checking which half of the unit square the cell is
59 in). Then we set the correct values of the mesh functions, depending
60 on which half we are in.
61
62 .. code-block:: python
63
64 # Iterate over mesh and set values
65 for cell in cells(mesh):
66 if cell.midpoint().x() < 0.5:
67 c00[cell] = 1.0
68 c01[cell] = 0.3
69 c11[cell] = 2.0
70 else:
71 c00[cell] = 3.0
72 c01[cell] = 0.5
73 c11[cell] = 4.0
74
75 Create files to store data and save to file:
76
77 .. code-block:: python
78
79 # Store to file
80 mesh_file = File("../unitsquare_32_32.xml.gz")
81 c00_file = File("../unitsquare_32_32_c00.xml.gz")
82 c01_file = File("../unitsquare_32_32_c01.xml.gz")
83 c11_file = File("../unitsquare_32_32_c11.xml.gz")
84
85 mesh_file << mesh
86 c00_file << c00
87 c01_file << c01
88 c11_file << c11
89
90 Plot the mesh functions using the ``plot`` function:
91
92 .. code-block:: python
93
94 # Plot mesh functions
95 plot(c00, title="C00")
96 plot(c01, title="C01")
97 plot(c11, title="C11")
98
99 interactive()
100
101 Implementation of tensor-weighted-poisson.py
102 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
103
104 This description goes through the implementation (in
105 :download:`demo_tensor-weighted-poisson.py` ) of a solver for the above
106 described Poisson equation step-by-step.
107
108
109 First, the :py:mod:`dolfin` module is imported:
110
111 .. code-block:: python
112
113 from dolfin import *
114
115 We proceed by defining a mesh of the domain and a finite element
116 function space :math:`V` relative to this mesh. We read the mesh file
117 generated by :download:`generate_data.py` and create the function
118 space in the following way:
119
120 .. code-block:: python
121
122 # Read mesh from file and create function space
123 mesh = Mesh("../unitsquare_32_32.xml.gz")
124 V = FunctionSpace(mesh, "Lagrange", 1)
125
126 The second argument to :py:class:`FunctionSpace
127 <dolfin.cpp.function.FunctionSpace>` is the finite element family,
128 while the third argument specifies the polynomial degree. Thus, in
129 this case, our space ``V`` consists of first-order, continuous
130 Lagrange finite element functions (or in order words, continuous
131 piecewise linear polynomials).
132
133 Next, we want to consider the Dirichlet boundary condition. A simple
134 Python function, returning a boolean, can be used to define the
135 subdomain for the Dirichlet boundary condition (:math:`\Gamma_D`).
136 The function should return True for those points inside the subdomain
137 and False for the points outside. In our case, we want to say that
138 the points :math:`(x, y)` such that :math:`x = 0` or :math:`x = 1` are
139 inside on the inside of :math:`\Gamma_D`. (Note that because of
140 rounding-off errors, it is often wise to instead specify :math:`x <
141 \epsilon` or :math:`x > 1 - \epsilon` where :math:`\epsilon` is a
142 small number (such as machine precision).)
143
144 .. code-block:: python
145
146 # Define Dirichlet boundary (x = 0 or x = 1)
147 def boundary(x):
148 return x[0] < DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS
149
150 Now, the Dirichlet boundary condition can be created using the class
151 :py:class:`DirichletBC <dolfin.cpp.fem.DirichletBC>`. A
152 :py:class:`DirichletBC <dolfin.cpp.fem.DirichletBC>` takes three
153 arguments: the function space the boundary condition applies to, the
154 value of the boundary condition, and the part of the boundary on which
155 the condition applies. In our example, the function space is
156 :math:`V`. The value of the boundary condition :math:`(0.0)` can be
157 represented using a :py:class:`Constant
158 <dolfin.functions.constant.Constant>` and the Dirichlet boundary is
159 defined immediately above. The definition of the Dirichlet boundary
160 condition then looks as follows:
161
162 .. code-block:: python
163
164 # Define boundary condition
165 u0 = Constant(0.0)
166 bc = DirichletBC(V, u0, boundary)
167
168 Before we define the conductivity matrix, we create a string
169 containing C++ code for evaluation of the conductivity. Later we will
170 use this string when we create an :py:class:`Expression
171 <dolfin.cpp.function.Expression>` containing the entries of the
172 matrix.
173
174 .. code-block:: python
175
176 # Code for C++ evaluation of conductivity
177 conductivity_code = """
178
179 class Conductivity : public Expression
180 {
181 public:
182
183 // Create expression with 3 components
184 Conductivity() : Expression(3) {}
185
186 // Function for evaluating expression on each cell
187 void eval(Array<double>& values, const Array<double>& x, const ufc::cell& cell) const
188 {
189 const uint D = cell.topological_dimension;
190 const uint cell_index = cell.index;
191 values[0] = (*c00)[cell_index];
192 values[1] = (*c01)[cell_index];
193 values[2] = (*c11)[cell_index];
194 }
195
196 // The data stored in mesh functions
197 std::shared_ptr<MeshFunction<double> > c00;
198 std::shared_ptr<MeshFunction<double> > c01;
199 std::shared_ptr<MeshFunction<double> > c11;
200
201 };
202 """
203
204 We define the conductivity matrix by first creating mesh functions
205 from the files we stored in :download:`generate_data.py`. Here, the
206 third argument in :py:class:`MeshFunction
207 <dolfin.cpp.mesh.MeshFunction>` is the path to the data files. Then,
208 we define an expression for the entries in the matrix where we give
209 the C++ code as an argument for optimalization. Finally, we use the
210 UFL function ``as_matrix`` to create the matrix consisting of the
211 expressions.
212
213 .. code-block:: python
214
215 # Define conductivity expression and matrix
216 c00 = MeshFunction("double", mesh, "../unitsquare_32_32_c00.xml.gz")
217 c01 = MeshFunction("double", mesh, "../unitsquare_32_32_c01.xml.gz")
218 c11 = MeshFunction("double", mesh, "../unitsquare_32_32_c11.xml.gz")
219
220 c = Expression(cppcode=conductivity_code, degree=0)
221 c.c00 = c00
222 c.c01 = c01
223 c.c11 = c11
224 C = as_matrix(((c[0], c[1]), (c[1], c[2])))
225
226 Next, we want to express the variational problem. First, we need to
227 specify the trial function :math:`u` and the test function :math:`v`,
228 both living in the function space :math:`V`. We do this by defining a
229 :py:func:`TrialFunction <dolfin.functions.function.TrialFunction>` and
230 a :py:func:`TestFunction <dolfin.functions.function.TestFunction>` on
231 the previously defined :py:class:`FunctionSpace
232 <dolfin.cpp.function.FunctionSpace>` :math:`V`.
233
234 Further, the source :math:`f` is involved in the variational form, and
235 hence it must be must specified. Since :math:`f` is given by a simple
236 mathematical formula, it can easily be declared using the
237 :py:class:`Expression <dolfin.cpp.function.Expression>` class. Note
238 that the string defining :math:`f` uses C++ syntax since, for
239 efficiency, DOLFIN will generate and compile C++ code for these
240 expressions at run-time.
241
242 With these ingredients, we can write down the bilinear form :math:`a`
243 and the linear form :math:`L` (using UFL operators). In summary, this
244 reads:
245
246 .. code-block:: python
247
248 # Define variational problem
249 u = TrialFunction(V)
250 v = TestFunction(V)
251 f = Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)", degree=2)
252 a = inner(C*grad(u), grad(v))*dx
253 L = f*v*dx
254
255 Now, we have specified the bilinear and linear forms and can consider
256 the solution of the variational problem. First, we need to define a
257 :py:class:`Function <dolfin.cpp.function.Function>` ``u`` to
258 represent the solution. (Upon initialization, it is simply set to the
259 zero function.) A :py:class:`Function <dolfin.cpp.function.Function>`
260 represents a function living in a finite element function space.
261 Next, we can call the :py:meth:`solve
262 <dolfin.cpp.fem.GenericAdaptiveVariationalSolver.solve>` function with
263 the arguments ``a == L``, ``u`` and ``bc`` as follows:
264
265 .. code-block:: python
266
267 # Compute solution
268 u = Function(V)
269 solve(a == L, u, bc)
270
271 The function ``u`` will be modified during the call to solve. The
272 default settings for solving a variational problem have been used.
273 However, the solution process can be controlled in much more detail if
274 desired.
275
276 A :py:class:`Function <dolfin.cpp.function.Function>` can be
277 manipulated in various ways, in particular, it can be plotted and
278 saved to file. Here, we output the solution to a VTK file (using the
279 suffix .pvd) for later visualization and also plot it using the
280 :py:meth:`plot <dolfin.cpp.io.VTKPlotter.plot>` command:
281
282 .. code-block:: python
283
284 # Save solution in VTK format
285 file = File("poisson.pvd")
286 file << u
287
288 # Plot solution
289 plot(u, interactive=True)
290
291 Complete code
292 -------------
293
294 demo_tensor-weighted-poisson.py:
295
296 .. literalinclude:: demo_tensor-weighted-poisson.py
297 :start-after: # Begin demo
298
299 generate_data.py:
300
301 .. literalinclude:: generate_data.py
302 :start-after: # Begin demo