File: ex13.rst

package info (click to toggle)
slepc4py 3.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,760 kB
  • sloc: python: 6,916; makefile: 129; ansic: 98; sh: 58
file content (340 lines) | stat: -rw-r--r-- 9,171 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
ex13.py: Nonlinear eigenproblem with contour integral
=====================================================

This example solves a nonlinear eigenvalue problem with the `NEP
<slepc4py.SLEPc.NEP>` module configured to apply a contour integral
method.

The problem arises from the PDE

.. math::

   u_{xx}(x) + n_c^2 \lambda^2 u(x) + g(\lambda) D_0 \lambda^2 u(x) = 0

where

.. math::

   g(\lambda) &= g_t/(\lambda-k_a + i g_t), \\
   k_a &= 8.0, \\
   g_t &= 0.5, \\
   D_0 &= 0.5, \\
   n_c &= 1.2,

and the boundary conditions are

.. math::

   u(0) &= 0 \\
   u_x(1) &= i \lambda u(1).

For the discretization, :math:`n` grid points are used, :math:`x_1=0,\dots,x_n=1`,
with step size :math:`h = 1/(n-1)`. Hence,

.. math::

   u_{xx}(x_i) &= \frac{1}{h^2} (u_{i-1} - 2 u_i + u_{i+1}) \\
               &= \frac{1}{h^2} [1, -2, 1] [u_{i-1}, u_i, u_{i+1}]^T.

The boundary condition at :math:`x=0` is :math:`u_1=0`, and at :math:`x=1`:

.. math::

   u'(1) &= 1/2 ( u'(1+h/2) + u'(1-h/2) ) \\
         &= 1/2 ( (u_{n+1}-u_n)/h  + (u_n-u_{n-1})/h ) \\
         &= 1/(2h) (u_{n+1} - u_{n-1}) = i\lambda u_n,

and therefore

.. math::

   u_{n+1} = 2i h \lambda u_n + u_{n-1}.

The Laplace term for :math:`u_n` is

.. math::

   &= \frac{1}{h^2} (u_{n-1} - 2u_n + u_{n+1}) \\
   &= \frac{1}{h^2} (u_{n-1} - 2u_n + 2ih\lambda u_n + u_{n-1}) \\
   &= \frac{1}{h^2} (2 u_{n-1} + (2ih\lambda - 2) u_n) \\
   &= \frac{1}{h^2} [2, 2ih\lambda -2] [u_{n-1}, u_n]^T.

The above discretization allows us to write the nonlinear PDE in the
following split-operator form

.. math::

   \{A + \lambda^2 n_c^2 I_d + g(\lambda) \lambda^2 D_0 I_d + 2i\lambda/h D\} u = 0

so :math:`f_1 = 1`, :math:`f_2 = n_c^2 \lambda^2`, :math:`f_3 = g(\lambda)
\lambda^2D_0`, :math:`f_4 = 2i\lambda/h`, with coefficient matrices

.. math::

   A = \begin{bmatrix}
       1 & 0 & 0 & \dots & 0 \\
       0 & * & * & \dots & 0 \\
       0 & * & * & \dots & 0 \\
       \vdots & \vdots & \vdots & \ddots & \vdots \\
       0 & 0 & 0 & \dots & *
       \end{bmatrix},
   I_d = \begin{bmatrix}
       0 & 0 & 0 & \dots & 0 \\
       0 & 1 & 0 & \dots & 0 \\
       0 & 0 & 1 & \dots & 0 \\
       \vdots & \vdots & \vdots & \ddots & \vdots \\
       0 & 0 & 0 & \dots & 0
       \end{bmatrix},
   D = \begin{bmatrix}
       0 & 0 & 0 & \dots & 0 \\
       0 & 0 & 0 & \dots & 0 \\
       0 & 0 & 0 & \dots & 0 \\
       \vdots & \vdots & \vdots & \ddots & \vdots \\
       0 & 0 & 0 & \dots & 1
       \end{bmatrix}.

Contributed by: Thomas Hisch.

The full source code for this demo can be `downloaded here
<../_static/ex13.py>`__.

Initialization by importing slepc4py, petsc4py, numpy and scipy.

::

  import sys

  import slepc4py

  slepc4py.init(sys.argv)  # isort:skip

  import numpy as np

  try:
      import scipy
      import scipy.optimize
  except ImportError:
      scipy = None

  from petsc4py import PETSc
  from slepc4py import SLEPc

  Print = PETSc.Sys.Print

Check that the selected PETSc/SLEPc are built with complex scalars.

::

  if not np.issubdtype(PETSc.ScalarType, np.complexfloating):
      Print("Demo should only be executed with complex PETSc scalars")
      exit(0)

Long function that defines the nonlinear eigenproblem and solves it.

