-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtest_arraycontext.py
1534 lines (1102 loc) · 45.5 KB
/
test_arraycontext.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
from __future__ import annotations
__copyright__ = "Copyright (C) 2020-21 University of Illinois Board of Trustees"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import logging
from dataclasses import dataclass
from functools import partial
import numpy as np
import pytest
from pytools.obj_array import make_obj_array
from pytools.tag import Tag
from arraycontext import (
BcastUntilActxArray,
EagerJAXArrayContext,
NumpyArrayContext,
PyOpenCLArrayContext,
PytatoPyOpenCLArrayContext,
dataclass_array_container,
pytest_generate_tests_for_array_contexts,
serialize_container,
tag_axes,
with_container_arithmetic,
)
from arraycontext.pytest import (
_PytestEagerJaxArrayContextFactory,
_PytestNumpyArrayContextFactory,
_PytestPyOpenCLArrayContextFactoryWithClass,
_PytestPytatoJaxArrayContextFactory,
_PytestPytatoPyOpenCLArrayContextFactory,
)
from testlib import DOFArray, MyContainer, MyContainerDOFBcast, Velocity2D
logger = logging.getLogger(__name__)
# {{{ array context fixture
class _PyOpenCLArrayContextForTests(PyOpenCLArrayContext):
"""Like :class:`PyOpenCLArrayContext`, but applies no program transformations
whatsoever. Only to be used for testing internal to :mod:`arraycontext`.
"""
def transform_loopy_program(self, t_unit):
return t_unit
class _PytatoPyOpenCLArrayContextForTests(PytatoPyOpenCLArrayContext):
"""Like :class:`PytatoPyOpenCLArrayContext`, but applies no program
transformations whatsoever. Only to be used for testing internal to
:mod:`arraycontext`.
"""
def transform_loopy_program(self, t_unit):
return t_unit
class _PyOpenCLArrayContextWithHostScalarsForTestsFactory(
_PytestPyOpenCLArrayContextFactoryWithClass):
actx_class = _PyOpenCLArrayContextForTests
class _PyOpenCLArrayContextForTestsFactory(
_PyOpenCLArrayContextWithHostScalarsForTestsFactory):
force_device_scalars = True
class _PytatoPyOpenCLArrayContextForTestsFactory(
_PytestPytatoPyOpenCLArrayContextFactory):
actx_class = _PytatoPyOpenCLArrayContextForTests
pytest_generate_tests = pytest_generate_tests_for_array_contexts([
_PyOpenCLArrayContextForTestsFactory,
_PyOpenCLArrayContextWithHostScalarsForTestsFactory,
_PytatoPyOpenCLArrayContextForTestsFactory,
_PytestEagerJaxArrayContextFactory,
_PytestPytatoJaxArrayContextFactory,
_PytestNumpyArrayContextFactory,
])
def _acf():
import pyopencl as cl
context = cl._csc()
queue = cl.CommandQueue(context)
return _PyOpenCLArrayContextForTests(queue, force_device_scalars=True)
# }}}
def _get_test_containers(actx, ambient_dim=2, shapes=50_000):
from numbers import Number
from testlib import DOFArray, MyContainer, MyContainerDOFBcast
if isinstance(shapes, Number | tuple):
shapes = [shapes]
x = DOFArray(actx, tuple(actx.from_numpy(randn(shape, np.float64))
for shape in shapes))
# pylint: disable=unexpected-keyword-arg, no-value-for-parameter
dataclass_of_dofs = MyContainer(
name="container",
mass=x,
momentum=make_obj_array([x] * ambient_dim),
enthalpy=x)
# pylint: disable=unexpected-keyword-arg, no-value-for-parameter
bcast_dataclass_of_dofs = MyContainerDOFBcast(
name="container",
mass=x,
momentum=make_obj_array([x] * ambient_dim),
enthalpy=x)
ary_dof = x
ary_of_dofs = make_obj_array([x] * ambient_dim)
mat_of_dofs = np.empty((ambient_dim, ambient_dim), dtype=object)
for i in np.ndindex(mat_of_dofs.shape):
mat_of_dofs[i] = x
return (ary_dof, ary_of_dofs, mat_of_dofs, dataclass_of_dofs,
bcast_dataclass_of_dofs)
# {{{ assert_close_to_numpy*
def randn(shape, dtype):
rng = np.random.default_rng()
dtype = np.dtype(dtype)
ashape = 1 if shape == 0 else shape
if dtype.kind == "c":
dtype = np.dtype(f"<f{dtype.itemsize // 2}")
r = rng.standard_normal(ashape, dtype) \
+ 1j * rng.standard_normal(ashape, dtype)
elif dtype.kind == "f":
r = rng.standard_normal(ashape, dtype)
elif dtype.kind == "i":
r = rng.integers(0, 512, ashape, dtype)
else:
raise TypeError(dtype.kind)
if shape == 0:
return np.array(r[0])
return r
def assert_close_to_numpy(actx, op, args):
assert np.allclose(
actx.to_numpy(
op(actx.np, *[
actx.from_numpy(arg) if isinstance(arg, np.ndarray) else arg
for arg in args])),
op(np, *args))
def assert_close_to_numpy_in_containers(actx, op, args):
assert_close_to_numpy(actx, op, args)
ref_result = op(np, *args)
# {{{ test DOFArrays
dofarray_args = [
DOFArray(actx, (actx.from_numpy(arg),))
if isinstance(arg, np.ndarray) else arg
for arg in args]
actx_result = op(actx.np, *dofarray_args)
if isinstance(actx_result, DOFArray):
actx_result = actx_result[0]
assert np.allclose(actx.to_numpy(actx_result), ref_result)
# }}}
# {{{ test object arrays of DOFArrays
obj_array_args = [
make_obj_array([arg]) if isinstance(arg, DOFArray) else arg
for arg in dofarray_args]
obj_array_result = op(actx.np, *obj_array_args)
if isinstance(obj_array_result, np.ndarray):
obj_array_result = obj_array_result[0][0]
assert np.allclose(actx.to_numpy(obj_array_result), ref_result)
# }}}
# }}}
# {{{ np.function same as numpy
@pytest.mark.parametrize(("sym_name", "n_args", "dtype"), [
# float only
("arctan2", 2, np.float64),
("minimum", 2, np.float64),
("maximum", 2, np.float64),
("where", 3, np.float64),
("min", 1, np.float64),
("max", 1, np.float64),
("any", 1, np.float64),
("all", 1, np.float64),
("arctan", 1, np.float64),
# float + complex
("sin", 1, np.float64),
("sin", 1, np.complex128),
("exp", 1, np.float64),
("exp", 1, np.complex128),
("conj", 1, np.float64),
("conj", 1, np.complex128),
("vdot", 2, np.float64),
("vdot", 2, np.complex128),
("abs", 1, np.float64),
("abs", 1, np.complex128),
("sum", 1, np.float64),
("sum", 1, np.complex64),
("isnan", 1, np.float64),
])
def test_array_context_np_workalike(actx_factory, sym_name, n_args, dtype):
actx = actx_factory()
if not hasattr(actx.np, sym_name):
pytest.skip(f"'{sym_name}' not implemented on '{type(actx).__name__}'")
ndofs = 512
args = [randn(ndofs, dtype) for i in range(n_args)]
c_to_numpy_arc_functions = {
"atan": "arctan",
"atan2": "arctan2",
}
def evaluate(np_, *args_):
func = getattr(np_, sym_name,
getattr(np_, c_to_numpy_arc_functions.get(sym_name, sym_name)))
return func(*args_)
assert_close_to_numpy_in_containers(actx, evaluate, args)
if sym_name not in ["where", "min", "max", "any", "all", "conj", "vdot", "sum"]:
# Scalar arguments are supported.
args = [randn(0, dtype)[()] for i in range(n_args)]
assert_close_to_numpy(actx, evaluate, args)
@pytest.mark.parametrize(("sym_name", "n_args", "dtype"), [
("zeros_like", 1, np.float64),
("zeros_like", 1, np.complex128),
("ones_like", 1, np.float64),
("ones_like", 1, np.complex128),
])
def test_array_context_np_like(actx_factory, sym_name, n_args, dtype):
actx = actx_factory()
ndofs = 512
args = [randn(ndofs, dtype) for i in range(n_args)]
assert_close_to_numpy(
actx, lambda _np, *_args: getattr(_np, sym_name)(*_args), args)
for c in (42.0, *_get_test_containers(actx)):
result = getattr(actx.np, sym_name)(c)
result = actx.thaw(actx.freeze(result))
if sym_name == "zeros_like":
if np.isscalar(result):
assert result == 0.0
else:
assert actx.to_numpy(actx.np.all(actx.np.equal(result, 0.0)))
elif sym_name == "ones_like":
if np.isscalar(result):
assert result == 1.0
else:
assert actx.to_numpy(actx.np.all(actx.np.equal(result, 1.0)))
else:
raise ValueError(f"unknown method: '{sym_name}'")
# }}}
# {{{ array manipulations
def test_actx_stack(actx_factory):
rng = np.random.default_rng()
actx = actx_factory()
ndofs = 5000
args = [rng.normal(size=ndofs) for i in range(10)]
assert_close_to_numpy_in_containers(
actx, lambda _np, *_args: _np.stack(_args), args)
def test_actx_concatenate(actx_factory):
rng = np.random.default_rng()
actx = actx_factory()
ndofs = 5000
args = [rng.normal(size=ndofs) for i in range(10)]
assert_close_to_numpy(
actx, lambda _np, *_args: _np.concatenate(_args), args)
def test_actx_reshape(actx_factory):
rng = np.random.default_rng()
actx = actx_factory()
for new_shape in [(3, 2), (3, -1), (6,), (-1,)]:
assert_close_to_numpy(
actx, lambda _np, *_args: _np.reshape(*_args),
(rng.normal(size=(2, 3)), new_shape))
def test_actx_ravel(actx_factory):
from numpy.random import default_rng
actx = actx_factory()
rng = default_rng()
ndim = rng.integers(low=1, high=6)
shape = tuple(rng.integers(2, 7, ndim))
assert_close_to_numpy(actx, lambda _np, ary: _np.ravel(ary),
(rng.random(shape),))
# }}}
# {{{ arithmetic same as numpy
def test_dof_array_arithmetic_same_as_numpy(actx_factory):
rng = np.random.default_rng()
actx = actx_factory()
ndofs = 50_000
def get_real(ary):
return ary.real
def get_imag(ary):
return ary.imag
import operator
from random import randrange, uniform
from pytools import generate_nonnegative_integer_tuples_below as gnitb
for op_func, n_args, use_integers in [
(operator.add, 2, False),
(operator.sub, 2, False),
(operator.mul, 2, False),
(operator.truediv, 2, False),
(operator.pow, 2, False),
# FIXME pyopencl.Array doesn't do mod.
# (operator.mod, 2, True),
# (operator.mod, 2, False),
# (operator.imod, 2, True),
# (operator.imod, 2, False),
# FIXME: Two outputs
# (divmod, 2, False),
(operator.iadd, 2, False),
(operator.isub, 2, False),
(operator.imul, 2, False),
(operator.itruediv, 2, False),
(operator.and_, 2, True),
(operator.xor, 2, True),
(operator.or_, 2, True),
(operator.iand, 2, True),
(operator.ixor, 2, True),
(operator.ior, 2, True),
(operator.ge, 2, False),
(operator.lt, 2, False),
(operator.gt, 2, False),
(operator.eq, 2, True),
(operator.ne, 2, True),
(operator.pos, 1, False),
(operator.neg, 1, False),
(operator.abs, 1, False),
(get_real, 1, False),
(get_imag, 1, False),
]:
for is_array_flags in gnitb(2, n_args):
if sum(is_array_flags) == 0:
# all scalars, no need to test
continue
if is_array_flags[0] == 0 and op_func in [
operator.iadd, operator.isub,
operator.imul, operator.itruediv,
operator.iand, operator.ixor, operator.ior,
]:
# can't do in place operations with a scalar lhs
continue
if op_func == operator.ge:
op_func_actx = actx.np.greater_equal
elif op_func == operator.lt:
op_func_actx = actx.np.less
elif op_func == operator.gt:
op_func_actx = actx.np.greater
elif op_func == operator.eq:
op_func_actx = actx.np.equal
elif op_func == operator.ne:
op_func_actx = actx.np.not_equal
else:
op_func_actx = op_func
args = [
(0.5+rng.uniform(size=ndofs)
if not use_integers else
rng.integers(3, 200, size=ndofs))
if is_array_flag else
(uniform(0.5, 2)
if not use_integers
else randrange(3, 200))
for is_array_flag in is_array_flags]
# {{{ get reference numpy result
# make a copy for the in place operators
ref_args = [
arg.copy() if isinstance(arg, np.ndarray) else arg
for arg in args]
ref_result = op_func(*ref_args)
# }}}
# {{{ test DOFArrays
actx_args = [
DOFArray(actx, (actx.from_numpy(arg),))
if isinstance(arg, np.ndarray) else arg
for arg in args]
actx_result = actx.to_numpy(op_func_actx(*actx_args)[0])
assert np.allclose(actx_result, ref_result)
# }}}
# {{{ test object arrays of DOFArrays
# It would be very nice if comparisons on object arrays behaved
# consistently with everything else. Alas, they do not. Instead:
#
# 0.5 < obj_array(DOFArray) -> obj_array([True])
#
# because hey, 0.5 < DOFArray returned something truthy.
if op_func not in [
operator.eq, operator.ne,
operator.le, operator.lt,
operator.ge, operator.gt,
operator.iadd, operator.isub,
operator.imul, operator.itruediv,
operator.iand, operator.ixor, operator.ior,
# All Python objects are real-valued, right?
get_imag,
]:
obj_array_args = [
make_obj_array([arg]) if isinstance(arg, DOFArray) else arg
for arg in actx_args]
obj_array_result = actx.to_numpy(
op_func_actx(*obj_array_args)[0][0])
assert np.allclose(obj_array_result, ref_result)
# }}}
# }}}
# {{{ reductions same as numpy
@pytest.mark.parametrize("op", ["sum", "min", "max"])
def test_reductions_same_as_numpy(actx_factory, op):
rng = np.random.default_rng()
actx = actx_factory()
ary = rng.normal(size=3000)
np_red = getattr(np, op)(ary)
actx_red = getattr(actx.np, op)(actx.from_numpy(ary))
actx_red = actx.to_numpy(actx_red)
assert actx_red.shape == ()
assert np.allclose(np_red, actx_red)
@pytest.mark.parametrize("sym_name", ["any", "all"])
def test_any_all_same_as_numpy(actx_factory, sym_name):
actx = actx_factory()
if not hasattr(actx.np, sym_name):
pytest.skip(f"'{sym_name}' not implemented on '{type(actx).__name__}'")
rng = np.random.default_rng()
ary_any = rng.integers(0, 2, 512)
ary_all = np.ones(512)
assert_close_to_numpy_in_containers(actx,
lambda _np, *_args: getattr(_np, sym_name)(*_args), [ary_any])
assert_close_to_numpy_in_containers(actx,
lambda _np, *_args: getattr(_np, sym_name)(*_args), [ary_all])
assert_close_to_numpy_in_containers(actx,
lambda _np, *_args: getattr(_np, sym_name)(*_args), [1 - ary_all])
def test_array_equal(actx_factory):
actx = actx_factory()
sym_name = "array_equal"
if not hasattr(actx.np, sym_name):
pytest.skip(f"'{sym_name}' not implemented on '{type(actx).__name__}'")
rng = np.random.default_rng()
ary = rng.integers(0, 2, 512)
ary_copy = ary.copy()
ary_diff_values = np.ones(512)
ary_diff_shape = np.ones(511)
ary_diff_type = DOFArray(actx, (np.ones(512),))
# Equal
assert_close_to_numpy_in_containers(actx,
lambda _np, *_args: getattr(_np, sym_name)(*_args), [ary, ary_copy])
# Different values
assert_close_to_numpy_in_containers(actx,
lambda _np, *_args: getattr(_np, sym_name)(*_args), [ary, ary_diff_values])
# Different shapes
assert_close_to_numpy_in_containers(actx,
lambda _np, *_args: getattr(_np, sym_name)(*_args), [ary, ary_diff_shape])
# Different types
assert not actx.to_numpy(actx.np.array_equal(ary, ary_diff_type))
# Empty
ary_empty = np.empty((5, 0), dtype=object)
ary_empty_copy = ary_empty.copy()
assert actx.to_numpy(actx.np.array_equal(ary_empty, ary_empty_copy))
# }}}
# {{{ test array context einsum
@pytest.mark.parametrize("spec", [
"ij->ij",
"ij->ji",
"ii->i",
])
def test_array_context_einsum_array_manipulation(actx_factory, spec):
actx = actx_factory()
rng = np.random.default_rng()
mat = actx.from_numpy(rng.normal(size=(10, 10)))
res = actx.to_numpy(actx.einsum(spec, mat))
ans = np.einsum(spec, actx.to_numpy(mat))
assert np.allclose(res, ans)
@pytest.mark.parametrize("spec", [
"ij,ij->ij",
"ij,ji->ij",
"ij,kj->ik",
])
def test_array_context_einsum_array_matmatprods(actx_factory, spec):
actx = actx_factory()
rng = np.random.default_rng()
mat_a = actx.from_numpy(rng.normal(size=(5, 5)))
mat_b = actx.from_numpy(rng.normal(size=(5, 5)))
res = actx.to_numpy(actx.einsum(spec, mat_a, mat_b))
ans = np.einsum(spec, actx.to_numpy(mat_a), actx.to_numpy(mat_b))
assert np.allclose(res, ans)
@pytest.mark.parametrize("spec", [
"im,mj,k->ijk"
])
def test_array_context_einsum_array_tripleprod(actx_factory, spec):
actx = actx_factory()
rng = np.random.default_rng()
mat_a = actx.from_numpy(rng.normal(size=(7, 5)))
mat_b = actx.from_numpy(rng.normal(size=(5, 7)))
vec = actx.from_numpy(rng.normal(size=(7)))
res = actx.to_numpy(actx.einsum(spec, mat_a, mat_b, vec))
ans = np.einsum(spec,
actx.to_numpy(mat_a),
actx.to_numpy(mat_b),
actx.to_numpy(vec))
assert np.allclose(res, ans)
# }}}
# {{{ array container classes for test
def test_container_map_on_device_scalar(actx_factory):
actx = actx_factory()
expected_sizes = [1, 2, 4, 4, 4]
arys = _get_test_containers(actx, shapes=0)
arys += (np.pi,)
from arraycontext import (
map_array_container,
map_reduce_array_container,
rec_map_array_container,
rec_map_reduce_array_container,
)
for size, ary in zip(expected_sizes, arys[:-1], strict=True):
result = map_array_container(lambda x: x, ary)
assert actx.to_numpy(actx.np.array_equal(result, ary))
result = rec_map_array_container(lambda x: x, ary)
assert actx.to_numpy(actx.np.array_equal(result, ary))
result = map_reduce_array_container(sum, np.size, ary)
assert result == size
result = rec_map_reduce_array_container(sum, np.size, ary)
assert result == size
def test_container_map(actx_factory):
actx = actx_factory()
ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs, _bcast_dc_of_dofs = \
_get_test_containers(actx)
# {{{ check
def _check_allclose(f, arg1, arg2, atol=2.0e-14):
from arraycontext import NotAnArrayContainerError
try:
arg1_iterable = serialize_container(arg1)
arg2_iterable = serialize_container(arg2)
except NotAnArrayContainerError:
assert np.linalg.norm(actx.to_numpy(f(arg1) - arg2)) < atol
else:
arg1_subarrays = [
subarray for _, subarray in arg1_iterable]
arg2_subarrays = [
subarray for _, subarray in arg2_iterable]
for subarray1, subarray2 in zip(arg1_subarrays, arg2_subarrays,
strict=True):
_check_allclose(f, subarray1, subarray2)
def func(x):
return x + 1
from arraycontext import rec_map_array_container
result = rec_map_array_container(func, 1)
assert result == 2
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
result = rec_map_array_container(func, ary)
_check_allclose(func, ary, result)
from arraycontext import mapped_over_array_containers
@mapped_over_array_containers
def mapped_func(x):
return func(x)
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
result = mapped_func(ary)
_check_allclose(func, ary, result)
@mapped_over_array_containers(leaf_class=DOFArray)
def check_leaf(x):
assert isinstance(x, DOFArray)
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
check_leaf(ary)
# }}}
def test_container_multimap(actx_factory):
actx = actx_factory()
ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs, _bcast_dc_of_dofs = \
_get_test_containers(actx)
# {{{ check
def _check_allclose(f, arg1, arg2, atol=2.0e-14):
from arraycontext import NotAnArrayContainerError
try:
arg1_iterable = serialize_container(arg1)
arg2_iterable = serialize_container(arg2)
except NotAnArrayContainerError:
assert np.linalg.norm(actx.to_numpy(f(arg1) - arg2)) < atol
else:
arg1_subarrays = [
subarray for _, subarray in arg1_iterable]
arg2_subarrays = [
subarray for _, subarray in arg2_iterable]
for subarray1, subarray2 in zip(arg1_subarrays, arg2_subarrays,
strict=True):
_check_allclose(f, subarray1, subarray2)
def func_all_scalar(x, y):
return x + y
def func_first_scalar(x, subary):
return x + subary
def func_multiple_scalar(a, subary1, b, subary2):
return a * subary1 + b * subary2
from arraycontext import rec_multimap_array_container
result = rec_multimap_array_container(func_all_scalar, 1, 2)
assert result == 3
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
result = rec_multimap_array_container(func_first_scalar, 1, ary)
_check_allclose(lambda x: 1 + x, ary, result)
result = rec_multimap_array_container(func_multiple_scalar, 2, ary, 2, ary)
_check_allclose(lambda x: 4 * x, ary, result)
from arraycontext import multimapped_over_array_containers
@multimapped_over_array_containers
def mapped_func(a, subary1, b, subary2):
return func_multiple_scalar(a, subary1, b, subary2)
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
result = mapped_func(2, ary, 2, ary)
_check_allclose(lambda x: 4 * x, ary, result)
@multimapped_over_array_containers(leaf_class=DOFArray)
def check_leaf(a, subary1, b, subary2):
assert isinstance(subary1, DOFArray)
assert isinstance(subary2, DOFArray)
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
check_leaf(2, ary, 2, ary)
with pytest.raises(AssertionError):
rec_multimap_array_container(func_multiple_scalar, 2, ary_dof, 2, dc_of_dofs)
# }}}
def test_container_arithmetic(actx_factory):
actx = actx_factory()
ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs, bcast_dc_of_dofs = \
_get_test_containers(actx)
# {{{ check
def _check_allclose(f, arg1, arg2, atol=5.0e-14):
assert np.linalg.norm(actx.to_numpy(f(arg1) - arg2)) < atol
from arraycontext import rec_multimap_array_container
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
rec_multimap_array_container(
partial(_check_allclose, lambda x: 3 * x),
ary, 2 * ary + ary)
rec_multimap_array_container(
partial(_check_allclose, lambda x: actx.np.sin(x)),
ary, actx.np.sin(ary))
with pytest.raises(TypeError):
ary_of_dofs + dc_of_dofs
with pytest.raises(TypeError):
dc_of_dofs + ary_of_dofs
with pytest.raises(TypeError):
ary_dof + dc_of_dofs
with pytest.raises(TypeError):
dc_of_dofs + ary_dof
bcast_result = ary_dof + bcast_dc_of_dofs
bcast_dc_of_dofs + ary_dof
assert actx.to_numpy(actx.np.linalg.norm(bcast_result.mass
- 2*ary_of_dofs)) < 1e-8
mock_gradient = MyContainerDOFBcast(
name="yo",
mass=ary_of_dofs,
momentum=mat_of_dofs,
enthalpy=ary_of_dofs)
grad_matvec_result = mock_gradient @ ary_of_dofs
assert isinstance(grad_matvec_result.mass, DOFArray)
assert grad_matvec_result.momentum.shape == ary_of_dofs.shape
assert actx.to_numpy(actx.np.linalg.norm(
grad_matvec_result.mass - sum(ary_of_dofs**2)
)) < 1e-8
# }}}
def test_container_freeze_thaw(actx_factory):
actx = actx_factory()
ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs, _bcast_dc_of_dofs = \
_get_test_containers(actx)
# {{{ check
from arraycontext import (
get_container_context_opt,
get_container_context_recursively_opt,
)
assert get_container_context_opt(ary_of_dofs) is None
assert get_container_context_opt(mat_of_dofs) is None
assert get_container_context_opt(ary_dof) is actx
assert get_container_context_opt(dc_of_dofs) is actx
assert get_container_context_recursively_opt(ary_of_dofs) is actx
assert get_container_context_recursively_opt(mat_of_dofs) is actx
for ary in [ary_dof, ary_of_dofs, mat_of_dofs, dc_of_dofs]:
frozen_ary = actx.freeze(ary)
thawed_ary = actx.thaw(frozen_ary)
frozen_ary = actx.freeze(thawed_ary)
assert get_container_context_recursively_opt(frozen_ary) is None
assert get_container_context_recursively_opt(thawed_ary) is actx
actx2 = actx.clone()
ary_dof_frozen = actx.freeze(ary_dof)
with pytest.raises(ValueError) as exc_info:
ary_dof + ary_dof_frozen
assert "frozen" in str(exc_info.value)
ary_dof_2 = actx2.thaw(actx.freeze(ary_dof))
with pytest.raises(ValueError):
ary_dof + ary_dof_2
# }}}
@pytest.mark.parametrize("ord", [2, np.inf])
def test_container_norm(actx_factory, ord):
actx = actx_factory()
from pytools.obj_array import make_obj_array
c = MyContainer(name="hey", mass=1, momentum=make_obj_array([2, 3]), enthalpy=5)
n1 = actx.np.linalg.norm(make_obj_array([c, c]), ord)
n2 = np.linalg.norm([1, 2, 3, 5]*2, ord)
assert abs(n1 - n2) < 1e-12
# }}}
# {{{ test flatten and unflatten
@pytest.mark.parametrize("shapes", [
0, # tests device scalars when flattening
512,
[(128, 67)],
[(127, 67), (18, 0)], # tests 0-sized arrays
[(64, 7), (154, 12)]
])
def test_flatten_array_container(actx_factory, shapes):
actx = actx_factory()
from arraycontext import flatten, unflatten
arys = _get_test_containers(actx, shapes=shapes)
for ary in arys:
flat = flatten(ary, actx)
assert flat.ndim == 1
ary_roundtrip = unflatten(ary, flat, actx)
from arraycontext import rec_multimap_reduce_array_container
assert rec_multimap_reduce_array_container(
np.prod,
lambda x, y: x.shape == y.shape,
ary, ary_roundtrip)
assert actx.to_numpy(
actx.np.linalg.norm(ary - ary_roundtrip)
) < 1.0e-15
# {{{ complex to real
if isinstance(shapes, int | tuple):
shapes = [shapes]
ary = DOFArray(actx, tuple(actx.from_numpy(randn(shape, np.float64))
for shape in shapes))
template = DOFArray(actx, tuple(actx.from_numpy(randn(shape, np.complex128))
for shape in shapes))
flat = flatten(ary, actx)
ary_roundtrip = unflatten(template, flat, actx, strict=False)
assert actx.to_numpy(
actx.np.linalg.norm(ary - ary_roundtrip)
) < 1.0e-15
# }}}
def _checked_flatten(ary, actx, leaf_class=None):
from arraycontext import flat_size_and_dtype, flatten
result = flatten(ary, actx, leaf_class=leaf_class)
if leaf_class is None:
size, dtype = flat_size_and_dtype(ary)
assert result.shape == (size,)
assert result.dtype == dtype
return result
def test_flatten_array_container_failure(actx_factory):
actx = actx_factory()
from arraycontext import unflatten
ary = _get_test_containers(actx, shapes=512)[0]
flat_ary = _checked_flatten(ary, actx)
if not isinstance(actx, NumpyArrayContext):
with pytest.raises(TypeError):
# cannot unflatten from a numpy array (except for numpy actx)
unflatten(ary, actx.to_numpy(flat_ary), actx)
with pytest.raises(ValueError):
# cannot unflatten non-flat arrays
unflatten(ary, flat_ary.reshape(2, -1), actx)
with pytest.raises(ValueError):
# cannot unflatten partially
unflatten(ary, flat_ary[:-1], actx)
def test_flatten_with_leaf_class(actx_factory):
actx = actx_factory()
arys = _get_test_containers(actx, shapes=512)
flat = _checked_flatten(arys[0], actx, leaf_class=DOFArray)
assert isinstance(flat, actx.array_types)
assert flat.shape == (arys[0].size,)
flat = _checked_flatten(arys[1], actx, leaf_class=DOFArray)
assert isinstance(flat, np.ndarray) and flat.dtype == object
assert all(isinstance(entry, actx.array_types) for entry in flat)
assert all(entry.shape == (arys[0].size,) for entry in flat)
flat = _checked_flatten(arys[3], actx, leaf_class=DOFArray)