File: test_vector.py

package info (click to toggle)
dolfin 2019.2.0~git20201207.b495043-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 30,988 kB
  • sloc: xml: 104,040; cpp: 102,020; python: 24,139; makefile: 300; javascript: 226; sh: 185
file content (452 lines) | stat: -rwxr-xr-x 15,636 bytes parent folder | download
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
"""Unit tests for the Vector interface"""

# Copyright (C) 2011-2014 Garth N. Wells
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# Modified by Anders Logg 2011

import pytest
import numpy
from copy import copy

from dolfin import *
from dolfin_utils.test import *

# TODO: Use the fixture setup from matrix in a shared conftest.py when
#       we move tests to one flat folder.

# Lists of backends supporting or not supporting GenericVector::data()
# access
data_backends = []
no_data_backends = ["PETSc", "Tpetra"]

# Add serial only backends
if MPI.size(MPI.comm_world) == 1:
    # TODO: What about "Dense" and "Sparse"? The sub_backend wasn't
    # used in the old test.
    data_backends += ["Eigen"]

# Remove backends we haven't built with
data_backends = list(filter(has_linear_algebra_backend, data_backends))
no_data_backends = list(filter(has_linear_algebra_backend, no_data_backends))
any_backends = data_backends + no_data_backends

# Fixtures setting up and resetting the global linear algebra backend
# for a list of backends
data_backend = set_parameters_fixture("linear_algebra_backend", data_backends)
no_data_backend = set_parameters_fixture("linear_algebra_backend",
                                         no_data_backends)
any_backend = set_parameters_fixture("linear_algebra_backend", any_backends)

