Debian Codegraph @

python/test/unit/la/test_vector.py

raw ◀ ▶
1 Debian patch touch this file
1 """Unit tests for the Vector 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
22 import pytest
23 import numpy
24 from copy import copy
•25 from ctypes import c_long
26
27 from dolfin import *
28 from dolfin_utils.test import *
29
30 # TODO: Use the fixture setup from matrix in a shared conftest.py when
31 # we move tests to one flat folder.
32
33 # Lists of backends supporting or not supporting GenericVector::data()
34 # access
35 data_backends = []
36 no_data_backends = ["PETSc", "Tpetra"]
37
38 # Add serial only backends
39 if MPI.size(MPI.comm_world) == 1:
40 # TODO: What about "Dense" and "Sparse"? The sub_backend wasn't
41 # used in the old test.
42 data_backends += ["Eigen"]
43
44 # Remove backends we haven't built with
45 data_backends = list(filter(has_linear_algebra_backend, data_backends))
46 no_data_backends = list(filter(has_linear_algebra_backend, no_data_backends))
47 any_backends = data_backends + no_data_backends
48
49 # Fixtures setting up and resetting the global linear algebra backend
50 # for a list of backends
51 data_backend = set_parameters_fixture("linear_algebra_backend", data_backends)
52 no_data_backend = set_parameters_fixture("linear_algebra_backend",
53 no_data_backends)
54 any_backend = set_parameters_fixture("linear_algebra_backend", any_backends)
55
56 class TestVectorForAnyBackend:
57
58 def test_create_empty_vector(self, any_backend):
59 v0 = Vector()
60 info(v0)
61 info(v0, True)
62 assert v0.size() == 0
63
64 def test_create_vector(self, any_backend):
65 n = 301
66 v1 = Vector(MPI.comm_world, n)
67 assert v1.size() == n
68
69 def test_copy_vector(self, any_backend):
70 n = 301
71 v0 = Vector(MPI.comm_world, n)
72 v1 = Vector(v0)
73 assert v0.size() == n
74 del v0
75 assert v1.size() == n
76
77 def test_assign_and_copy_vector(self, any_backend):
78 n = 301
79 v0 = Vector(MPI.comm_world, n)
80 v0[:] = 1.0
81 assert v0.sum() == n
82 v1 = Vector(v0)
83 del v0
84 assert v1.sum() == n
85
86 def test_zero(self, any_backend):
87 v0 = Vector(MPI.comm_world, 301)
88 v0.zero()
89 assert v0.sum() == 0.0
90
91 def test_apply(self, any_backend):
92 v0 = Vector(MPI.comm_world, 301)
93 v0.apply("insert")
94 v0.apply("add")
95
96 def test_str(self, any_backend):
97 v0 = Vector(MPI.comm_world, 13)
98 tmp = v0.str(False)
99 tmp = v0.str(True)
100
101 def test_init_range(self, any_backend):
102 n = 301
103 local_range = MPI.local_range(MPI.comm_world, n)
104 v0 = Vector(MPI.comm_world)
105 v0.init(local_range)
106 assert v0.local_range() == local_range
107
108 def test_size(self, any_backend):
109 n = 301
110 v0 = Vector(MPI.comm_world, 301)
111 assert v0.size() == n
112
113 def test_local_size(self, any_backend):
114 n = 301
115 local_range = MPI.local_range(MPI.comm_world, n)
116 v0 = Vector(MPI.comm_world)
117 v0.init(local_range)
118 assert v0.local_size() == local_range[1] - local_range[0]
119
120 def test_owns_index(self, any_backend):
121 m, n = 301, 25
122 v0 = Vector(MPI.comm_world, m)
123 local_range = v0.local_range()
124 in_range = local_range[0] <= n < local_range[1]
125 assert v0.owns_index(n) == in_range
126
127 #def test_set(self, any_backend):
128
129 #def test_add(self, any_backend):
130
131 def test_get_local(self, any_backend):
132 from numpy import empty
133 n = 301
134 v0 = Vector(MPI.comm_world, n)
135 data = v0.get_local()
136
137 def test_set_local(self, any_backend):
138 from numpy import zeros
139 n = 301
140 v0 = Vector(MPI.comm_world, n)
141 data = zeros((v0.local_size()), dtype='d')
142 v0.set_local(data)
143 data = zeros((v0.local_size()*2), dtype='d')
144
145 def test_add_local(self, any_backend):
146 from numpy import zeros
147 n = 301
148 v0 = Vector(MPI.comm_world, n)
149 data = zeros((v0.local_size()), dtype='d')
150 v0.add_local(data)
151 data = zeros((v0.local_size()*2), dtype='d')
152
153 def test_gather(self, any_backend):
154 # Gather not implemented in Eigen
155 if any_backend == "Eigen" or any_backend == "Tpetra":
156 return
157
158 # Create distributed vector of local size 1
159 x = DefaultFactory().create_vector(MPI.comm_world)
160 r = MPI.rank(x.mpi_comm())
161 x.init((r, r+1))
162
163 # Create local vector
164 y = DefaultFactory().create_vector(MPI.comm_self)
165
166 # Do the actual test across all rank permutations
167 for target_rank in range(MPI.size(x.mpi_comm())):
168
169 # Set nonzero value on single rank
170 if r == target_rank:
171 x[0] = 42.0 # Set using local index
172 else:
173 x[0] = 0.0 # Set using local index
174 assert numpy.isclose(x.sum(), 42.0)
175
176 # Gather (using global index) and check the result
177 x.gather(y, numpy.array([target_rank], dtype=la_index_dtype()))
178 assert numpy.isclose(y[0], 42.0)
179
180 # NumPy array version
181 out = x.gather(numpy.array([target_rank], dtype=la_index_dtype()))
182 assert out.shape == (1,) and numpy.isclose(out[0], 42.0)
183
184 # Test gather on zero
185 out = x.gather_on_zero()
186 if r == 0:
187 expected = numpy.array([42.0 if i == target_rank else 0.0
188 for i in range(x.size())])
189 else:
190 expected = numpy.array([])
191 assert out.shape == expected.shape and numpy.allclose(out, expected)
192
193 # Test also the corner case of empty indices on one process
194 if r == target_rank:
195 out = x.gather(numpy.array([], dtype=la_index_dtype()))
196 expected = numpy.array([])
197 else:
198 out = x.gather(numpy.array([target_rank], dtype=la_index_dtype()))
199 expected = numpy.array([42.0])
200 assert out.shape == expected.shape and numpy.allclose(out, expected)
201
202 # Check that distributed gather vector is not accepted
203 if MPI.size(MPI.comm_world) > 1:
204 z = DefaultFactory().create_vector(MPI.comm_world)
205 with pytest.raises(RuntimeError):
206 x.gather(z, numpy.array([0], dtype=la_index_dtype()))
207
208 # Check that gather vector of wrong size is not accepted
209 z = DefaultFactory().create_vector(MPI.comm_self)
210 z.init(3)
211 with pytest.raises(RuntimeError):
212 x.gather(z, numpy.array([0], dtype=la_index_dtype()))
213
214 def test_axpy(self, any_backend):
215 n = 301
216 v0 = Vector(MPI.comm_world, n)
217 v0[:] = 1.0
218 v1 = Vector(v0)
219 v0.axpy(2.0, v1)
220 assert v0.sum() == 2*n + n
221
222 def test_abs(self, any_backend):
223 n = 301
224 v0 = Vector(MPI.comm_world, n)
225 v0[:] = -1.0
226 v0.abs()
227 assert v0.sum() == n
228
229 def test_inner(self, any_backend):
230 n = 301
231 v0 = Vector(MPI.comm_world, n)
232 v0[:] = 2.0
233 v1 = Vector(MPI.comm_world, n)
234 v1[:] = 3.0
235 assert v0.inner(v1) == 6*n
236
237 def test_norm(self, any_backend):
238 n = 301
239 v0 = Vector(MPI.comm_world, n)
240 v0[:] = -2.0
241 assert v0.norm("l1") == 2.0*n
242 assert v0.norm("l2") == sqrt(4.0*n)
243 assert v0.norm("linf") == 2.0
244
245 def test_min(self, any_backend):
246 v0 = Vector(MPI.comm_world, 301)
247 v0[:] = 2.0
248 assert v0.min() == 2.0
249
250 def test_max(self, any_backend):
251 v0 = Vector(MPI.comm_world,301)
252 v0[:] = -2.0
253 assert v0.max() == -2.0
254
255 def test_sum(self, any_backend):
256 n = 301
257 v0 = Vector(MPI.comm_world, n)
258 v0[:] = -2.0
259 assert v0.sum() == -2.0*n
260
261 def test_sum_entries(self, any_backend):
262 from numpy import zeros
263 n = 301
264 v0 = Vector(MPI.comm_world, n)
265 v0[:] = -2.0
266 entries = zeros(5, dtype='uintp')
267 assert v0.sum(entries) == -2.0
268 entries[0] = 2
269 entries[1] = 1
270 entries[2] = 236
271 entries[3] = 123
272 entries[4] = 97
273 assert v0.sum(entries) == -2.0*5
274
275 def test_scalar_mult(self, any_backend):
276 n = 301
277 v0 = Vector(MPI.comm_world, n)
278 v0[:] = -1.0
279 v0 *= 2.0
280 assert v0.sum() == -2.0*n
281
282 def test_vector_element_mult(self, any_backend):
283 n = 301
284 v0 = Vector(MPI.comm_world, n)
285 v1 = Vector(MPI.comm_world, n)
286 v0[:] = -2.0
287 v1[:] = 3.0
288 v0 *= v1
289 assert v0.sum() == -6.0*n
290
291 def test_scalar_divide(self, any_backend):
292 n = 301
293 v0 = Vector(MPI.comm_world, n)
294 v0[:] = -1.0
295 v0 /= -2.0
296 assert v0.sum() == 0.5*n
297
298 def test_vector_add(self, any_backend):
299 n = 301
300 v0 = Vector(MPI.comm_world, n)
301 v1 = Vector(MPI.comm_world, n)
302 v0[:] = -1.0
303 v1[:] = 2.0
304 v0 += v1
305 assert v0.sum() == n
306
307 def test_scalar_add(self, any_backend):
308 n = 301
309 v0 = Vector(MPI.comm_world, n)
310 v1 = Vector(MPI.comm_world, n)
311 v0[:] = -1.0
312 v0 += 2.0
313 assert v0.sum() == n
314 v0 -= 2.0
315 assert v0.sum() == -n
316 v0 = v0 + 3.0
317 assert v0.sum() == 2*n
318 v0 = v0 - 1.0
319 assert v0.sum() == n
320
321 def test_vector_subtract(self, any_backend):
322 n = 301
323 v0 = Vector(MPI.comm_world, n)
324 v1 = Vector(MPI.comm_world, n)
325 v0[:] = -1.0
326 v1[:] = 2.0
327 v0 -= v1
328 assert v0.sum() == -3.0*n
329
330 def test_vector_assignment(self, any_backend):
331 m, n = 301, 345
332 v0 = Vector(MPI.comm_world, m)
333 v1 = Vector(MPI.comm_world, n)
334 v0[:] = -1.0
335 v1[:] = 2.0
336 v0 = v1
337 assert v0.sum() == 2.0*n
338
339 def test_vector_assignment_length(self, any_backend):
340 # Test that assigning vectors of different lengths fails
341 m, n = 301, 345
342 v0 = Vector(MPI.comm_world, m)
343 v1 = Vector(MPI.comm_world, n)
344 def wrong_assignment(v0, v1):
345 v0[:] = v1
346 with pytest.raises(RuntimeError):
347 wrong_assignment(v0, v1)
348
349 def test_vector_assignment_length(self, any_backend):
350 # Test that assigning with diffrent parallel layouts fails
351 if MPI.size(MPI.comm_world) > 1:
352 m = 301
353 local_range0 = MPI.local_range(MPI.comm_world, m)
354 print("local range", local_range0[0], local_range0[1])
355
356 # Shift parallel partitiong but preserve global size
357 if MPI.rank(MPI.comm_world) == 0:
358 local_range1 = (local_range0[0], local_range0[1] + 1)
359 elif MPI.rank(MPI.comm_world) == MPI.size(MPI.comm_world) - 1:
360 local_range1 = (local_range0[0] + 1, local_range0[1])
361 else:
362 local_range1 = (local_range0[0] + 1, local_range0[1] + 1)
363
364 v0 = Vector(MPI.comm_world)
365 v0.init(local_range0)
366 v1 = Vector(MPI.comm_world)
367 v1.init(local_range1)
368 assert v0.size() == v1.size()
369
370 def wrong_assignment(v0, v1):
371 v0[:] = v1
372 with pytest.raises(RuntimeError):
373 wrong_assignment(v0, v1)
374
375
376 # Test the access of the raw data through pointers
377 # This is only available for Eigen backend
378 def test_vector_data(self, data_backend):
379 # Test for ordinary Vector
380 v = Vector(MPI.comm_world, 301)
381 v = as_backend_type(v)
382
383 rw_array = v.array_view()
384 assert rw_array.flags.owndata == False
385 with pytest.raises(Exception):
386 rw_array.resize([10])
387
388 # Check that the array is a writable view
389 rw_array[0] = 42
390 ro_array = v.get_local()
391 assert ro_array[0] == 42
392
393 # Test for as_backend_type Vector
394 v = as_backend_type(v)
395 rw_array2 = v.array_view()
396 assert (rw_array2 == ro_array).all()
397
398 # xfail on TypeError
399 xfail_type = pytest.mark.xfail(strict=True, raises=TypeError)
400 xfail_type_py3 = pytest.mark.xfail(strict=True, raises=TypeError)
401
•402 # some systems (32 bit arches) do not have numpy.float128
403 try:
404 test_float128 = numpy.float128(42.0)
405 except AttributeError:
406 test_float128 = numpy.longdouble(42.0)
407 @pytest.mark.parametrize("operand",
•408 [int(42), 42.0, numpy.sin(1.0), float(42.0),
409 numpy.float64(42.0),
410 int(42.0), c_long(42).value,
411 numpy.float16(42.0), numpy.float16(42.0),
•412 numpy.float32(42.0), test_float128,
413 numpy.longdouble(42.0), numpy.int8(42.0),
414 numpy.int16(42.0), numpy.int32(42.0),
415 numpy.intc(42.0), numpy.longdouble(42.0),
•416 numpy.intp(42.0), numpy.int64(42.0),
417 numpy.int_(42.0), numpy.longlong(42.0),
418 ])
419 def test_vector_type_priority_with_numpy(self, any_backend, operand):
420 """Test that DOLFIN return types are prefered over NumPy types for
421 binary operations on NumPy objects
422
423 """
424
425 def _test_binary_ops(v, operand):
426 assert isinstance(v + operand, cpp.la.GenericVector)
427 assert isinstance(v - operand, cpp.la.GenericVector)
428 assert isinstance(v*operand, cpp.la.GenericVector)
429 assert isinstance(v/operand, cpp.la.GenericVector)
430 assert isinstance(operand + v, cpp.la.GenericVector)
431 assert isinstance(operand - v, cpp.la.GenericVector)
432 assert isinstance(operand*v, cpp.la.GenericVector)
433 assert isinstance(v+v, cpp.la.GenericVector)
434 assert isinstance(v-v, cpp.la.GenericVector)
435 assert isinstance(v*v, cpp.la.GenericVector)
436 v += v.copy(); assert isinstance(v, cpp.la.GenericVector)
437 v -= v.copy(); assert isinstance(v, cpp.la.GenericVector)
438 v *= v.copy(); assert isinstance(v, cpp.la.GenericVector)
439 v += operand; assert isinstance(v, cpp.la.GenericVector)
440 v -= operand; assert isinstance(v, cpp.la.GenericVector)
441 v *= operand; assert isinstance(v, cpp.la.GenericVector)
442 v /= operand; assert isinstance(v, cpp.la.GenericVector)
443 op = copy(operand); op += v; assert isinstance(op, cpp.la.GenericVector)
444 op = copy(operand); op -= v; assert isinstance(op, cpp.la.GenericVector)
445 op = copy(operand); op *= v; assert isinstance(op, cpp.la.GenericVector)
446
447 # Test with vector wrapper
448 v = Vector(MPI.comm_world, 8)
449 _test_binary_ops(v, operand)
450
451 # Test with vector casted to backend type
452 v = as_backend_type(v)
453 _test_binary_ops(v, operand)