Debian Codegraph @

python/demo/documented/maxwell-eigenvalues/demo_maxwell-eigenvalues.py.rst

raw
1 .. # -*- coding: utf-8 -*-
2
3 .. codeauthor:: Douglas N. Arnold <[email protected]>,
4 Patrick E. Farrell <[email protected]>
5
6 Stable and unstable finite elements for the Maxwell eigenvalue problem
7 ======================================================================
8
9 The Maxwell eigenvalue problem seeks eigenvalues :math:`\lambda` and
10 the corresponding nonzero vector-valued eigenfunctions :math:`u`
11 satisfying the partial differential equation
12
13 .. math::
14 \operatorname{curl}\operatorname{curl} u = \lambda u \text{ in $\Omega$}
15
16 (we have simplified slightly by setting the material parameters equal
17 to 1). The PDE is to be supplemented with boundary conditions, which
18 we take here to be the essential boundary condition
19
20 .. math::
21 u \times n = 0 \text{ on $\partial\Omega$}.
22
23 The eigenvalues :math:`\lambda` are all real and non-negative, but
24 only the positive ones are of interest, since, if :math:`\lambda >0`,
25 then it follows from the PDE that :math:`\operatorname{div} u = 0`,
26 which is also a requirement of Maxwell's equations. There exist, in
27 addition, an infinite-dimensional family of eigenfunctions with
28 eigenvalue :math:`\lambda=0`, since for any smooth function
29 :math:`\phi` vanishing to second order on the boundary,
30 :math:`u=\operatorname{grad}\phi` is such an eigenfunction. But these
31 functions are not divergence-free and should not be considered Maxwell
32 eigenfunctions.
33
34 Model problem
35 -------------
36
37 In this demo we shall consider the Maxwell eigenvalue problem in two
38 dimensions with the domain :math:`\Omega` taken to be the square
39 :math:`(0,\pi)\times(0,\pi)`, since in that case the exact eigenpairs
40 have a simple analytic expression. They are
41
42 .. math::
43 u(x,y) = (\sin m x, \sin n y), \quad \lambda = m^2 + n^2,
44
45 for any non-negative integers :math:`m` and :math:`n,` not both zero.
46 Thus the eigenvalues are
47
48 .. math::
49 \lambda = 1, 1, 2, 4, 4, 5, 5, 8, 9, 9, 10, 10, 13, 13, \dots
50
51 In the demo program we compute the 12 eigenvalues nearest 5.5, and so
52 should obtain the first 12 numbers on this list, ranging from 1 to 10.
53
54 The weak formulation and the finite element method
55 --------------------------------------------------
56
57 A weak formulation of the eigenvalue problem seeks :math:`0\ne u\in
58 H_0(\operatorname{curl})` and :math:`\lambda>0` such that
59
60 .. math::
61 \int_{\Omega} \operatorname{curl} u\, \operatorname{curl}v\, {\rm d} x
62 = \lambda \int_{\Omega} u v\, {\rm d} x \quad \forall \ v\in H_0(\operatorname{curl}),
63
64 where :math:`H_0(\operatorname{curl})` is the space of
65 square-integrable vector fields with square-integrable curl and
66 satisfying the essential boundary condition. If we replace
67 :math:`H_0(\operatorname{curl})` in this formulation by a finite
68 element subspace, we obtain a finite element method.
69
70 Stable and unstable finite elements
71 -----------------------------------
72
73 We consider here two possible choices of finite element spaces. The
74 first, the Nédélec edge elements, which are obtained in FEniCS as
75 ``FunctionSpace(mesh, 'H1curl', 1)``, are well suited to this problem
76 and give an accurate discretization. The second choice is simply the
77 vector-valued Lagrange piecewise linears: ``VectorFunctionSpace(mesh,
78 'Lagrange', 1)``. To the uninitiated it usually comes as a surprise
79 that the Lagrange elements do not provide an accurate discretization
80 of the Maxwell eigenvalue problem: the computed eigenvalues do not
81 converge to the true ones as the mesh is refined! This is a subtle
82 matter connected to the stability theory of mixed finite element
83 methods. See `this paper
84 <http://umn.edu/~arnold/papers/icm2002.pdf>`_ for details.
85
86 While the Nédélec elements behave stably for any mesh, the failure of
87 the Lagrange elements differs on different sorts of meshes. Here we
88 compute with two structured meshes, the first obtained from a
89 :math:`40\times 40` grid of squares by dividing each with its
90 positively-sloped diagonal, and the second the crossed mesh obtained
91 by dividing each subsquare into four using both diagonals. The output
92 from the first case is:
93
94 .. code-block:: none
95
96 diagonal mesh
97 Nédélec: [ 1.00 1.00 2.00 4.00 4.00 5.00 5.00 8.01 8.98 8.99 9.99 9.99]
98 Lagrange: [ 5.16 5.26 5.26 5.30 5.39 5.45 5.53 5.61 5.61 5.62 5.71 5.73]
99 Exact: [ 1.00 1.00 2.00 4.00 4.00 5.00 5.00 8.00 9.00 9.00 10.00 10.00]
100
101 Note that the eigenvalues calculated using the Nédélec elements are
102 all correct to within a fraction of a percent. But the 12 eigenvalues
103 computed by the Lagrange elements are certainly all *wrong*, since
104 they are far from being integers!
105
106 On the crossed mesh, we obtain a different mode of failure:
107
108 .. code-block:: none
109
110 crossed mesh
111 Nédélec: [ 1.00 1.00 2.00 4.00 4.00 5.00 5.00 7.99 9.00 9.00 10.00 10.00]
112 Lagrange: [ 1.00 1.00 2.00 4.00 4.00 5.00 5.00 6.00 8.01 9.01 9.01 10.02]
113 Exact: [ 1.00 1.00 2.00 4.00 4.00 5.00 5.00 8.00 9.00 9.00 10.00 10.00]
114
115 Again the Nédélec elements are accurate. The Lagrange elements also
116 approximate most of the eigenvalues well, but they return a *totally
117 spurious* value of 6.00 as well. If we were to compute more
118 eigenvalues, more spurious ones would be returned. This mode of
119 failure might be considered more dangerous, since it is harder to
120 spot.
121
122 The implementation
123 ------------------
124
125 **Preamble.** First we import ``dolfin`` and ``numpy`` and make sure
126 that dolfin has been configured with PETSc and SLEPc (since we depend
127 on the SLEPc eigenvalue solver). ::
128
129 from dolfin import *
130 import numpy as np
131 if not has_linear_algebra_backend("PETSc"):
132 print("DOLFIN has not been configured with PETSc. Exiting.")
133 exit()
134 if not has_slepc():
135 print("DOLFIN has not been configured with SLEPc. Exiting.")
136 exit()
137
138 **Function eigenvalues.**
139 The function ``eigenvalues`` takes the finite element space ``V`` and the
140 essential boundary conditions ``bcs`` for it, and returns a requested
141 set of Maxwell eigenvalues (specified in the code below)
142 as a sorted numpy array::
143
144 def eigenvalues(V, bcs):
145
146 We start by defining the bilinear forms on the right- and left-hand
147 sides of the weak formulation::
148
149 #
150 # Define the bilinear forms on the right- and left-hand sides
151 u = TrialFunction(V)
152 v = TestFunction(V)
153 a = inner(curl(u), curl(v))*dx
154 b = inner(u, v)*dx
155
156 Next we assemble the bilinear forms ``a`` and ``b`` into PETSc
157 matrices ``A`` and ``B``, so the eigenvalue problem is converted into
158 a generalized matrix eigenvalue problem :math:`Ax=\lambda B x`.
159 During the assembly step the essential boundary conditions are
160 incorporated by modifying the rows and columns of the matrices corresponding to
161 constrained boundary degrees of freedom. We use ``assemble_system``
162 rather than ``assemble`` to do the assembly, since it maintains the
163 symmetry of the matrices. ``assemble_system`` is designed for source
164 problems, rather than eigenvalue problems, and requires a right-hand
165 side linear form, so we define a dummy form to feed it. ::
166
167 #
168 # Assemble into PETSc matrices
169 dummy = v[0]*dx
170 A = PETScMatrix()
171 assemble_system(a, dummy, bcs, A_tensor=A)
172 B = PETScMatrix()
173 assemble_system(b, dummy, bcs, A_tensor=B)
174
175 We zero out the rows of :math:`B` corresponding to constrained
176 boundary degrees of freedom, so as not to introduce spurious
177 eigenpairs with nonzero boundary DOFs. ::
178
179 #
180 [bc.zero(B) for bc in bcs]
181
182 Now we solve the generalized matrix eigenvalue problem using the SLEPc
183 package. The behavior of the ``SLEPcEigenSolver`` is controlled by a
184 parameter set (use ``info(solver, True)`` to see all possible
185 parameters). We use parameters to set the eigensolution method to
186 Krylov-Schur, which is good for computing a subset of the eigenvalues
187 of a sparse matrix, and to tell SLEPc that the matrices ``A`` and
188 ``B`` in the generalized eigenvalue problem are symmetric
189 (Hermitian). ::
190
191 #
192 solver = SLEPcEigenSolver(A, B)
193 solver.parameters["solver"] = "krylov-schur"
194 solver.parameters["problem_type"] = "gen_hermitian"
195
196 We specify that we want 12 eigenvalues nearest in magnitude to a
197 target value of 5.5. Note that when the ``spectrum`` parameter is set
198 to ``target magnitude``, the ``spectral_transform`` parameter should
199 be set to ``shift-and-invert`` and the ``spectral_shift`` parameter
200 should be set equal to the target. ::
201
202 #
203 solver.parameters["spectrum"] = "target magnitude"
204 solver.parameters["spectral_transform"] = "shift-and-invert"
205 solver.parameters["spectral_shift"] = 5.5
206 neigs = 12
207 solver.solve(neigs)
208
209 Finally we collect the computed eigenvalues in list which we convert
210 to a numpy array and sort before returning. Note that we are not
211 guaranteed to get the number of eigenvalues requested. The function
212 ``solver.get_number_converged()`` reports the actual number of
213 eigenvalues computed, which may be more or less than the number
214 requested. ::
215
216 #
217 # Return the computed eigenvalues in a sorted array
218 computed_eigenvalues = []
219 for i in range(min(neigs, solver.get_number_converged())):
220 r, _ = solver.get_eigenvalue(i) # ignore the imaginary part
221 computed_eigenvalues.append(r)
222 return np.sort(np.array(computed_eigenvalues))
223
224 **Function print_eigenvalues.** Given just a mesh, the function
225 ``print_eigenvalues`` calls the preceding function ``eigenvalues`` to
226 solve the Maxwell eigenvalue problem for each of the two finite
227 element spaces, Nédélec and Lagrange, and prints the results, together
228 with the known exact eigenvalues::
229
230 def print_eigenvalues(mesh):
231
232 First we define the Nédélec edge element space and the essential
233 boundary conditions for it, and call ``eigenvalues`` to compute the
234 eigenvalues. Since the degrees of freedom for the Nédélec space are
235 tangential components on element edges, we simply need to constrain
236 all the DOFs associated to boundary points to zero. ::
237
238 #
239 nedelec_V = FunctionSpace(mesh, "N1curl", 1)
240 nedelec_bcs = [DirichletBC(nedelec_V, Constant((0.0, 0.0)), DomainBoundary())]
241 nedelec_eig = eigenvalues(nedelec_V, nedelec_bcs)
242
243 Then we do the same for the vector Lagrange elements. Since the
244 Lagrange DOFs are both components of the vector, we must specify which
245 component must vanish on which edges (the x-component on horizontal
246 edges and the y-component on vertical edges). ::
247
248 #
249 lagrange_V = VectorFunctionSpace(mesh, "Lagrange", 1)
250 lagrange_bcs = [DirichletBC(lagrange_V.sub(1), 0, "near(x[0], 0) || near(x[0], pi)"),
251 DirichletBC(lagrange_V.sub(0), 0, "near(x[1], 0) || near(x[1], pi)")]
252 lagrange_eig = eigenvalues(lagrange_V, lagrange_bcs)
253
254 The true eigenvalues are just the 12 smallest numbers of the form
255 :math:`m^2 + n^2`, :math:`m,n\ge0`, not counting 0. ::
256
257 #
258 true_eig = np.sort(np.array([float(m**2 + n**2) for m in range(6) for n in range(6)]))[1:13]
259
260 Finally we print the results::
261
262 #
263 np.set_printoptions(formatter={'float': '{:5.2f}'.format})
264 print("Nedelec: {}".format(nedelec_eig))
265 print("Lagrange: {}".format(lagrange_eig))
266 print("Exact: {}".format(true_eig))
267
268 **Calling the functions.** To complete the program, we call
269 ``print_eigenvalues`` for each of two different meshes ::
270
271 mesh = RectangleMesh(Point(0, 0), Point(pi, pi), 40, 40)
272 print("\ndiagonal mesh")
273 print_eigenvalues(mesh)
274
275 mesh = RectangleMesh(Point(0, 0), Point(pi, pi), 40, 40, "crossed")
276 print("\ncrossed mesh")
277 print_eigenvalues(mesh)