Debian Codegraph @

python/test/unit/la/test_matrix.py

raw
1 """Unit tests for the Matrix interface"""
2
3 # Copyright (C) 2011-2014 Garth N. Wells
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 # Modified by Anders Logg 2011
21 # Modified by Mikael Mortensen 2011
22 # Modified by Jan Blechta 2013
23
24 import pytest
25 from dolfin import *
26 from dolfin_utils.test import *
27
28 # TODO: Reuse this fixture setup code between matrix and vector tests:
29
30 # Lists of backends supporting or not supporting FooMatrix::data()
31 # access
32 data_backends = []
33 no_data_backends = [("PETSc", ""), ("Tpetra", "")]
34
35 # Add serial only backends
36 if MPI.size(MPI.comm_world) == 1:
37 # TODO: What about "Dense" and "Sparse"? The sub_backend wasn't
38 # used in the old test.
39 data_backends += [("Eigen", "")]
40
41 # Remove backends we haven't built with
42 data_backends = [b for b in data_backends if has_linear_algebra_backend(b[0])]
43 no_data_backends = [b for b in no_data_backends if has_linear_algebra_backend(b[0])]
44 any_backends = data_backends + no_data_backends
45
46
47 # Fixtures setting up and resetting the global linear algebra backend
48 # for a list of backends
49 any_backend = set_parameters_fixture("linear_algebra_backend", any_backends,
50 lambda x: x[0])
51 data_backend = set_parameters_fixture("linear_algebra_backend", data_backends,
52 lambda x: x[0])
53 no_data_backend = set_parameters_fixture("linear_algebra_backend",
54 no_data_backends, lambda x: x[0])
55
56 # With and without explicit backend choice
57 use_backend = true_false_fixture
58
59 class TestMatrixForAnyBackend:
60
61 def assemble_matrices(self, use_backend=False, keep_diagonal=False):
62 " Assemble a pair of matrices, one (square) MxM and one MxN"
63 mesh = UnitSquareMesh(21, 23)
64
65 V = FunctionSpace(mesh, "Lagrange", 2)
66 W = FunctionSpace(mesh, "Lagrange", 1)
67
68 v = TestFunction(V)
69 u = TrialFunction(V)
70 s = TrialFunction(W)
71
72 # Forms
73 a = dot(grad(u), grad(v))*ds
74 b = v*s*dx
75
76 if use_backend:
77 backend = globals()[self.backend + self.sub_backend + 'Factory'].instance()
78 else:
79 backend = None
80
81 # Build square matrix with some 'empty' diagonals
82 A = assemble(a, backend=backend, keep_diagonal=keep_diagonal)
83
84 # Build non-square matrix
85 B = assemble(b, backend=backend, keep_diagonal=keep_diagonal)
86
87 return A, B
88
89 def test_basic_la_operations(self, use_backend, any_backend):
90 # Hack to make old tests work in new framework. The original
91 # setup was a bit exoteric...
92 # TODO: Removing use of self in this class will make it
93 # clearer what happens in this test.
94 self.backend, self.sub_backend = any_backend
95
96 from numpy import ndarray, array, ones, sum
97
98 A, B = self.assemble_matrices(use_backend)
99 unit_norm = A.norm('frobenius')
100
101 def wrong_getitem(type):
102 if type == 0:
103 A["0,1"]
104 elif type == 1:
105 A[0]
106 elif type == 2:
107 A[0, 0, 0]
108
109 # Test wrong getitem
110 with pytest.raises(TypeError):
111 wrong_getitem(0)
112 with pytest.raises(TypeError):
113 wrong_getitem(1)
114 with pytest.raises(TypeError):
115 wrong_getitem(2)
116
117 # Test __imul__ operator
118 A *= 2
119 assert round(A.norm('frobenius') - 2*unit_norm, 7) == 0
120
121 # Test __idiv__ operator
122 A /= 2
123 assert round(A.norm('frobenius') - unit_norm, 7) == 0
124
125 # Test __mul__ operator
126 C = 4*A
127 assert round(C.norm('frobenius') - 4*unit_norm, 7) == 0
128
129 # Test __iadd__ operator
130 A += C
131 assert round(A.norm('frobenius') - 5*unit_norm, 7) == 0
132
133 # Test __isub__ operator
134 A -= C
135 assert round(A.norm('frobenius') - unit_norm, 7) == 0
136
137 # Test __mul__ and __add__ operator
138 D = (C+A)*0.2
139 assert round(D.norm('frobenius') - unit_norm, 7) == 0
140
141 # Test __div__ and __sub__ operator
142 F = (C-A)/3
143 assert round(F.norm('frobenius') - unit_norm, 7) == 0
144
145 # Test axpy
146 A.axpy(10,C,True)
147 assert round(A.norm('frobenius') - 41*unit_norm, 7) == 0
148
149 # Test expected size of rectangular array
150 assert A.size(0) == B.size(0)
151 assert B.size(1) == 528
152
153 # Test setitem/getitem
154 #A[5,5] = 15
155 #assert A[5,5] == 15
156
157 @skip_in_parallel
158 def test_numpy_array(self, use_backend, any_backend):
159 self.backend, self.sub_backend = any_backend
160
161 from numpy import ndarray, array, ones, sum
162
163 # Assemble matrices
164 A, B = self.assemble_matrices(use_backend)
165
166 # Test to NumPy array
167 A2 = A.array()
168 assert isinstance(A2,ndarray)
169 assert A2.shape == (2021, 2021)
170 assert round(sqrt(sum(A2**2)) - A.norm('frobenius'), 7) == 0
171
172 if self.backend == 'Eigen':
173 try:
174 import scipy.sparse
175 import numpy.linalg
176 A = as_backend_type(A)
177 A3 = A.sparray()
178 assert isinstance(A3, scipy.sparse.csr_matrix)
179 assert round(numpy.linalg.norm(A3.todense() - A2) - 0.0, 7) == 0
180
181 row, col, val = A.data()
182 A_scipy = scipy.sparse.csr_matrix((val, col, row))
183 assert round(numpy.linalg.norm(A_scipy.todense(), 'fro') \
184 - A.norm("frobenius"), 7) == 0.0
185
186 except ImportError:
187 pass
188
189 def test_create_empty_matrix(self, any_backend):
190 A = Matrix()
191 assert A.size(0) == 0
192 assert A.size(1) == 0
193 info(A)
194 info(A, True)
195
196 def test_copy_empty_matrix(self, any_backend):
197 A = Matrix()
198 B = Matrix(A)
199 assert B.size(0) == 0
200 assert B.size(1) == 0
201
202 def test_copy_matrix(self, any_backend):
203 A0, B0 = self.assemble_matrices()
204
205 A1 = Matrix(A0)
206 assert A0.size(0) == A1.size(0)
207 assert A0.size(1) == A1.size(1)
208 assert A0.norm("frobenius") == A1.norm("frobenius")
209
210 B1 = Matrix(B0)
211 assert B0.size(0) == B1.size(0)
212 assert B0.size(1) == B1.size(1)
213 assert round(B0.norm("frobenius") - B1.norm("frobenius"), 7) == 0
214
215 def test_ident_zeros(self, use_backend, any_backend):
216 self.backend, self.sub_backend = any_backend
217
218 # Check that PETScMatrix::ident_zeros() rethrows PETSc error
219 if self.backend[0:5] == "PETSc":
220 try:
221 from petsc4py import PETSc
222 except ImportError:
223 # Can't detect PETSc version. Skip the test.
224 pass
225 else:
226 petsc_version = PETSc.Sys.getVersion()
227 if petsc_version[0:2] == (3, 7) and petsc_version[2] >= 6:
228 # Skip the test. PETSc 3.7.(>=6) is doing the diagonal
229 # check only in debug mode so that DOLFIN might not
230 # rethrow the error. Fixed in
231 # https://bitbucket.org/petsc/petsc/commits/a21198abcdd10db88d217ac122e897fcbe3179cd
232 pass
233 else:
234 # NOTE: Throw try-except-else,if blocks above and do the
235 # test everytime when PETSc requirement is bumped
236 # to 3.8
237 A, B = self.assemble_matrices(use_backend=use_backend)
238 with pytest.raises(RuntimeError):
239 A.ident_zeros()
240
241 # Assemble matrix A with diagonal entries
242 A, B = self.assemble_matrices(use_backend=use_backend,
243 keep_diagonal=True)
244
245 # Find zero rows
246 zero_rows = []
247 for i in range(A.local_range(0)[0], A.local_range(0)[1]):
248 row = A.getrow(i)[1]
249 if sum(abs(row)) < DOLFIN_EPS:
250 zero_rows.append(i)
251
252 # Set zero rows to (0,...,0, 1, 0,...,0)
253 A.ident_zeros()
254
255 # Check it
256 for i in zero_rows:
257 cols = A.getrow(i)[0]
258 row = A.getrow(i)[1]
259 for j in range(cols.size + 1):
260 if i == cols[j]:
261 assert round(row[j] - 1.0, 7) == 0
262 break
263 assert j < cols.size
264 assert round(sum(abs(row)) - 1.0, 7) == 0
265
266 @skip_in_parallel
267 def test_ident(self, use_backend, any_backend):
268 self.backend, self.sub_backend = any_backend
269 if self.backend == 'Tpetra':
270 pytest.skip()
271 A, B = self.assemble_matrices(use_backend)
272 N, M = A.size(0), A.size(1)
273
274 # Make sure rows are not identity from before
275 import numpy
276 ROWS = [2, 4]
277 for row in ROWS:
278 block = numpy.array([[42.0]], dtype=float)
279 A.set(block, numpy.array([row], dtype=numpy.intc),
280 numpy.array([row], dtype=numpy.intc))
281 A.apply("insert")
282
283 def check_row(A, row, idented):
284 cols, vals = A.getrow(row)
285 i = list(cols).index(row)
286 if idented:
287 assert vals[i] == 1
288 vals[i] = 0
289 for c in cols:
290 if c != row:
291 assert (vals == 0).all()
292 else:
293 assert vals[i] == 42.0
294
295 for row in ROWS:
296 check_row(A, row, False)
297 A.ident(numpy.array(ROWS, dtype=numpy.intc))
298 A.apply("insert")
299 for row in ROWS:
300 check_row(A, row, True)
301
302 def test_setting_getting_diagonal(self, use_backend, any_backend):
303 self.backend, self.sub_backend = any_backend
304
305 mesh = UnitSquareMesh(21, 23)
306
307 V = FunctionSpace(mesh, "Lagrange", 2)
308 v = TestFunction(V)
309 u = TrialFunction(V)
310 w = Function(V)
311
312 if use_backend:
313 backend = globals()[self.backend + self.sub_backend + 'Factory'].instance()
314 else:
315 backend = None
316
317 B = assemble(u*v*dx(), backend=backend, keep_diagonal=True)
318
319 b = assemble(action(u*v*dx(), Constant(1)))
320 A = B.copy()
321 A.zero()
322 A.set_diagonal(b)
323
324 resultsA = Vector()
325 resultsB = Vector()
326 A.init_vector(resultsA, 1)
327 B.init_vector(resultsB, 1)
328
329 ones = b.copy()
330 ones[:] = 1.0
331
332 A.mult(ones, resultsA)
333 B.mult(ones, resultsB)
334 assert round(resultsA.norm("l2") - resultsB.norm("l2"), 7) == 0
335
336 A.get_diagonal(w.vector())
337 w.vector()[:] -= b
338 assert round(w.vector().norm("l2"), 14) == 0
339
340 @skip_in_parallel
341 def test_get_set(self, use_backend, any_backend):
342 self.backend, self.sub_backend = any_backend
343 if self.backend == 'Tpetra':
344 pytest.skip()
345 A, B = self.assemble_matrices(use_backend)
346 N, M = A.size(0), A.size(1)
347
348 import numpy
349 rows = numpy.array([1, 2], dtype=numpy.intc)
350 cols = numpy.array([1, 2], dtype=numpy.intc)
351
352 block_in = numpy.ones((2, 2), dtype=float) * 42
353 Anp0 = A.array()
354 assert (Anp0[1:3,1:3] != block_in).any()
355
356 A.set(block_in, rows, cols)
357 A.apply("insert")
358
359 Anp1 = A.array()
360 assert (Anp1[1:3,1:3] == block_in).all()
361
362 block_out = numpy.zeros_like(block_in)
363 A.get(block_out, rows, cols)
364 assert (block_out == block_in).all()
365
366 # def test_create_from_sparsity_pattern(self):
367
368 # def test_size(self):
369
370 # def test_local_range(self):
371
372 # def test_zero(self):
373
374 # def test_apply(self):
375
376 # def test_str(self):
377
378 # def test_resize(self):
379
380
381 # Test the access of the raw data through pointers
382 # This is only available for the Eigen backend
383 def test_matrix_data(self, use_backend, data_backend):
384 """ Test for ordinary Matrix"""
385 self.backend, self.sub_backend = data_backend
386
387 A, B = self.assemble_matrices(use_backend)
388 A = as_backend_type(A)
389 B = as_backend_type(B)
390
391 array = A.array()
392 rows, cols, values = A.data()
393 i = 0
394 for row in range(A.size(0)):
395 for col in range(rows[row], rows[row+1]):
396 assert array[row, cols[col]] == values[i]
397 i += 1
398
399 # Test for as_backend_typeed Matrix
400 A = as_backend_type(A)
401 rows, cols, values = A.data()
402 for row in range(A.size(0)):
403 for k in range(rows[row], rows[row+1]):
404 assert array[row,cols[k]] == values[k]
405
406
407 def test_matrix_nnz(self, any_backend):
408 A, B = self.assemble_matrices()
409 assert A.nnz() == 2992
410 assert B.nnz() == 9398
411
412 A, B = self.assemble_matrices(keep_diagonal=True)
413 assert A.nnz() == 4589
414 # NOTE: Following should never be tested because diagonal is not
415 # invariant w.r.t. different row and column dof reordering!
416 #assert B.nnz() == ??