-
Notifications
You must be signed in to change notification settings - Fork 221
/
test_operator.py
1677 lines (1467 loc) · 65.4 KB
/
test_operator.py
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import pytest
from itertools import permutations
from conftest import skipif
from devito import (Grid, Eq, Operator, Constant, Function, TimeFunction,
SparseFunction, SparseTimeFunction, Dimension, error, SpaceDimension,
NODE, CELL, dimensions, configuration, TensorFunction,
TensorTimeFunction, VectorFunction, VectorTimeFunction)
from devito.ir.equations import ClusterizedEq
from devito.ir.iet import (Callable, Conditional, Expression, Iteration, FindNodes,
IsPerfectIteration, retrieve_iteration_tree)
from devito.ir.support import Any, Backward, Forward
from devito.passes.iet import DataManager
from devito.symbolics import ListInitializer, indexify, retrieve_indexed
from devito.tools import flatten, powerset
from devito.types import Array, Scalar
pytestmark = skipif(['yask', 'ops'])
def dimify(dimensions):
assert isinstance(dimensions, str)
return tuple(SpaceDimension(name=i) for i in dimensions.split())
def symbol(name, dimensions, value=0., shape=(3, 5), mode='function'):
"""Short-cut for symbol creation to test "function"
and "indexed" API."""
assert(mode in ['function', 'indexed'])
s = Function(name=name, dimensions=dimensions, shape=shape)
s.data_with_halo[:] = value
return s.indexify() if mode == 'indexed' else s
class TestCodeGen(object):
def test_parameters(self):
"""Tests code generation for Operator parameters."""
grid = Grid(shape=(3,))
a_dense = Function(name='a_dense', grid=grid)
const = Constant(name='constant')
eqn = Eq(a_dense, a_dense + 2.*const)
op = Operator(eqn, dle=('advanced', {'openmp': False}))
assert len(op.parameters) == 5
assert op.parameters[0].name == 'a_dense'
assert op.parameters[0].is_Tensor
assert op.parameters[1].name == 'constant'
assert op.parameters[1].is_Scalar
assert op.parameters[2].name == 'timers'
assert op.parameters[2].is_Object
assert op.parameters[3].name == 'x_M'
assert op.parameters[3].is_Scalar
assert op.parameters[4].name == 'x_m'
assert op.parameters[4].is_Scalar
assert 'a_dense[x + 1] = 2.0F*constant + a_dense[x + 1]' in str(op)
@pytest.mark.parametrize('expr, so, to, expected', [
('Eq(u.forward,u+1)', 0, 1, 'Eq(u[t+1,x,y,z],u[t,x,y,z]+1)'),
('Eq(u.forward,u+1)', 1, 1, 'Eq(u[t+1,x+1,y+1,z+1],u[t,x+1,y+1,z+1]+1)'),
('Eq(u.forward,u+1)', 1, 2, 'Eq(u[t+1,x+1,y+1,z+1],u[t,x+1,y+1,z+1]+1)'),
('Eq(u.forward,u+u.backward + m)', 8, 2,
'Eq(u[t+1,x+8,y+8,z+8],m[x,y,z]+u[t,x+8,y+8,z+8]+u[t-1,x+8,y+8,z+8])')
])
def test_index_shifting(self, expr, so, to, expected):
"""Tests that array accesses get properly shifted based on the halo and
padding regions extent."""
grid = Grid(shape=(4, 4, 4))
x, y, z = grid.dimensions
t = grid.stepping_dim # noqa
u = TimeFunction(name='u', grid=grid, space_order=so, time_order=to) # noqa
m = Function(name='m', grid=grid, space_order=0) # noqa
expr = eval(expr)
expr = Operator(expr)._specialize_exprs([indexify(expr)])[0]
assert str(expr).replace(' ', '') == expected
@pytest.mark.parametrize('expr,exp_uindices,exp_mods', [
('Eq(v.forward, u[0, x, y, z] + v + 1)', [(0, 5), (2, 5)], {'v': 5}),
('Eq(v.forward, u + v + 1)', [(0, 5), (2, 5), (0, 2)], {'v': 5, 'u': 2}),
])
def test_multiple_steppers(self, expr, exp_uindices, exp_mods):
"""Tests generation of multiple, mixed time stepping indices."""
grid = Grid(shape=(3, 3, 3))
x, y, z = grid.dimensions
u = TimeFunction(name='u', grid=grid) # noqa
v = TimeFunction(name='v', grid=grid, time_order=4) # noqa
op = Operator(eval(expr), dle='noop')
iters = FindNodes(Iteration).visit(op)
time_iter = [i for i in iters if i.dim.is_Time]
assert len(time_iter) == 1
time_iter = time_iter[0]
# Check uindices in Iteration header
signatures = [(i._offset, i._modulo) for i in time_iter.uindices]
assert len(signatures) == len(exp_uindices)
assert all(i in signatures for i in exp_uindices)
# Check uindices within each TimeFunction
exprs = [i.expr for i in FindNodes(Expression).visit(op)]
assert(i.indices[i.function._time_position].modulo == exp_mods[i.function.name]
for i in flatten(retrieve_indexed(i) for i in exprs))
class TestArithmetic(object):
@pytest.mark.parametrize('expr, result', [
('Eq(a, a + b + 5.)', 10.),
('Eq(a, b - a)', 1.),
('Eq(a, 4 * (b * a))', 24.),
('Eq(a, (6. / b) + (8. * a))', 18.),
])
@pytest.mark.parametrize('mode', ['function'])
def test_flat(self, expr, result, mode):
"""Tests basic point-wise arithmetic on two-dimensional data"""
i, j = dimify('i j')
a = symbol(name='a', dimensions=(i, j), value=2., mode=mode)
b = symbol(name='b', dimensions=(i, j), value=3., mode=mode)
fa = a.base.function if mode == 'indexed' else a
fb = b.base.function if mode == 'indexed' else b
eqn = eval(expr)
Operator(eqn)(a=fa, b=fb)
assert np.allclose(fa.data, result, rtol=1e-12)
@pytest.mark.parametrize('expr, result', [
('Eq(a, a + b + 5.)', 10.),
('Eq(a, b - a)', 1.),
('Eq(a, 4 * (b * a))', 24.),
('Eq(a, (6. / b) + (8. * a))', 18.),
])
@pytest.mark.parametrize('mode', ['function', 'indexed'])
def test_deep(self, expr, result, mode):
"""Tests basic point-wise arithmetic on multi-dimensional data"""
i, j, k, l = dimify('i j k l')
a = symbol(name='a', dimensions=(i, j, k, l), shape=(3, 5, 7, 6),
value=2., mode=mode)
b = symbol(name='b', dimensions=(j, k), shape=(5, 7),
value=3., mode=mode)
fa = a.base.function if mode == 'indexed' else a
fb = b.base.function if mode == 'indexed' else b
eqn = eval(expr)
Operator(eqn)(a=fa, b=fb)
assert np.allclose(fa.data, result, rtol=1e-12)
@pytest.mark.parametrize('expr, result', [
('Eq(a[j, l], a[j - 1 , l] + 1.)',
np.meshgrid(np.arange(2., 8.), np.arange(2., 7.))[1]),
('Eq(a[j, l], a[j, l - 1] + 1.)',
np.meshgrid(np.arange(2., 8.), np.arange(2., 7.))[0]),
])
def test_indexed_increment(self, expr, result):
"""Tests point-wise increments with stencil offsets in one dimension"""
j, l = dimify('j l')
a = symbol(name='a', dimensions=(j, l), value=1., shape=(5, 6),
mode='indexed').base
fa = a.function
fa.data[:] = 0.
eqn = eval(expr)
Operator(eqn)(a=fa)
assert np.allclose(fa.data, result, rtol=1e-12)
@pytest.mark.parametrize('expr, result', [
('Eq(a[j, l], b[j - 1 , l] + 1.)', np.zeros((5, 6)) + 3.),
('Eq(a[j, l], b[j , l - 1] + 1.)', np.zeros((5, 6)) + 3.),
('Eq(a[j, l], b[j - 1, l - 1] + 1.)', np.zeros((5, 6)) + 3.),
('Eq(a[j, l], b[j + 1, l + 1] + 1.)', np.zeros((5, 6)) + 3.),
])
def test_indexed_stencil(self, expr, result):
"""Test point-wise arithmetic with stencil offsets across two
functions in indexed expression format"""
j, l = dimify('j l')
a = symbol(name='a', dimensions=(j, l), value=0., shape=(5, 6),
mode='indexed').base
fa = a.function
b = symbol(name='b', dimensions=(j, l), value=2., shape=(5, 6),
mode='indexed').base
fb = b.function
eqn = eval(expr)
Operator(eqn)(a=fa, b=fb)
assert np.allclose(fa.data[1:-1, 1:-1], result[1:-1, 1:-1], rtol=1e-12)
@pytest.mark.parametrize('expr, result', [
('Eq(a[1, j, l], a[0, j - 1 , l] + 1.)', np.zeros((5, 6)) + 3.),
('Eq(a[1, j, l], a[0, j , l - 1] + 1.)', np.zeros((5, 6)) + 3.),
('Eq(a[1, j, l], a[0, j - 1, l - 1] + 1.)', np.zeros((5, 6)) + 3.),
('Eq(a[1, j, l], a[0, j + 1, l + 1] + 1.)', np.zeros((5, 6)) + 3.),
])
def test_indexed_buffered(self, expr, result):
"""Test point-wise arithmetic with stencil offsets across a single
functions with buffering dimension in indexed expression format"""
i, j, l = dimify('i j l')
a = symbol(name='a', dimensions=(i, j, l), value=2., shape=(3, 5, 6),
mode='indexed').base
fa = a.function
eqn = eval(expr)
Operator(eqn)(a=fa)
assert np.allclose(fa.data[1, 1:-1, 1:-1], result[1:-1, 1:-1], rtol=1e-12)
@pytest.mark.parametrize('expr, result', [
('Eq(a[1, j, l], a[0, j - 1 , l] + 1.)', np.zeros((5, 6)) + 3.),
])
def test_indexed_open_loops(self, expr, result):
"""Test point-wise arithmetic with stencil offsets and open loop
boundaries in indexed expression format"""
i, j, l = dimify('i j l')
a = Function(name='a', dimensions=(i, j, l), shape=(3, 5, 6))
fa = a.function
fa.data[0, :, :] = 2.
eqn = eval(expr)
Operator(eqn)(a=fa)
assert np.allclose(fa.data[1, 1:-1, 1:-1], result[1:-1, 1:-1], rtol=1e-12)
def test_indexed_w_indirections(self):
"""Test point-wise arithmetic with indirectly indexed Functions."""
grid = Grid(shape=(10, 10))
x, y = grid.dimensions
p_poke = Dimension('p_src')
d = Dimension('d')
npoke = 1
u = Function(name='u', grid=grid, space_order=0)
coordinates = Function(name='coordinates', dimensions=(p_poke, d),
shape=(npoke, grid.dim), space_order=0, dtype=np.int32)
coordinates.data[0, 0] = 4
coordinates.data[0, 1] = 3
poke_eq = Eq(u[coordinates[p_poke, 0], coordinates[p_poke, 1]], 1.0)
op = Operator(poke_eq)
op.apply()
ix, iy = np.where(u.data == 1.)
assert len(ix) == len(iy) == 1
assert ix[0] == 4 and iy[0] == 3
assert np.all(u.data[0:3] == 0.) and np.all(u.data[5:] == 0.)
assert np.all(u.data[:, 0:3] == 0.) and np.all(u.data[:, 5:] == 0.)
def test_constant_time_dense(self):
"""Test arithmetic between different data objects, namely Constant
and Function."""
i, j = dimify('i j')
const = Constant(name='truc', value=2.)
a = Function(name='a', shape=(20, 20), dimensions=(i, j))
a.data[:] = 2.
eqn = Eq(a, a + 2.*const)
op = Operator(eqn)
op.apply(a=a, truc=const)
assert(np.allclose(a.data, 6.))
# Applying a different constant still works
op.apply(a=a, truc=Constant(name='truc2', value=3.))
assert(np.allclose(a.data, 12.))
def test_incs_same_lhs(self):
"""Test point-wise arithmetic with multiple increments expressed
as different equations."""
grid = Grid(shape=(10, 10))
u = Function(name='u', grid=grid, space_order=0)
op = Operator([Eq(u, u+1.0), Eq(u, u+2.0)])
u.data[:] = 0.0
op.apply()
assert np.all(u.data[:] == 3)
def test_sparsefunction_inject(self):
"""
Test injection of a SparseFunction into a Function
"""
grid = Grid(shape=(11, 11))
u = Function(name='u', grid=grid, space_order=0)
sf1 = SparseFunction(name='s', grid=grid, npoint=1)
op = Operator(sf1.inject(u, expr=sf1))
assert sf1.data.shape == (1, )
sf1.coordinates.data[0, :] = (0.6, 0.6)
sf1.data[0] = 5.0
u.data[:] = 0.0
op.apply()
# This should be exactly on a point, all others 0
assert u.data[6, 6] == pytest.approx(5.0)
assert np.sum(u.data) == pytest.approx(5.0)
def test_sparsefunction_interp(self):
"""
Test interpolation of a SparseFunction from a Function
"""
grid = Grid(shape=(11, 11))
u = Function(name='u', grid=grid, space_order=0)
sf1 = SparseFunction(name='s', grid=grid, npoint=1)
op = Operator(sf1.interpolate(u))
assert sf1.data.shape == (1, )
sf1.coordinates.data[0, :] = (0.45, 0.45)
sf1.data[:] = 0.0
u.data[:] = 0.0
u.data[4, 4] = 4.0
op.apply()
# Exactly in the middle of 4 points, only 1 nonzero is 4
assert sf1.data[0] == pytest.approx(1.0)
def test_sparsetimefunction_interp(self):
"""
Test injection of a SparseTimeFunction into a TimeFunction
"""
grid = Grid(shape=(11, 11))
u = TimeFunction(name='u', grid=grid, time_order=2, save=5, space_order=0)
sf1 = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=5)
op = Operator(sf1.interpolate(u))
assert sf1.data.shape == (5, 1)
sf1.coordinates.data[0, :] = (0.45, 0.45)
sf1.data[:] = 0.0
u.data[:] = 0.0
u.data[:, 4, 4] = 8*np.arange(5)+4
# Because of time_order=2 this is probably the range we get anyway, but
# to be sure...
op.apply(time_m=1, time_M=3)
# Exactly in the middle of 4 points, only 1 nonzero is 4
assert np.all(sf1.data[:, 0] == pytest.approx([0.0, 3.0, 5.0, 7.0, 0.0]))
def test_sparsetimefunction_inject(self):
"""
Test injection of a SparseTimeFunction from a TimeFunction
"""
grid = Grid(shape=(11, 11))
u = TimeFunction(name='u', grid=grid, time_order=2, save=5, space_order=0)
sf1 = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=5)
op = Operator(sf1.inject(u, expr=3*sf1))
assert sf1.data.shape == (5, 1)
sf1.coordinates.data[0, :] = (0.45, 0.45)
sf1.data[:, 0] = np.arange(5)
u.data[:] = 0.0
# Because of time_order=2 this is probably the range we get anyway, but
# to be sure...
op.apply(time_m=1, time_M=3)
# Exactly in the middle of 4 points, only 1 nonzero is 4
assert np.all(u.data[1, 4:6, 4:6] == pytest.approx(0.75))
assert np.all(u.data[2, 4:6, 4:6] == pytest.approx(1.5))
assert np.all(u.data[3, 4:6, 4:6] == pytest.approx(2.25))
assert np.sum(u.data[:]) == pytest.approx(4*0.75+4*1.5+4*2.25)
def test_sparsetimefunction_inject_dt(self):
"""
Test injection of the time deivative of a SparseTimeFunction into a TimeFunction
"""
grid = Grid(shape=(11, 11))
u = TimeFunction(name='u', grid=grid, time_order=2, save=5, space_order=0)
sf1 = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=5, time_order=2)
# This should end up as a central difference operator
op = Operator(sf1.inject(u, expr=3*sf1.dt))
assert sf1.data.shape == (5, 1)
sf1.coordinates.data[0, :] = (0.45, 0.45)
sf1.data[:, 0] = np.arange(5)
u.data[:] = 0.0
# Because of time_order=2 this is probably the range we get anyway, but
# to be sure...
op.apply(time_m=1, time_M=3, dt=1)
# Exactly in the middle of 4 points, only 1 nonzero is 4
assert np.all(u.data[1:4, 4:6, 4:6] == pytest.approx(0.75))
assert np.sum(u.data[:]) == pytest.approx(12*0.75)
@pytest.mark.parametrize('func1', [TensorFunction, TensorTimeFunction,
VectorFunction, VectorTimeFunction])
def test_tensor(self, func1):
grid = Grid(tuple([5]*3))
f1 = func1(name="f1", grid=grid)
op1 = Operator(Eq(f1, f1.dx))
op2 = Operator([Eq(f, f.dx) for f in f1.values()])
assert str(op1.ccode) == str(op2.ccode)
class TestAllocation(object):
@pytest.mark.parametrize('shape', [(20, 20),
(20, 20, 20),
(20, 20, 20, 20)])
def test_first_touch(self, shape):
dimensions = dimify('i j k l')[:len(shape)]
grid = Grid(shape=shape, dimensions=dimensions)
m = Function(name='m', grid=grid, first_touch=True)
assert(np.allclose(m.data, 0))
m2 = Function(name='m2', grid=grid, first_touch=False)
assert(np.allclose(m2.data, 0))
assert(np.array_equal(m.data, m2.data))
@pytest.mark.parametrize('ndim', [2, 3])
def test_staggered(self, ndim):
"""
Test the "deformed" allocation for staggered functions
"""
grid = Grid(shape=tuple([11]*ndim))
for stagg in tuple(powerset(grid.dimensions))[1::] + (NODE, CELL):
f = Function(name='f', grid=grid, staggered=stagg)
assert f.data.shape == tuple([11]*ndim)
# Add a non-staggered field to ensure that the auto-derived
# dimension size arguments are at maximum
g = Function(name='g', grid=grid)
# Test insertion into a central point
index = tuple(5 for _ in f.dimensions)
set_f = Eq(f[index], 2.)
set_g = Eq(g[index], 3.)
Operator([set_f, set_g])()
assert f.data[index] == 2.
@pytest.mark.parametrize('ndim', [2, 3])
def test_staggered_time(self, ndim):
"""
Test the "deformed" allocation for staggered functions
"""
grid = Grid(shape=tuple([11]*ndim))
for stagg in tuple(powerset(grid.dimensions))[1::] + (NODE,):
f = TimeFunction(name='f', grid=grid, staggered=stagg)
assert f.data.shape[1:] == tuple([11]*ndim)
# Add a non-staggered field to ensure that the auto-derived
# dimension size arguments are at maximum
g = TimeFunction(name='g', grid=grid)
# Test insertion into a central point
index = tuple([0] + [5 for _ in f.dimensions[1:]])
set_f = Eq(f[index], 2.)
set_g = Eq(g[index], 3.)
Operator([set_f, set_g])()
assert f.data[index] == 2.
class TestArguments(object):
def verify_arguments(self, arguments, expected):
"""
Utility function to verify an argument dictionary against
expected values.
"""
for name, v in expected.items():
if isinstance(v, (Function, SparseFunction)):
condition = v._C_as_ndarray(arguments[name])[v._mask_domain] == v.data
condition = condition.all()
else:
condition = arguments[name] == v
if not condition:
error('Wrong argument %s: expected %s, got %s' %
(name, v, arguments[name]))
assert condition
def verify_parameters(self, parameters, expected):
"""
Utility function to verify a parameter set against expected
values.
"""
boilerplate = ['timers']
parameters = [p.name for p in parameters]
for exp in expected:
if exp not in parameters + boilerplate:
error("Missing parameter: %s" % exp)
assert exp in parameters + boilerplate
extra = [p for p in parameters if p not in expected and p not in boilerplate]
if len(extra) > 0:
error("Redundant parameters: %s" % str(extra))
assert len(extra) == 0
def test_default_functions(self):
"""
Test the default argument derivation for functions.
"""
grid = Grid(shape=(5, 6, 7))
f = TimeFunction(name='f', grid=grid)
g = Function(name='g', grid=grid)
op = Operator(Eq(f.forward, g + f), dle=('advanced', {'openmp': False}))
expected = {
'x_m': 0, 'x_M': 4,
'y_m': 0, 'y_M': 5,
'z_m': 0, 'z_M': 6,
'f': f, 'g': g,
}
self.verify_arguments(op.arguments(time=4), expected)
exp_parameters = ['f', 'g', 'x_m', 'x_M', 'y_m', 'y_M', 'z_m', 'z_M',
'x0_blk0_size', 'y0_blk0_size', 'time_m', 'time_M']
self.verify_parameters(op.parameters, exp_parameters)
def test_default_sparse_functions(self):
"""
Test the default argument derivation for composite functions.
"""
grid = Grid(shape=(5, 6, 7))
f = TimeFunction(name='f', grid=grid)
s = SparseTimeFunction(name='s', grid=grid, npoint=3, nt=4)
s.coordinates.data[:, 0] = np.arange(0., 3.)
s.coordinates.data[:, 1] = np.arange(1., 4.)
s.coordinates.data[:, 2] = np.arange(2., 5.)
op = Operator(s.interpolate(f))
expected = {
's': s, 's_coords': s.coordinates,
# Default dimensions of the sparse data
'p_s_size': 3, 'p_s_m': 0, 'p_s_M': 2,
'd_size': 3, 'd_m': 0, 'd_M': 2,
'time_size': 4, 'time_m': 0, 'time_M': 3,
}
self.verify_arguments(op.arguments(), expected)
def test_override_function_size(self):
"""
Test runtime size overrides for Function dimensions.
Note: The current behaviour for size-only arguments seems
ambiguous (eg. op(x=3, y=4), as it sets `dim_size` as well as
`dim_end`. Since `dim_size` is used for the cast, we can get
garbage results if it does not agree with the shape of the
provided data. This should error out, or potentially we could
set the corresponding size, while aliasing `dim` to `dim_e`?
The same should be tested for TimeFunction once fixed.
"""
grid = Grid(shape=(5, 6, 7))
g = Function(name='g', grid=grid)
op = Operator(Eq(g, 1.))
args = {'x': 3, 'y': 4, 'z': 5}
arguments = op.arguments(**args)
expected = {
'x_m': 0, 'x_M': 3,
'y_m': 0, 'y_M': 4,
'z_m': 0, 'z_M': 5,
'g': g
}
self.verify_arguments(arguments, expected)
# Verify execution
op(**args)
assert (g.data[4:] == 0.).all()
assert (g.data[:, 5:] == 0.).all()
assert (g.data[:, :, 6:] == 0.).all()
assert (g.data[:4, :5, :6] == 1.).all()
def test_override_function_subrange(self):
"""
Test runtime start/end override for Function dimensions.
"""
grid = Grid(shape=(5, 6, 7))
g = Function(name='g', grid=grid)
op = Operator(Eq(g, 1.))
args = {'x_m': 1, 'x_M': 3, 'y_m': 2, 'y_M': 4, 'z_m': 3, 'z_M': 5}
arguments = op.arguments(**args)
expected = {
'x_m': 1, 'x_M': 3,
'y_m': 2, 'y_M': 4,
'z_m': 3, 'z_M': 5,
'g': g
}
self.verify_arguments(arguments, expected)
# Verify execution
op(**args)
mask = np.ones((5, 6, 7), dtype=np.bool)
mask[1:4, 2:5, 3:6] = False
assert (g.data[mask] == 0.).all()
assert (g.data[1:4, 2:5, 3:6] == 1.).all()
def test_override_timefunction_subrange(self):
"""
Test runtime start/end overrides for TimeFunction dimensions.
"""
grid = Grid(shape=(5, 6, 7))
f = TimeFunction(name='f', grid=grid, time_order=0)
# Suppress DLE to work around a know bug with GCC and OpenMP:
# https://github.com/devitocodes/devito/issues/320
op = Operator(Eq(f, 1.), dle=None)
# TODO: Currently we require the `time` subrange to be set
# explicitly. Ideally `t` would directly alias with `time`,
# but this seems broken currently.
args = {'x_m': 1, 'x_M': 3, 'y_m': 2, 'y_M': 4,
'z_m': 3, 'z_M': 5, 't_m': 1, 't_M': 4}
arguments = op.arguments(**args)
expected = {
'x_m': 1, 'x_M': 3,
'y_m': 2, 'y_M': 4,
'z_m': 3, 'z_M': 5,
'time_m': 1, 'time_M': 4,
'f': f
}
self.verify_arguments(arguments, expected)
# Verify execution
op(**args)
mask = np.ones((1, 5, 6, 7), dtype=np.bool)
mask[:, 1:4, 2:5, 3:6] = False
assert (f.data[mask] == 0.).all()
assert (f.data[:, 1:4, 2:5, 3:6] == 1.).all()
def test_override_function_data(self):
"""
Test runtime data overrides for Function symbols.
"""
grid = Grid(shape=(5, 6, 7))
a = Function(name='a', grid=grid)
op = Operator(Eq(a, a + 3))
# Run with default value
a.data[:] = 1.
op()
assert (a.data[:] == 4.).all()
# Override with symbol (different name)
a1 = Function(name='a1', grid=grid)
a1.data[:] = 2.
op(a=a1)
assert (a1.data[:] == 5.).all()
# Override with symbol (same name as original)
a2 = Function(name='a', grid=grid)
a2.data[:] = 3.
op(a=a2)
assert (a2.data[:] == 6.).all()
# Override with user-allocated numpy data
a3 = np.zeros_like(a._data_allocated)
a3[:] = 4.
op(a=a3)
assert (a3[a._mask_domain] == 7.).all()
def test_override_timefunction_data(self):
"""
Test runtime data overrides for TimeFunction symbols.
"""
grid = Grid(shape=(5, 6, 7))
a = TimeFunction(name='a', grid=grid, save=2)
# Suppress DLE to work around a know bug with GCC and OpenMP:
# https://github.com/devitocodes/devito/issues/320
op = Operator(Eq(a, a + 3), dle=None)
# Run with default value
a.data[:] = 1.
op(time_m=0, time=1)
assert (a.data[:] == 4.).all()
# Override with symbol (different name)
a1 = TimeFunction(name='a1', grid=grid, save=2)
a1.data[:] = 2.
op(time_m=0, time=1, a=a1)
assert (a1.data[:] == 5.).all()
# Override with symbol (same name as original)
a2 = TimeFunction(name='a', grid=grid, save=2)
a2.data[:] = 3.
op(time_m=0, time=1, a=a2)
assert (a2.data[:] == 6.).all()
# Override with user-allocated numpy data
a3 = np.zeros_like(a._data_allocated)
a3[:] = 4.
op(time_m=0, time=1, a=a3)
assert (a3[a._mask_domain] == 7.).all()
def test_dimension_size_infer(self, nt=100):
"""Test that the dimension sizes are being inferred correctly"""
grid = Grid(shape=(3, 5, 7))
a = Function(name='a', grid=grid)
b = TimeFunction(name='b', grid=grid, save=nt)
op = Operator(Eq(b, a))
time = b.indices[0]
op_arguments = op.arguments()
assert(op_arguments[time.min_name] == 0)
assert(op_arguments[time.max_name] == nt-1)
def test_dimension_offset_adjust(self, nt=100):
"""Test that the dimension sizes are being inferred correctly"""
i, j, k = dimify('i j k')
shape = (10, 10, 10)
grid = Grid(shape=shape, dimensions=(i, j, k))
a = Function(name='a', grid=grid)
b = TimeFunction(name='b', grid=grid, save=nt)
time = b.indices[0]
eqn = Eq(b[time + 1, i, j, k], b[time - 1, i, j, k]
+ b[time, i, j, k] + a[i, j, k])
op = Operator(eqn)
op_arguments = op.arguments(time=nt-10)
assert(op_arguments[time.min_name] == 1)
assert(op_arguments[time.max_name] == nt - 10)
def test_dimension_size_override(self):
"""Test explicit overrides for the leading time dimension"""
grid = Grid(shape=(3, 5, 7))
a = TimeFunction(name='a', grid=grid)
one = Function(name='one', grid=grid)
one.data[:] = 1.
op = Operator(Eq(a.forward, a + one))
# Test dimension override via the buffered dimenions
a.data[0] = 0.
op(a=a, t=5)
assert(np.allclose(a.data[1], 5.))
# Test dimension override via the parent dimenions
a.data[0] = 0.
op(a=a, time=4)
assert(np.allclose(a.data[0], 4.))
def test_override_sparse_data_fix_dim(self):
"""
Ensure the arguments are derived correctly for an input SparseFunction.
The dimensions are forced to be the same in this case to verify
the aliasing on the SparseFunction name.
"""
grid = Grid(shape=(10, 10))
time = grid.time_dim
u = TimeFunction(name='u', grid=grid, time_order=2, space_order=2)
original_coords = (1., 1.)
new_coords = (2., 2.)
p_dim = Dimension(name='p_src')
src1 = SparseTimeFunction(name='src1', grid=grid, dimensions=(time, p_dim), nt=10,
npoint=1, coordinates=original_coords, time_order=2)
src2 = SparseTimeFunction(name='src2', grid=grid, dimensions=(time, p_dim),
npoint=1, nt=10, coordinates=new_coords, time_order=2)
op = Operator(src1.inject(u, src1))
# Move the source from the location where the setup put it so we can test
# whether the override picks up the original coordinates or the changed ones
args = op.arguments(src1=src2, time=0)
arg_name = src1.coordinates._arg_names[0]
assert(np.array_equal(src2.coordinates._C_as_ndarray(args[arg_name]),
np.asarray((new_coords,))))
def test_override_sparse_data_default_dim(self):
"""
Ensure the arguments are derived correctly for an input SparseFunction.
The dimensions are the defaults (name dependant 'p_name') in this case to verify
the aliasing on the SparseFunction coordinates and dimensions.
"""
grid = Grid(shape=(10, 10))
original_coords = (1., 1.)
new_coords = (2., 2.)
u = TimeFunction(name='u', grid=grid, time_order=2, space_order=2)
src1 = SparseTimeFunction(name='src1', grid=grid, npoint=1, nt=10,
coordinates=original_coords, time_order=2)
src2 = SparseTimeFunction(name='src2', grid=grid, npoint=1, nt=10,
coordinates=new_coords, time_order=2)
op = Operator(src1.inject(u, src1))
# Move the source from the location where the setup put it so we can test
# whether the override picks up the original coordinates or the changed ones
args = op.arguments(src1=src2, t=0)
arg_name = src1.coordinates._arg_names[0]
assert(np.array_equal(src2.coordinates._C_as_ndarray(args[arg_name]),
np.asarray((new_coords,))))
def test_argument_derivation_order(self, nt=100):
""" Ensure the precedence order of arguments is respected
Defaults < (overriden by) Tensor Arguments < Dimensions < Scalar Arguments
"""
i, j, k = dimify('i j k')
shape = (10, 10, 10)
grid = Grid(shape=shape, dimensions=(i, j, k))
a = Function(name='a', grid=grid)
b = TimeFunction(name='b', grid=grid, save=nt)
time = b.indices[0]
op = Operator(Eq(b, a))
# Simple case, same as that tested above.
# Repeated here for clarity of further tests.
op_arguments = op.arguments()
assert(op_arguments[time.min_name] == 0)
assert(op_arguments[time.max_name] == nt-1)
# Providing a tensor argument should infer the dimension size from its shape
b1 = TimeFunction(name='b1', grid=grid, save=nt+1)
op_arguments = op.arguments(b=b1)
assert(op_arguments[time.min_name] == 0)
assert(op_arguments[time.max_name] == nt)
# Providing a dimension size explicitly should override the automatically inferred
op_arguments = op.arguments(b=b1, time=nt - 1)
assert(op_arguments[time.min_name] == 0)
assert(op_arguments[time.max_name] == nt - 1)
# Providing a scalar argument explicitly should override the automatically
# inferred
op_arguments = op.arguments(b=b1, time_M=nt - 2)
assert(op_arguments[time.min_name] == 0)
assert(op_arguments[time.max_name] == nt - 2)
def test_derive_constant_value(self):
"""Ensure that values for Constant symbols are derived correctly."""
grid = Grid(shape=(5, 6))
f = Function(name='f', grid=grid)
a = Constant(name='a', value=3.)
Operator(Eq(f, a))()
assert np.allclose(f.data, 3.)
g = Function(name='g', grid=grid)
b = Constant(name='b')
op = Operator(Eq(g, b))
b.data = 4.
op()
assert np.allclose(g.data, 4.)
def test_argument_from_index_constant(self):
nx, ny = 30, 30
grid = Grid(shape=(nx, ny))
x, y = grid.dimensions
arbdim = Dimension('arb')
u = TimeFunction(name='u', grid=grid, save=None, time_order=2, space_order=0)
snap = Function(name='snap', dimensions=(arbdim, x, y), shape=(5, nx, ny),
space_order=0)
save_t = Constant(name='save_t', dtype=np.int32)
save_slot = Constant(name='save_slot', dtype=np.int32)
expr = Eq(snap.subs(arbdim, save_slot), u.subs(grid.stepping_dim, save_t))
op = Operator(expr)
u.data[:] = 0.0
snap.data[:] = 0.0
u.data[0, 10, 10] = 1.0
op.apply(save_t=0, save_slot=1)
assert snap.data[1, 10, 10] == 1.0
def test_argument_no_shifting(self):
"""Tests that there's no shifting in the written-to region when
iteration bounds are prescribed."""
grid = Grid(shape=(11, 11))
x, y = grid.dimensions
a = Function(name='a', grid=grid)
a.data[:] = 1.
# Try with an operator w/o stencil offsets
op = Operator(Eq(a, a + a))
op(x_m=3, x_M=7)
assert (a.data[:3, :] == 1.).all()
assert (a.data[3:7, :] == 2.).all()
assert (a.data[8:, :] == 1.).all()
# Try with an operator w/ stencil offsets
a.data[:] = 1.
op = Operator(Eq(a, a + (a[x-1, y] + a[x+1, y]) / 2.))
op(x_m=3, x_M=7)
assert (a.data[:3, :] == 1.).all()
assert (a.data[3:7, :] >= 2.).all()
assert (a.data[8:, :] == 1.).all()
def test_argument_unknown(self):
"""Check that Operators deal with unknown runtime arguments."""
grid = Grid(shape=(11, 11))
a = Function(name='a', grid=grid)
op = Operator(Eq(a, a + a))
try:
op.apply(b=3)
assert False
except ValueError:
# `b` means nothing to `op`, so we end up here
assert True
try:
configuration['ignore-unknowns'] = True
op.apply(b=3)
assert True
except ValueError:
# we should not end up here as we're now ignoring unknown arguments
assert False
finally:
configuration['ignore-unknowns'] = configuration._defaults['ignore-unknowns']
@pytest.mark.parametrize('so,to,pad,expected', [
(0, 1, 0, (2, 4, 4, 4)),
(2, 1, 0, (2, 8, 8, 8)),
(4, 1, 0, (2, 12, 12, 12)),
(4, 3, 0, (4, 12, 12, 12)),
(4, 1, 3, (2, 15, 15, 15)),
((2, 5, 2), 1, 0, (2, 11, 11, 11)),
((2, 5, 4), 1, 3, (2, 16, 16, 16)),
])
def test_function_dataobj(self, so, to, pad, expected):
"""
Tests that the C-level structs from DiscreteFunctions are properly
populated upon application of an Operator.
"""
grid = Grid(shape=(4, 4, 4))
u = TimeFunction(name='u', grid=grid, space_order=so, time_order=to, padding=pad)
op = Operator(Eq(u, 1), dse='noop', dle='noop')
u_arg = op.arguments(time=0)['u']
u_arg_shape = tuple(u_arg._obj.size[i] for i in range(u.ndim))
assert u_arg_shape == expected
def test_illegal_override(self):
grid0 = Grid(shape=(11, 11))
grid1 = Grid(shape=(13, 13))
a0 = Function(name='a', grid=grid0)
b0 = Function(name='b', grid=grid0)
a1 = Function(name='a', grid=grid1)
op = Operator(Eq(a0, a0 + b0 + 1))
op.apply()
try:
op.apply(a=a1, b=b0)
assert False
except ValueError as e:
assert 'Override' in e.args[0] # Check it's hitting the right error msg
except:
assert False
def test_incomplete_override(self):
"""
Simulate a typical user error when one has to supply replacements for lots
of Functions (a complex Operator) but at least one is forgotten.
"""
grid0 = Grid(shape=(11, 11))
grid1 = Grid(shape=(13, 13))
a0 = Function(name='a', grid=grid0)
a1 = Function(name='a', grid=grid1)
b = Function(name='b', grid=grid0)
op = Operator(Eq(a0, a0 + b + 1))
op.apply()
try:
op.apply(a=a1)
assert False
except ValueError as e:
assert 'Default' in e.args[0] # Check it's hitting the right error msg
except:
assert False
@skipif('nompi')
@pytest.mark.parallel(mode=1)
def test_new_distributor(self):
"""
Test that `comm` and `nb` are correctly updated when a different distributor
from that it was originally built with is required by an operator.
Note that MPI is required to ensure `comm` and `nb` are included in op.objects.
"""
from devito.mpi import MPI
grid = Grid(shape=(10, 10), comm=MPI.COMM_SELF)
grid2 = Grid(shape=(10, 10), comm=MPI.COMM_WORLD)
u = TimeFunction(name='u', grid=grid, space_order=2)
u2 = TimeFunction(name='u2', grid=grid2, space_order=2)
# Create some operator that requires MPI communication
eqn = Eq(u.forward, u + u.laplace)
op = Operator(eqn)
assert op.arguments(u=u, time_M=0)['comm'] is grid.distributor._obj_comm.value
assert (op.arguments(u=u, time_M=0)['nb'] is
grid.distributor._obj_neighborhood.value)
assert op.arguments(u=u2, time_M=0)['comm'] is grid2.distributor._obj_comm.value
assert (op.arguments(u=u2, time_M=0)['nb'] is
grid2.distributor._obj_neighborhood.value)
class TestDeclarator(object):
def test_heap_1D_stencil(self):
i, j = dimensions('i j')
a = Array(name='a', dimensions=(i,))
b = Array(name='b', dimensions=(i,))
f = Function(name='f', shape=(3,), dimensions=(j,))
operator = Operator([Eq(a[i], a[i] + b[i] + 5.), Eq(f[j], a[j])],
dse='noop', dle=None)
assert """\
float (*a);
posix_memalign((void**)&a, 64, sizeof(float[i_size]));