class TestVectorForAnyBackend:

    def test_create_empty_vector(self, any_backend):
        v0 = Vector()
        info(v0)
        info(v0, True)
        assert v0.size() == 0

    def test_create_vector(self, any_backend):
        n = 301
        v1 = Vector(MPI.comm_world, n)
        assert v1.size() == n

    def test_copy_vector(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v1 = Vector(v0)
        assert v0.size() == n
        del v0
        assert v1.size() == n

    def test_assign_and_copy_vector(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = 1.0
        assert v0.sum() == n
        v1 = Vector(v0)
        del v0
        assert v1.sum() == n

    def test_zero(self, any_backend):
        v0 = Vector(MPI.comm_world, 301)
        v0.zero()
        assert v0.sum() == 0.0

    def test_apply(self, any_backend):
        v0 = Vector(MPI.comm_world, 301)
        v0.apply("insert")
        v0.apply("add")

    def test_str(self, any_backend):
        v0 = Vector(MPI.comm_world, 13)
        tmp = v0.str(False)
        tmp = v0.str(True)

    def test_init_range(self, any_backend):
        n = 301
        local_range = MPI.local_range(MPI.comm_world, n)
        v0 = Vector(MPI.comm_world)
        v0.init(local_range)
        assert v0.local_range() == local_range

    def test_size(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, 301)
        assert v0.size() == n

    def test_local_size(self, any_backend):
        n = 301
        local_range = MPI.local_range(MPI.comm_world, n)
        v0 = Vector(MPI.comm_world)
        v0.init(local_range)
        assert v0.local_size() == local_range[1] - local_range[0]

    def test_owns_index(self, any_backend):
        m, n = 301, 25
        v0 = Vector(MPI.comm_world, m)
        local_range = v0.local_range()
        in_range = local_range[0] <= n < local_range[1]
        assert v0.owns_index(n) == in_range

    #def test_set(self, any_backend):

    #def test_add(self, any_backend):

    def test_get_local(self, any_backend):
        from numpy import empty
        n = 301
        v0 = Vector(MPI.comm_world, n)
        data = v0.get_local()

    def test_set_local(self, any_backend):
        from numpy import zeros
        n = 301
        v0 = Vector(MPI.comm_world, n)
        data = zeros((v0.local_size()), dtype='d')
        v0.set_local(data)
        data = zeros((v0.local_size()*2), dtype='d')

    def test_add_local(self, any_backend):
        from numpy import zeros
        n = 301
        v0 = Vector(MPI.comm_world, n)
        data = zeros((v0.local_size()), dtype='d')
        v0.add_local(data)
        data = zeros((v0.local_size()*2), dtype='d')

    def test_gather(self, any_backend):
        # Gather not implemented in Eigen
        if any_backend == "Eigen" or any_backend == "Tpetra":
            return

        # Create distributed vector of local size 1
        x = DefaultFactory().create_vector(MPI.comm_world)
        r = MPI.rank(x.mpi_comm())
        x.init((r, r+1))

        # Create local vector
        y = DefaultFactory().create_vector(MPI.comm_self)

        # Do the actual test across all rank permutations
        for target_rank in range(MPI.size(x.mpi_comm())):

            # Set nonzero value on single rank
            if r == target_rank:
                x[0] = 42.0  # Set using local index
            else:
                x[0] = 0.0  # Set using local index
            assert numpy.isclose(x.sum(), 42.0)

            # Gather (using global index) and check the result
            x.gather(y, numpy.array([target_rank], dtype=la_index_dtype()))
            assert numpy.isclose(y[0], 42.0)

            # NumPy array version
            out = x.gather(numpy.array([target_rank], dtype=la_index_dtype()))
            assert out.shape == (1,) and numpy.isclose(out[0], 42.0)

            # Test gather on zero
            out = x.gather_on_zero()
            if r == 0:
                expected = numpy.array([42.0 if i == target_rank else 0.0
                                        for i in range(x.size())])
            else:
                expected = numpy.array([])
            assert out.shape == expected.shape and numpy.allclose(out, expected)

            # Test also the corner case of empty indices on one process
            if r == target_rank:
                out = x.gather(numpy.array([], dtype=la_index_dtype()))
                expected = numpy.array([])
            else:
                out = x.gather(numpy.array([target_rank], dtype=la_index_dtype()))
                expected = numpy.array([42.0])
            assert out.shape == expected.shape and numpy.allclose(out, expected)

        # Check that distributed gather vector is not accepted
        if MPI.size(MPI.comm_world) > 1:
            z = DefaultFactory().create_vector(MPI.comm_world)
            with pytest.raises(RuntimeError):
                x.gather(z, numpy.array([0], dtype=la_index_dtype()))

        # Check that gather vector of wrong size is not accepted
        z = DefaultFactory().create_vector(MPI.comm_self)
        z.init(3)
        with pytest.raises(RuntimeError):
            x.gather(z, numpy.array([0], dtype=la_index_dtype()))

    def test_axpy(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = 1.0
        v1 = Vector(v0)
        v0.axpy(2.0, v1)
        assert v0.sum() == 2*n + n

    def test_abs(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v0.abs()
        assert v0.sum() == n

    def test_inner(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = 2.0
        v1 = Vector(MPI.comm_world, n)
        v1[:] = 3.0
        assert v0.inner(v1) == 6*n

    def test_norm(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = -2.0
        assert v0.norm("l1") == 2.0*n
        assert v0.norm("l2") == sqrt(4.0*n)
        assert v0.norm("linf") == 2.0

    def test_min(self, any_backend):
        v0 = Vector(MPI.comm_world, 301)
        v0[:] = 2.0
        assert v0.min() == 2.0

    def test_max(self, any_backend):
        v0 = Vector(MPI.comm_world,301)
        v0[:] = -2.0
        assert v0.max() == -2.0

    def test_sum(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = -2.0
        assert v0.sum() == -2.0*n

    def test_sum_entries(self, any_backend):
        from numpy import zeros
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = -2.0
        entries = zeros(5, dtype='uintp')
        assert v0.sum(entries) == -2.0
        entries[0] = 2
        entries[1] = 1
        entries[2] = 236
        entries[3] = 123
        entries[4] = 97
        assert v0.sum(entries) == -2.0*5

    def test_scalar_mult(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v0 *= 2.0
        assert v0.sum() == -2.0*n

    def test_vector_element_mult(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v1 = Vector(MPI.comm_world, n)
        v0[:] = -2.0
        v1[:] =  3.0
        v0 *= v1
        assert v0.sum() == -6.0*n

    def test_scalar_divide(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v0 /= -2.0
        assert v0.sum() == 0.5*n

    def test_vector_add(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v1 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v1[:] =  2.0
        v0 += v1
        assert v0.sum() == n

    def test_scalar_add(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v1 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v0 += 2.0
        assert v0.sum() == n
        v0 -= 2.0
        assert v0.sum() == -n
        v0 = v0 + 3.0
        assert v0.sum() == 2*n
        v0 = v0 - 1.0
        assert v0.sum() == n

    def test_vector_subtract(self, any_backend):
        n = 301
        v0 = Vector(MPI.comm_world, n)
        v1 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v1[:] =  2.0
        v0 -= v1
        assert v0.sum() == -3.0*n

    def test_vector_assignment(self, any_backend):
        m, n = 301, 345
        v0 = Vector(MPI.comm_world, m)
        v1 = Vector(MPI.comm_world, n)
        v0[:] = -1.0
        v1[:] =  2.0
        v0 = v1
        assert v0.sum() == 2.0*n

    def test_vector_assignment_length(self, any_backend):
        # Test that assigning vectors of different lengths fails
        m, n = 301, 345
        v0 = Vector(MPI.comm_world, m)
        v1 = Vector(MPI.comm_world, n)
        def wrong_assignment(v0, v1):
            v0[:] = v1
        with pytest.raises(RuntimeError):
            wrong_assignment(v0, v1)

    def test_vector_assignment_length(self, any_backend):
        # Test that assigning with diffrent parallel layouts fails
        if MPI.size(MPI.comm_world) > 1:
            m = 301
            local_range0 = MPI.local_range(MPI.comm_world, m)
            print("local range", local_range0[0], local_range0[1])

            # Shift parallel partitiong but preserve global size
            if MPI.rank(MPI.comm_world) == 0:
                local_range1 = (local_range0[0], local_range0[1] + 1)
            elif MPI.rank(MPI.comm_world) == MPI.size(MPI.comm_world) - 1:
                local_range1 = (local_range0[0] + 1, local_range0[1])
            else:
                local_range1 = (local_range0[0] + 1, local_range0[1] + 1)

            v0 = Vector(MPI.comm_world)
            v0.init(local_range0)
            v1 = Vector(MPI.comm_world)
            v1.init(local_range1)
            assert v0.size() == v1.size()

            def wrong_assignment(v0, v1):
                v0[:] = v1
                with pytest.raises(RuntimeError):
                    wrong_assignment(v0, v1)


    # Test the access of the raw data through pointers
    # This is only available for Eigen backend
    def test_vector_data(self, data_backend):
        # Test for ordinary Vector
        v = Vector(MPI.comm_world, 301)
        v = as_backend_type(v)

        rw_array = v.array_view()
        assert rw_array.flags.owndata == False
        with pytest.raises(Exception):
            rw_array.resize([10])

        # Check that the array is a writable view
        rw_array[0] = 42
        ro_array = v.get_local()
        assert ro_array[0] == 42

        # Test for as_backend_type Vector
        v = as_backend_type(v)
        rw_array2 = v.array_view()
        assert (rw_array2 == ro_array).all()

    # xfail on TypeError
    xfail_type = pytest.mark.xfail(strict=True, raises=TypeError)
    xfail_type_py3 = pytest.mark.xfail(strict=True, raises=TypeError)

    # some systems (32 bit arches) do not have numpy.float128
    try:
        test_float128 = numpy.float128(42.0)
    except AttributeError:
        test_float128 = numpy.longdouble(42.0)
    @pytest.mark.parametrize("operand",
                             [int(42), 42.0, numpy.sin(1.0), numpy.float(42.0),
                                numpy.float64(42.0), numpy.float_(42.0),
                                numpy.int(42.0), numpy.long(42.0),
                                numpy.float16(42.0), numpy.float16(42.0),
                                numpy.float32(42.0), test_float128,
                                numpy.longfloat(42.0), numpy.int8(42.0),
                                numpy.int16(42.0), numpy.int32(42.0),
                                numpy.intc(42.0), numpy.longdouble(42.0),
                                numpy.int0(42.0), numpy.int64(42.0),
                                numpy.int_(42.0), numpy.longlong(42.0),
                             ])
    def test_vector_type_priority_with_numpy(self, any_backend, operand):
        """Test that DOLFIN return types are prefered over NumPy types for
        binary operations on NumPy objects

        """

        def _test_binary_ops(v, operand):
            assert isinstance(v + operand, cpp.la.GenericVector)
            assert isinstance(v - operand, cpp.la.GenericVector)
            assert isinstance(v*operand, cpp.la.GenericVector)
            assert isinstance(v/operand, cpp.la.GenericVector)
            assert isinstance(operand + v, cpp.la.GenericVector)
            assert isinstance(operand - v, cpp.la.GenericVector)
            assert isinstance(operand*v, cpp.la.GenericVector)
            assert isinstance(v+v, cpp.la.GenericVector)
            assert isinstance(v-v, cpp.la.GenericVector)
            assert isinstance(v*v, cpp.la.GenericVector)
            v += v.copy(); assert isinstance(v, cpp.la.GenericVector)
            v -= v.copy(); assert isinstance(v, cpp.la.GenericVector)
            v *= v.copy(); assert isinstance(v, cpp.la.GenericVector)
            v += operand; assert isinstance(v, cpp.la.GenericVector)
            v -= operand; assert isinstance(v, cpp.la.GenericVector)
            v *= operand; assert isinstance(v, cpp.la.GenericVector)
            v /= operand; assert isinstance(v, cpp.la.GenericVector)
            op = copy(operand); op += v; assert isinstance(op, cpp.la.GenericVector)
            op = copy(operand); op -= v; assert isinstance(op, cpp.la.GenericVector)
            op = copy(operand); op *= v; assert isinstance(op, cpp.la.GenericVector)

        # Test with vector wrapper
        v = Vector(MPI.comm_world, 8)
        _test_binary_ops(v, operand)

        # Test with vector casted to backend type
        v = as_backend_type(v)
        _test_binary_ops(v, operand)