::

  def solve(n):
      L = 1.0
      h = L / (n - 1)
      nc = 1.2
      ka = 10.0
      gt = 4.0
      D0 = 0.5

      A = PETSc.Mat().create()
      A.setSizes([n, n])
      A.setFromOptions()
      A.setOption(PETSc.Mat.Option.HERMITIAN, False)

      rstart, rend = A.getOwnershipRange()
      d0, d1, d2 = (
          1 / h**2,
          -2 / h**2,
          1 / h**2,
      )
      Print(f"dterms={(d0, d1, d2)}")

      if rstart == 0:
          # dirichlet boundary condition at the left lead
          A[0, 0] = 1.0
          A[0, 1] = 0.0
          A[1, 0] = 0.0

          A[1, 1] = d1
          A[1, 2] = d2
          rstart += 2
      if rend == n:
          # at x=1.0 neumann boundary condition (not handled here but in a
          # different matrix (D))
          A[n - 1, n - 2] = 2.0 / h**2
          A[n - 1, n - 1] = (-2) / h**2  # + 2j*k*h / h**2 (neumann)
          rend -= 1

      for i in range(rstart, rend):
          A[i, i - 1 : i + 2] = [d0, d1, d2]

      A.assemble()

      Id = PETSc.Mat().create()
      Id.setSizes([n, n])
      Id.setFromOptions()
      Id.setOption(PETSc.Mat.Option.HERMITIAN, True)
      rstart, rend = Id.getOwnershipRange()
      if rstart == 0:
          # due to dirichlet BC
          rstart += 1
      for i in range(rstart, rend):
          Id[i, i] = 1.0
      Id.assemble()

      D = PETSc.Mat().create()
      D.setSizes([n, n])
      D.setFromOptions()
      D.setOption(PETSc.Mat.Option.HERMITIAN, True)
      _, rend = D.getOwnershipRange()
      if rend == n:
          D[n - 1, n - 1] = 1
      D.assemble()

      Print(f"DOF: {A.getInfo()['nz_used']}, MEM: {A.getInfo()['memory']}")

      f1 = SLEPc.FN().create()
      f1.setType(SLEPc.FN.Type.RATIONAL)
      f1.setRationalNumerator([1.0])
      f2 = SLEPc.FN().create()
      f2.setType(SLEPc.FN.Type.RATIONAL)
      f2.setRationalNumerator([nc**2, 0.0, 0.0])
      f3 = SLEPc.FN().create()
      f3.setType(SLEPc.FN.Type.RATIONAL)
      f3.setRationalNumerator([D0 * gt, 0.0, 0.0])
      f3.setRationalDenominator([1.0, -ka + 1j * gt])
      f4 = SLEPc.FN().create()
      f4.setType(SLEPc.FN.Type.RATIONAL)
      f4.setRationalNumerator([2j / h, 0])

      # Setup the solver
      nep = SLEPc.NEP().create()

      nep.setSplitOperator(
          [A, Id, Id, D],
          [f1, f2, f3, f4],
          PETSc.Mat.Structure.SUBSET,
      )

      # Customize options
      nep.setTolerances(tol=1e-7)

      nep.setDimensions(nev=24)
      nep.setType(SLEPc.NEP.Type.CISS)

      # the rg params are chosen s.t. the singularity at k = ka - 1j*gt is
      # outside of the contour.
      radius = 3 * gt
      vscale = 0.5 * gt / radius
      rg_params = (ka, 3 * gt, vscale)
      R = nep.getRG()
      R.setType(SLEPc.RG.Type.ELLIPSE)
      Print(f"RG params: {rg_params}")
      R.setEllipseParameters(*rg_params)

      nep.setFromOptions()

      # Solve the problem
      nep.solve()

      its = nep.getIterationNumber()
      Print("Number of iterations of the method: %i" % its)
      sol_type = nep.getType()
      Print("Solution method: %s" % sol_type)
      nev, ncv, mpd = nep.getDimensions()
      Print("")
      Print("Subspace dimension: %i" % ncv)
      tol, maxit = nep.getTolerances()
      Print("Stopping condition: tol=%.4g" % tol)
      Print("")

      nconv = nep.getConverged()
      Print("Number of converged eigenpairs %d" % nconv)

      x = A.createVecs("right")

      evals = []
      modes = []
      if nconv > 0:
          Print()
          Print("        lam            ||T(lam)x||   |lam-lam_exact|/|lam_exact| ")
          Print("--------------------- ------------- -----------------------------")
          for i in range(nconv):
              lam = nep.getEigenpair(i, x)
              error = nep.computeError(i)

              def eigenvalue_error_term(k):
                  gkmu = gt / (k - ka + 1j * gt)
                  nceff = np.sqrt(nc**2 + gkmu * D0)
                  return -1j / np.tan(nceff * k * L) - 1 / nceff

              # compute the expected_eigenvalue

              # we assume that the numerically calculated eigenvalue is close to
              # the exact one, which we can determine using a Newton-Raphson
              # method.
              if scipy:
                  expected_lam = scipy.optimize.newton(
                      eigenvalue_error_term, np.complex128(lam), rtol=1e-11
                  )
                  rel_err = abs(lam - expected_lam) / abs(expected_lam)
                  rel_err = "%6g" % rel_err
              else:
                  rel_err = "scipy not installed"

              Print(" %9f%+9f j %12g   %s" % (lam.real, lam.imag, error, rel_err))

              evals.append(lam)
              modes.append(x.getArray().copy())
          Print()

      return np.asarray(evals), rg_params, ka, gt

The main function reads the problem size ``n`` from the command line,
solves the problem with the above function, and then plots the computed
eigenvalues.

::

  def main():
      opts = PETSc.Options()
      n = opts.getInt("n", 256)
      Print(f"n={n}")

      evals, rg_params, ka, gt = solve(n)

      if not opts.getBool("ploteigs", True) or PETSc.COMM_WORLD.getRank():
          return

      try:
          import matplotlib.pyplot as plt
          from matplotlib.patches import Ellipse
      except ImportError:
          print("plot is not shown, because matplotlib is not installed")
      else:
          fig, ax = plt.subplots()
          ax.plot(evals.real, evals.imag, "x")

          height = 2 * rg_params[1] * rg_params[2]
          ellipse = Ellipse(
              xy=(rg_params[0], 0.0),
              width=rg_params[1] * 2,
              height=height,
              edgecolor="r",
              fc="None",
              lw=2,
          )
          ax.add_patch(ellipse)

          ax.grid()
          ax.legend()
          plt.show()


  if __name__ == "__main__":
      main()