Debian Codegraph @

python/test/unit/la/test_linear_operator.py

raw
1 "Unit tests for matrix-free linear solvers (LinearOperator)"
2
3 # Copyright (C) 2012 Anders Logg
4 #
5 # This file is part of DOLFIN.
6 #
7 # DOLFIN is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Lesser General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # DOLFIN is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public License
18 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
19
20 from dolfin import *
21 import pytest
22
23 from dolfin_utils.test import *
24
25 backends = ["PETSc"]
26
27
28 # Backends supporting the LinearOperator interface
29 @pytest.mark.parametrize('backend', backends)
30 def test_linear_operator(backend):
31
32 # Check whether backend is available
33 if not has_linear_algebra_backend(backend):
34 pytest.skip('Need %s as backend to run this test' % backend)
35
36 # Set linear algebra backend
37 prev_backend = parameters["linear_algebra_backend"]
38 parameters["linear_algebra_backend"] = backend
39
40 # Define linear operator
41 class MyLinearOperator(LinearOperator):
42
43 def __init__(self, a_action, u):
44 LinearOperator.__init__(self, u.vector(), u.vector())
45 self.a_action = a_action
46 self.u = u
47
48 def size(self, dim):
49 return self.u.function_space().dim()
50
51 def mult(self, x, y):
52
53 # Update coefficient vector
54 self.u.vector()[:] = x
55
56 # Assemble action
57 assemble(self.a_action, tensor=y)
58
59 # Try wrapped and backend implementation of operator
60 for _as_backend_type in [(lambda x: x), as_backend_type]:
61
62 # Compute reference value by solving ordinary linear system
63 mesh = UnitSquareMesh(8, 8)
64
65 V = FunctionSpace(mesh, "Lagrange", 1)
66 u = TrialFunction(V)
67 v = TestFunction(V)
68 f = Constant(1.0)
69 a = dot(grad(u), grad(v))*dx + u*v*dx
70 L = f*v*dx
71 A = assemble(a)
72 b = assemble(L)
73 x = Vector()
74 solve(A, x, b, "gmres", "none")
75 norm_ref = norm(x, "l2")
76
77 # Solve using linear operator defined by form action
78 u = Function(V)
79 a_action = action(a, coefficient=u)
80 O = MyLinearOperator(a_action, u)
81 Ob = _as_backend_type(O)
82 solve(Ob, x, b, "gmres", "none")
83 norm_action = norm(x, "l2")
84
85 # Check at least that petsc4py interface is available
86 if backend == 'PETSc' and has_petsc4py() and _as_backend_type == as_backend_type:
87 from petsc4py import PETSc
88 assert isinstance(Ob.mat(), PETSc.Mat)
89
90 # Reset backend
91 parameters["linear_algebra_backend"] = prev_backend