-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
test_array_core.py
5348 lines (4079 loc) · 158 KB
/
test_array_core.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
import contextlib
import copy
import pathlib
import re
import xml.etree.ElementTree
from unittest import mock
import pytest
np = pytest.importorskip("numpy")
import math
import operator
import os
import time
import warnings
from functools import reduce
from io import StringIO
from operator import add, sub
from threading import Lock
from tlz import concat, merge
from tlz.curried import identity
import dask
import dask.array as da
from dask.array.chunk import getitem
from dask.array.core import (
Array,
BlockView,
PerformanceWarning,
blockdims_from_blockshape,
broadcast_chunks,
broadcast_shapes,
broadcast_to,
common_blockdim,
concatenate,
concatenate3,
concatenate_axes,
dotmany,
from_array,
from_delayed,
from_func,
getter,
graph_from_arraylike,
normalize_chunks,
optimize,
stack,
store,
)
from dask.array.reshape import _not_implemented_message
from dask.array.tests.test_dispatch import EncapsulateNDArray
from dask.array.utils import assert_eq, same_keys
from dask.base import compute_as_if_collection, tokenize
from dask.blockwise import broadcast_dimensions
from dask.blockwise import make_blockwise_graph as top
from dask.blockwise import optimize_blockwise
from dask.delayed import Delayed, delayed
from dask.highlevelgraph import HighLevelGraph, MaterializedLayer
from dask.layers import Blockwise
from dask.utils import SerializableLock, key_split, parse_bytes, tmpdir, tmpfile
from dask.utils_test import dec, hlg_layer_topological, inc
@pytest.mark.parametrize("inline_array", [True, False])
def test_graph_from_arraylike(inline_array):
d = 2
chunk = (2, 3)
shape = tuple(d * n for n in chunk)
arr = np.ones(shape)
dsk = graph_from_arraylike(
arr, chunk, shape=shape, name="X", inline_array=inline_array
)
assert isinstance(dsk, HighLevelGraph)
if inline_array:
assert len(dsk.layers) == 1
assert isinstance(hlg_layer_topological(dsk, 0), Blockwise)
else:
assert len(dsk.layers) == 2
assert isinstance(hlg_layer_topological(dsk, 0), MaterializedLayer)
assert isinstance(hlg_layer_topological(dsk, 1), Blockwise)
dsk = dict(dsk)
# Somewhat odd membership check to avoid numpy elemwise __in__ overload
assert any(arr is v for v in dsk.values()) is not inline_array
def test_top():
assert top(inc, "z", "ij", "x", "ij", numblocks={"x": (2, 2)}) == {
("z", 0, 0): (inc, ("x", 0, 0)),
("z", 0, 1): (inc, ("x", 0, 1)),
("z", 1, 0): (inc, ("x", 1, 0)),
("z", 1, 1): (inc, ("x", 1, 1)),
}
assert top(
add, "z", "ij", "x", "ij", "y", "ij", numblocks={"x": (2, 2), "y": (2, 2)}
) == {
("z", 0, 0): (add, ("x", 0, 0), ("y", 0, 0)),
("z", 0, 1): (add, ("x", 0, 1), ("y", 0, 1)),
("z", 1, 0): (add, ("x", 1, 0), ("y", 1, 0)),
("z", 1, 1): (add, ("x", 1, 1), ("y", 1, 1)),
}
assert top(
dotmany, "z", "ik", "x", "ij", "y", "jk", numblocks={"x": (2, 2), "y": (2, 2)}
) == {
("z", 0, 0): (dotmany, [("x", 0, 0), ("x", 0, 1)], [("y", 0, 0), ("y", 1, 0)]),
("z", 0, 1): (dotmany, [("x", 0, 0), ("x", 0, 1)], [("y", 0, 1), ("y", 1, 1)]),
("z", 1, 0): (dotmany, [("x", 1, 0), ("x", 1, 1)], [("y", 0, 0), ("y", 1, 0)]),
("z", 1, 1): (dotmany, [("x", 1, 0), ("x", 1, 1)], [("y", 0, 1), ("y", 1, 1)]),
}
assert top(identity, "z", "", "x", "ij", numblocks={"x": (2, 2)}) == {
("z",): (identity, [[("x", 0, 0), ("x", 0, 1)], [("x", 1, 0), ("x", 1, 1)]])
}
def test_top_supports_broadcasting_rules():
assert top(
add, "z", "ij", "x", "ij", "y", "ij", numblocks={"x": (1, 2), "y": (2, 1)}
) == {
("z", 0, 0): (add, ("x", 0, 0), ("y", 0, 0)),
("z", 0, 1): (add, ("x", 0, 1), ("y", 0, 0)),
("z", 1, 0): (add, ("x", 0, 0), ("y", 1, 0)),
("z", 1, 1): (add, ("x", 0, 1), ("y", 1, 0)),
}
def test_top_literals():
assert top(add, "z", "ij", "x", "ij", 123, None, numblocks={"x": (2, 2)}) == {
("z", 0, 0): (add, ("x", 0, 0), 123),
("z", 0, 1): (add, ("x", 0, 1), 123),
("z", 1, 0): (add, ("x", 1, 0), 123),
("z", 1, 1): (add, ("x", 1, 1), 123),
}
def test_blockwise_literals():
x = da.ones((10, 10), chunks=(5, 5))
z = da.blockwise(add, "ij", x, "ij", 100, None, dtype=x.dtype)
assert_eq(z, x + 100)
z = da.blockwise(
lambda x, y, z: x * y + z, "ij", 2, None, x, "ij", 100, None, dtype=x.dtype
)
assert_eq(z, 2 * x + 100)
z = da.blockwise(getitem, "ij", x, "ij", slice(None), None, dtype=x.dtype)
assert_eq(z, x)
def test_blockwise_1_in_shape_I():
def test_f(a, b):
assert 1 in b.shape
p, k, N = 7, 2, 5
da.blockwise(
test_f,
"x",
da.zeros((2 * p, 9, k * N), chunks=(p, 3, k)),
"xzt",
da.zeros((2 * p, 9, 1), chunks=(p, 3, -1)),
"xzt",
concatenate=True,
dtype=float,
).compute()
def test_blockwise_1_in_shape_II():
def test_f(a, b):
assert 1 in b.shape
p, k, N = 7, 2, 5
da.blockwise(
test_f,
"x",
da.zeros((2 * p, 9, k * N, 8), chunks=(p, 9, k, 4)),
"xztu",
da.zeros((2 * p, 9, 1, 8), chunks=(p, 9, -1, 4)),
"xztu",
concatenate=True,
dtype=float,
).compute()
def test_blockwise_1_in_shape_III():
def test_f(a, b):
assert 1 in b.shape
k, N = 2, 5
da.blockwise(
test_f,
"x",
da.zeros((k * N, 9, 8), chunks=(k, 3, 4)),
"xtu",
da.zeros((1, 9, 8), chunks=(-1, 3, 4)),
"xtu",
concatenate=True,
dtype=float,
).compute()
def test_concatenate3_on_scalars():
assert_eq(concatenate3([1, 2]), np.array([1, 2]))
def test_chunked_dot_product():
x = np.arange(400).reshape((20, 20))
o = np.ones((20, 20))
getx = graph_from_arraylike(x, (5, 5), shape=(20, 20), name="x")
geto = graph_from_arraylike(o, (5, 5), shape=(20, 20), name="o")
result = top(
dotmany, "out", "ik", "x", "ij", "o", "jk", numblocks={"x": (4, 4), "o": (4, 4)}
)
dsk = merge(getx, geto, result)
out = dask.get(dsk, [[("out", i, j) for j in range(4)] for i in range(4)])
assert_eq(np.dot(x, o), concatenate3(out))
def test_chunked_transpose_plus_one():
x = np.arange(400).reshape((20, 20))
getx = graph_from_arraylike(x, (5, 5), shape=(20, 20), name="x")
f = lambda x: x.T + 1
comp = top(f, "out", "ij", "x", "ji", numblocks={"x": (4, 4)})
dsk = merge(getx, comp)
out = dask.get(dsk, [[("out", i, j) for j in range(4)] for i in range(4)])
assert_eq(concatenate3(out), x.T + 1)
def test_broadcast_dimensions_works_with_singleton_dimensions():
argpairs = [("x", "i")]
numblocks = {"x": ((1,),)}
assert broadcast_dimensions(argpairs, numblocks) == {"i": (1,)}
def test_broadcast_dimensions():
argpairs = [("x", "ij"), ("y", "ij")]
d = {"x": ("Hello", 1), "y": (1, (2, 3))}
assert broadcast_dimensions(argpairs, d) == {"i": "Hello", "j": (2, 3)}
def test_Array():
arr = object() # arraylike is unimportant since we never compute
shape = (1000, 1000)
chunks = (100, 100)
name = "x"
dsk = graph_from_arraylike(arr, chunks, shape, name)
a = Array(dsk, name, chunks, shape=shape, dtype="f8")
assert a.numblocks == (10, 10)
assert a.__dask_keys__() == [[("x", i, j) for j in range(10)] for i in range(10)]
assert a.chunks == ((100,) * 10, (100,) * 10)
assert a.shape == shape
assert len(a) == shape[0]
with pytest.raises(ValueError):
Array(dsk, name, chunks, shape=shape)
with pytest.raises(TypeError):
Array(dsk, name, chunks, shape=shape, dtype="f8", meta=np.empty(0, 0))
def test_uneven_chunks():
a = Array({}, "x", chunks=(3, 3), shape=(10, 10), dtype="f8")
assert a.chunks == ((3, 3, 3, 1), (3, 3, 3, 1))
def test_numblocks_suppoorts_singleton_block_dims():
arr = object() # arraylike is unimportant since we never compute
shape = (100, 10)
chunks = (10, 10)
name = "x"
dsk = graph_from_arraylike(arr, chunks, shape, name)
a = Array(dsk, name, chunks, shape=shape, dtype="f8")
assert set(concat(a.__dask_keys__())) == {("x", i, 0) for i in range(10)}
def test_keys():
dsk = {("x", i, j): () for i in range(5) for j in range(6)}
dx = Array(dsk, "x", chunks=(10, 10), shape=(50, 60), dtype="f8")
assert dx.__dask_keys__() == [[(dx.name, i, j) for j in range(6)] for i in range(5)]
# Cache works
assert dx.__dask_keys__() is dx.__dask_keys__()
# Test mutating names clears key cache
dx.dask = {("y", i, j): () for i in range(5) for j in range(6)}
dx._name = "y"
new_keys = [[(dx.name, i, j) for j in range(6)] for i in range(5)]
assert dx.__dask_keys__() == new_keys
assert np.array_equal(dx._key_array, np.array(new_keys, dtype="object"))
d = Array({}, "x", (), shape=(), dtype="f8")
assert d.__dask_keys__() == [("x",)]
def test_Array_computation():
a = Array({("x", 0, 0): np.eye(3)}, "x", shape=(3, 3), chunks=(3, 3), dtype="f8")
assert_eq(np.array(a), np.eye(3))
assert isinstance(a.compute(), np.ndarray)
assert float(a[0, 0]) == 1
def test_Array_numpy_gufunc_call__array_ufunc__01():
x = da.random.default_rng().normal(size=(3, 10, 10), chunks=(2, 10, 10))
nx = x.compute()
ny = np.linalg._umath_linalg.inv(nx)
y = np.linalg._umath_linalg.inv(x)
assert_eq(ny, y)
def test_Array_numpy_gufunc_call__array_ufunc__02():
x = da.random.default_rng().normal(size=(3, 10, 10), chunks=(2, 10, 10))
nx = x.compute()
nw, nv = np.linalg._umath_linalg.eig(nx)
w, v = np.linalg._umath_linalg.eig(x)
assert_eq(nw, w)
assert_eq(nv, v)
def test_stack():
a, b, c = (
Array(
graph_from_arraylike(object(), chunks=(2, 3), shape=(4, 6), name=name),
name,
chunks=(2, 3),
dtype="f8",
shape=(4, 6),
)
for name in "ABC"
)
s = stack([a, b, c], axis=0)
colon = slice(None, None, None)
assert s.shape == (3, 4, 6)
assert s.chunks == ((1, 1, 1), (2, 2), (3, 3))
assert s.chunksize == (1, 2, 3)
assert s.dask[(s.name, 0, 1, 0)] == (getitem, ("A", 1, 0), (None, colon, colon))
assert s.dask[(s.name, 2, 1, 0)] == (getitem, ("C", 1, 0), (None, colon, colon))
assert same_keys(s, stack([a, b, c], axis=0))
s2 = stack([a, b, c], axis=1)
assert s2.shape == (4, 3, 6)
assert s2.chunks == ((2, 2), (1, 1, 1), (3, 3))
assert s2.chunksize == (2, 1, 3)
assert s2.dask[(s2.name, 0, 1, 0)] == (getitem, ("B", 0, 0), (colon, None, colon))
assert s2.dask[(s2.name, 1, 1, 0)] == (getitem, ("B", 1, 0), (colon, None, colon))
assert same_keys(s2, stack([a, b, c], axis=1))
s2 = stack([a, b, c], axis=2)
assert s2.shape == (4, 6, 3)
assert s2.chunks == ((2, 2), (3, 3), (1, 1, 1))
assert s2.chunksize == (2, 3, 1)
assert s2.dask[(s2.name, 0, 1, 0)] == (getitem, ("A", 0, 1), (colon, colon, None))
assert s2.dask[(s2.name, 1, 1, 2)] == (getitem, ("C", 1, 1), (colon, colon, None))
assert same_keys(s2, stack([a, b, c], axis=2))
pytest.raises(ValueError, lambda: stack([]))
pytest.raises(ValueError, lambda: stack([a, b, c], axis=3))
assert set(b.dask.keys()).issubset(s2.dask.keys())
assert stack([a, b, c], axis=-1).chunks == stack([a, b, c], axis=2).chunks
def test_stack_zero_size():
x = np.empty((2, 0, 3))
y = da.from_array(x, chunks=1)
result_np = np.concatenate([x, x])
result_da = da.concatenate([y, y])
assert_eq(result_np, result_da)
def test_short_stack():
x = np.array([1])
d = da.from_array(x, chunks=(1,))
s = da.stack([d])
assert s.shape == (1, 1)
chunks = compute_as_if_collection(Array, s.dask, s.__dask_keys__())
assert chunks[0][0].shape == (1, 1)
def test_stack_scalars():
d = da.arange(4, chunks=2)
s = da.stack([d.mean(), d.sum()])
assert s.compute().tolist() == [np.arange(4).mean(), np.arange(4).sum()]
def test_stack_promote_type():
i = np.arange(10, dtype="i4")
f = np.arange(10, dtype="f4")
di = da.from_array(i, chunks=5)
df = da.from_array(f, chunks=5)
res = da.stack([di, df])
assert_eq(res, np.stack([i, f]))
def test_stack_rechunk():
rng = da.random.default_rng()
x = rng.random(10, chunks=5)
y = rng.random(10, chunks=4)
z = da.stack([x, y], axis=0)
assert z.shape == (2, 10)
assert z.chunks == ((1, 1), (4, 1, 3, 2))
assert_eq(z, np.stack([x.compute(), y.compute()], axis=0))
def test_stack_unknown_chunksizes():
dd = pytest.importorskip("dask.dataframe")
pd = pytest.importorskip("pandas")
a_df = pd.DataFrame({"x": np.arange(12)})
b_df = pd.DataFrame({"y": np.arange(12) * 10})
a_ddf = dd.from_pandas(a_df, sort=False, npartitions=3)
b_ddf = dd.from_pandas(b_df, sort=False, npartitions=3)
a_x = a_ddf.values
b_x = b_ddf.values
assert np.isnan(a_x.shape[0])
assert np.isnan(b_x.shape[0])
with pytest.raises(ValueError) as exc_info:
da.stack([a_x, b_x], axis=0)
assert "shape" in str(exc_info.value)
assert "nan" in str(exc_info.value)
c_x = da.stack([a_x, b_x], axis=0, allow_unknown_chunksizes=True)
assert_eq(c_x, np.stack([a_df.values, b_df.values], axis=0))
with pytest.raises(ValueError) as exc_info:
da.stack([a_x, b_x], axis=1)
assert "shape" in str(exc_info.value)
assert "nan" in str(exc_info.value)
c_x = da.stack([a_x, b_x], axis=1, allow_unknown_chunksizes=True)
assert_eq(c_x, np.stack([a_df.values, b_df.values], axis=1))
m_df = pd.DataFrame({"m": np.arange(12) * 100})
n_df = pd.DataFrame({"n": np.arange(12) * 1000})
m_ddf = dd.from_pandas(m_df, sort=False, npartitions=3)
n_ddf = dd.from_pandas(n_df, sort=False, npartitions=3)
m_x = m_ddf.values
n_x = n_ddf.values
assert np.isnan(m_x.shape[0])
assert np.isnan(n_x.shape[0])
with pytest.raises(ValueError) as exc_info:
da.stack([[a_x, b_x], [m_x, n_x]])
assert "shape" in str(exc_info.value)
assert "nan" in str(exc_info.value)
c_x = da.stack([[a_x, b_x], [m_x, n_x]], allow_unknown_chunksizes=True)
assert_eq(c_x, np.stack([[a_df.values, b_df.values], [m_df.values, n_df.values]]))
def test_concatenate():
a, b, c = (
Array(
graph_from_arraylike(object(), chunks=(2, 3), shape=(4, 6), name=name),
name,
chunks=(2, 3),
dtype="f8",
shape=(4, 6),
)
for name in "ABC"
)
x = concatenate([a, b, c], axis=0)
assert x.shape == (12, 6)
assert x.chunks == ((2, 2, 2, 2, 2, 2), (3, 3))
assert x.dask[(x.name, 0, 1)] == ("A", 0, 1)
assert x.dask[(x.name, 5, 0)] == ("C", 1, 0)
assert same_keys(x, concatenate([a, b, c], axis=0))
y = concatenate([a, b, c], axis=1)
assert y.shape == (4, 18)
assert y.chunks == ((2, 2), (3, 3, 3, 3, 3, 3))
assert y.dask[(y.name, 1, 0)] == ("A", 1, 0)
assert y.dask[(y.name, 1, 5)] == ("C", 1, 1)
assert same_keys(y, concatenate([a, b, c], axis=1))
assert set(b.dask.keys()).issubset(y.dask.keys())
z = concatenate([a], axis=0)
assert z.shape == a.shape
assert z.chunks == a.chunks
assert z.dask == a.dask
assert z is a
assert (
concatenate([a, b, c], axis=-1).chunks == concatenate([a, b, c], axis=1).chunks
)
pytest.raises(ValueError, lambda: concatenate([]))
pytest.raises(ValueError, lambda: concatenate([a, b, c], axis=2))
@pytest.mark.parametrize(
"dtypes", [((">f8", ">f8"), "float64"), (("<f4", "<f8"), "float64")]
)
def test_concatenate_types(dtypes):
dts_in, dt_out = dtypes
arrs = [np.zeros(4, dtype=dt) for dt in dts_in]
darrs = [from_array(arr, chunks=(2,)) for arr in arrs]
x = concatenate(darrs, axis=0)
assert x.dtype == dt_out
def test_concatenate_unknown_axes():
dd = pytest.importorskip("dask.dataframe")
pd = pytest.importorskip("pandas")
a_df = pd.DataFrame({"x": np.arange(12)})
b_df = pd.DataFrame({"y": np.arange(12) * 10})
a_ddf = dd.from_pandas(a_df, sort=False, npartitions=3)
b_ddf = dd.from_pandas(b_df, sort=False, npartitions=3)
a_x = a_ddf.values
b_x = b_ddf.values
assert np.isnan(a_x.shape[0])
assert np.isnan(b_x.shape[0])
da.concatenate([a_x, b_x], axis=0) # works fine
with pytest.raises(ValueError) as exc_info:
da.concatenate([a_x, b_x], axis=1) # unknown chunks
assert "nan" in str(exc_info.value)
assert "allow_unknown_chunksize" in str(exc_info.value)
c_x = da.concatenate(
[a_x, b_x], axis=1, allow_unknown_chunksizes=True
) # unknown chunks
assert_eq(c_x, np.concatenate([a_df.values, b_df.values], axis=1))
def test_concatenate_flatten():
x = np.array([1, 2])
y = np.array([[3, 4], [5, 6]])
a = da.from_array(x, chunks=(2,))
b = da.from_array(y, chunks=(2, 1))
assert_eq(np.concatenate([x, y], axis=None), da.concatenate([a, b], axis=None))
def test_concatenate_rechunk():
rng = da.random.default_rng()
x = rng.random((6, 6), chunks=(3, 3))
y = rng.random((6, 6), chunks=(2, 2))
z = da.concatenate([x, y], axis=0)
assert z.shape == (12, 6)
assert z.chunks == ((3, 3, 2, 2, 2), (2, 1, 1, 2))
assert_eq(z, np.concatenate([x.compute(), y.compute()], axis=0))
z = da.concatenate([x, y], axis=1)
assert z.shape == (6, 12)
assert z.chunks == ((2, 1, 1, 2), (3, 3, 2, 2, 2))
assert_eq(z, np.concatenate([x.compute(), y.compute()], axis=1))
def test_concatenate_fixlen_strings():
x = np.array(["a", "b", "c"])
y = np.array(["aa", "bb", "cc"])
a = da.from_array(x, chunks=(2,))
b = da.from_array(y, chunks=(2,))
assert_eq(np.concatenate([x, y]), da.concatenate([a, b]))
def test_concatenate_zero_size():
x = np.random.default_rng().random(10)
y = da.from_array(x, chunks=3)
result_np = np.concatenate([x, x[:0]])
result_da = da.concatenate([y, y[:0]])
assert_eq(result_np, result_da)
assert result_da is y
# dtype of a size 0 arrays can affect the output dtype
result_np = np.concatenate([np.zeros(0, dtype=float), np.zeros(1, dtype=int)])
result_da = da.concatenate([da.zeros(0, dtype=float), da.zeros(1, dtype=int)])
assert_eq(result_np, result_da)
# All empty arrays case
result_np = np.concatenate([np.zeros(0), np.zeros(0)])
result_da = da.concatenate([da.zeros(0), da.zeros(0)])
assert_eq(result_np, result_da)
def test_block_simple_row_wise():
a1 = np.ones((2, 2))
a2 = 2 * a1
d1 = da.asarray(a1)
d2 = da.asarray(a2)
expected = np.block([a1, a2])
result = da.block([d1, d2])
assert_eq(expected, result)
expected = np.block([a1, a2[:, :0]])
result = da.block([d1, d2[:, :0]])
assert result is d1
assert_eq(expected, result)
def test_block_simple_column_wise():
a1 = np.ones((2, 2))
a2 = 2 * a1
d1 = da.asarray(a1)
d2 = da.asarray(a2)
expected = np.block([[a1], [a2]])
result = da.block([[d1], [d2]])
assert_eq(expected, result)
def test_block_with_1d_arrays_row_wise():
# # # 1-D vectors are treated as row arrays
a1 = np.array([1, 2, 3])
a2 = np.array([2, 3, 4])
d1 = da.asarray(a1)
d2 = da.asarray(a2)
expected = np.block([a1, a2])
result = da.block([d1, d2])
assert_eq(expected, result)
expected = np.block([a1, a2[:0]])
result = da.block([d1, d2[:0]])
assert result is d1
assert_eq(expected, result)
def test_block_with_1d_arrays_multiple_rows():
a1 = np.array([1, 2, 3])
a2 = np.array([2, 3, 4])
d1 = da.asarray(a1)
d2 = da.asarray(a2)
expected = np.block([[a1, a2], [a1, a2]])
result = da.block([[d1, d2], [d1, d2]])
assert_eq(expected, result)
def test_block_with_1d_arrays_column_wise():
# # # 1-D vectors are treated as row arrays
a1 = np.array([1, 2, 3])
a2 = np.array([2, 3, 4])
d1 = da.asarray(a1)
d2 = da.asarray(a2)
expected = np.block([[a1], [a2]])
result = da.block([[d1], [d2]])
assert_eq(expected, result)
def test_block_mixed_1d_and_2d():
a1 = np.ones((2, 2))
a2 = np.array([2, 2])
d1 = da.asarray(a1)
d2 = da.asarray(a2)
expected = np.block([[d1], [d2]])
result = da.block([[a1], [a2]])
assert_eq(expected, result)
def test_block_complicated():
# a bit more complicated
a1 = np.array([[1, 1, 1]])
a2 = np.array([[2, 2, 2]])
a3 = np.array([[3, 3, 3, 3, 3, 3]])
a4 = np.array([4, 4, 4, 4, 4, 4])
a5 = np.array(5)
a6 = np.array([6, 6, 6, 6, 6])
a7 = np.zeros((2, 6))
d1 = da.asarray(a1)
d2 = da.asarray(a2)
d3 = da.asarray(a3)
d4 = da.asarray(a4)
d5 = da.asarray(a5)
d6 = da.asarray(a6)
d7 = da.asarray(a7)
expected = np.block([[a1, a2], [a3], [a4], [a5, a6], [a7]])
result = da.block([[d1, d2], [d3], [d4], [d5, d6], [d7]])
assert_eq(expected, result)
def test_block_nested():
a1 = np.array([1, 1, 1])
a2 = np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]])
a3 = np.array([3, 3, 3])
a4 = np.array([4, 4, 4])
a5 = np.array(5)
a6 = np.array([6, 6, 6, 6, 6])
a7 = np.zeros((2, 6))
d1 = da.asarray(a1)
d2 = da.asarray(a2)
d3 = da.asarray(a3)
d4 = da.asarray(a4)
d5 = da.asarray(a5)
d6 = da.asarray(a6)
d7 = da.asarray(a7)
expected = np.block([[np.block([[a1], [a3], [a4]]), a2], [a5, a6], [a7]])
result = da.block([[da.block([[d1], [d3], [d4]]), d2], [d5, d6], [d7]])
assert_eq(expected, result)
def test_block_3d():
a000 = np.ones((2, 2, 2), int) * 1
a100 = np.ones((3, 2, 2), int) * 2
a010 = np.ones((2, 3, 2), int) * 3
a001 = np.ones((2, 2, 3), int) * 4
a011 = np.ones((2, 3, 3), int) * 5
a101 = np.ones((3, 2, 3), int) * 6
a110 = np.ones((3, 3, 2), int) * 7
a111 = np.ones((3, 3, 3), int) * 8
d000 = da.asarray(a000)
d100 = da.asarray(a100)
d010 = da.asarray(a010)
d001 = da.asarray(a001)
d011 = da.asarray(a011)
d101 = da.asarray(a101)
d110 = da.asarray(a110)
d111 = da.asarray(a111)
expected = np.block([[[a000, a001], [a010, a011]], [[a100, a101], [a110, a111]]])
result = da.block([[[d000, d001], [d010, d011]], [[d100, d101], [d110, d111]]])
assert_eq(expected, result)
expected = np.block(
[
[[a000, a001[:, :, :0]], [a010[:, :0, :], a011[:, :0, :0]]],
[[a100[:0, :, :], a101[:0, :, :0]], [a110[:0, :0, :], a111[:0, :0, :0]]],
]
)
result = da.block(
[
[[d000, d001[:, :, :0]], [d010[:, :0, :], d011[:, :0, :0]]],
[[d100[:0, :, :], d101[:0, :, :0]], [d110[:0, :0, :], d111[:0, :0, :0]]],
]
)
assert result is d000
assert_eq(expected, result)
def test_block_with_mismatched_shape():
a = np.array([0, 0])
b = np.eye(2)
for arrays in [[a, b], [b, a]]:
with pytest.raises(ValueError):
da.block(arrays)
def test_block_no_lists():
assert_eq(da.block(1), np.block(1))
assert_eq(da.block(np.eye(3)), np.block(np.eye(3)))
def test_block_invalid_nesting():
for arrays in [
[1, [2]],
[1, []],
[[1], 2],
[[], 2],
[[[1], [2]], [[3, 4]], [5]], # missing brackets
]:
with pytest.raises(ValueError) as e:
da.block(arrays)
e.match(r"depths are mismatched")
def test_block_empty_lists():
for arrays in [[], [[]], [[1], []]]:
with pytest.raises(ValueError) as e:
da.block(arrays)
e.match(r"empty")
def test_block_tuple():
for arrays in [([1, 2], [3, 4]), [(1, 2), (3, 4)]]:
with pytest.raises(TypeError) as e:
da.block(arrays)
e.match(r"tuple")
def test_broadcast_shapes():
assert () == broadcast_shapes()
assert (2, 5) == broadcast_shapes((2, 5))
assert (0, 5) == broadcast_shapes((0, 1), (1, 5))
assert np.allclose(
(2, np.nan), broadcast_shapes((1, np.nan), (2, 1)), equal_nan=True
)
assert np.allclose(
(2, np.nan), broadcast_shapes((2, 1), (1, np.nan)), equal_nan=True
)
assert (3, 4, 5) == broadcast_shapes((3, 4, 5), (4, 1), ())
assert (3, 4) == broadcast_shapes((3, 1), (1, 4), (4,))
assert (5, 6, 7, 3, 4) == broadcast_shapes((3, 1), (), (5, 6, 7, 1, 4))
pytest.raises(ValueError, lambda: broadcast_shapes((3,), (3, 4)))
pytest.raises(ValueError, lambda: broadcast_shapes((2, 3), (2, 3, 1)))
pytest.raises(ValueError, lambda: broadcast_shapes((2, 3), (1, np.nan)))
def test_elemwise_on_scalars():
x = np.arange(10, dtype=np.int64)
a = from_array(x, chunks=(5,))
assert len(a.__dask_keys__()) == 2
assert_eq(a.sum() ** 2, x.sum() ** 2)
y = np.arange(10, dtype=np.int32)
b = from_array(y, chunks=(5,))
result = a.sum() * b
# Dask 0-d arrays do not behave like numpy scalars for type promotion
assert result.dtype == np.int64
assert result.compute().dtype == np.int64
assert (x.sum() * y).dtype == np.int32
assert_eq((x.sum() * y).astype(np.int64), result)
def test_elemwise_with_ndarrays():
x = np.arange(3)
y = np.arange(12).reshape(4, 3)
a = from_array(x, chunks=(3,))
b = from_array(y, chunks=(2, 3))
assert_eq(x + a, 2 * x)
assert_eq(a + x, 2 * x)
assert_eq(x + b, x + y)
assert_eq(b + x, x + y)
assert_eq(a + y, x + y)
assert_eq(y + a, x + y)
# Error on shape mismatch
pytest.raises(ValueError, lambda: a + y.T)
pytest.raises(ValueError, lambda: a + np.arange(2))
def test_elemwise_differently_chunked():
x = np.arange(3)
y = np.arange(12).reshape(4, 3)
a = from_array(x, chunks=(3,))
b = from_array(y, chunks=(2, 2))
assert_eq(a + b, x + y)
assert_eq(b + a, x + y)
def test_elemwise_dtype():
values = [
da.from_array(np.ones(5, np.float32), chunks=3),
da.from_array(np.ones(5, np.int16), chunks=3),
da.from_array(np.ones(5, np.int64), chunks=3),
da.from_array(np.ones((), np.float64), chunks=()) * 1e200,
np.ones(5, np.float32),
1,
1.0,
1e200,
np.int64(1),
np.ones((), np.int64),
]
for x in values:
for y in values:
assert da.maximum(x, y).dtype == da.result_type(x, y)
def test_operators():
x = np.arange(10)
y = np.arange(10).reshape((10, 1))
a = from_array(x, chunks=(5,))
b = from_array(y, chunks=(5, 1))
c = a + 1
assert_eq(c, x + 1)
c = a + b
assert_eq(c, x + x.reshape((10, 1)))
expr = (3 / a * b) ** 2 > 5
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # divide by zero
assert_eq(expr, (3 / x * y) ** 2 > 5)
c = da.exp(a)
assert_eq(c, np.exp(x))
assert_eq(abs(-a), a)
assert_eq(a, +x)
def test_operator_dtype_promotion():
x = np.arange(10, dtype=np.float32)
y = np.array([1])
a = from_array(x, chunks=(5,))
assert_eq(x + 1, a + 1) # still float32
assert_eq(x + 1e50, a + 1e50) # now float64
assert_eq(x + y, a + y) # also float64
def test_field_access():
x = np.array([(1, 1.0), (2, 2.0)], dtype=[("a", "i4"), ("b", "f4")])
y = from_array(x, chunks=(1,))
assert_eq(y["a"], x["a"])
assert_eq(y[["b", "a"]], x[["b", "a"]])
assert same_keys(y[["b", "a"]], y[["b", "a"]])
def test_field_access_with_shape():
dtype = [("col1", ("f4", (3, 2))), ("col2", ("f4", 3))]
data = np.ones((100, 50), dtype=dtype)
x = da.from_array(data, 10)
assert_eq(x["col1"], data["col1"])
assert_eq(x[["col1"]], data[["col1"]])
assert_eq(x["col2"], data["col2"])
assert_eq(x[["col1", "col2"]], data[["col1", "col2"]])
def test_matmul():
rng = np.random.default_rng()
x = rng.random((5, 5))
y = rng.random((5, 2))
a = from_array(x, chunks=(1, 5))
b = from_array(y, chunks=(5, 1))
assert_eq(operator.matmul(a, b), a.dot(b))