/
test_base.py
1618 lines (1232 loc) · 47.1 KB
/
test_base.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 dataclasses
import datetime
import inspect
import os
import subprocess
import sys
import time
from collections import OrderedDict
from concurrent.futures import Executor
from enum import Enum, Flag, IntEnum, IntFlag
from operator import add, mul
from typing import Union
import pytest
from tlz import compose, curry, merge, partial
import dask
import dask.bag as db
from dask.base import (
DaskMethodsMixin,
clone_key,
collections_to_dsk,
compute,
compute_as_if_collection,
function_cache,
get_collection_names,
get_name_from_key,
get_scheduler,
is_dask_collection,
named_schedulers,
normalize_function,
normalize_token,
optimize,
persist,
replace_name_in_key,
tokenize,
unpack_collections,
visualize,
)
from dask.core import literal
from dask.delayed import Delayed, delayed
from dask.diagnostics import Profiler
from dask.highlevelgraph import HighLevelGraph
from dask.utils import tmpdir, tmpfile
from dask.utils_test import dec, import_or_none, inc
da = import_or_none("dask.array")
dd = import_or_none("dask.dataframe")
np = import_or_none("numpy")
sp = import_or_none("scipy.sparse")
pd = import_or_none("pandas")
def f1(a, b, c=1):
pass
def f2(a, b=1, c=2):
pass
def f3(a):
pass
def test_normalize_function():
assert normalize_function(f2)
assert normalize_function(lambda a: a)
assert normalize_function(partial(f2, b=2)) == normalize_function(partial(f2, b=2))
assert normalize_function(partial(f2, b=2)) != normalize_function(partial(f2, b=3))
assert normalize_function(partial(f1, b=2)) != normalize_function(partial(f2, b=2))
assert normalize_function(compose(f2, f3)) == normalize_function(compose(f2, f3))
assert normalize_function(compose(f2, f3)) != normalize_function(compose(f2, f1))
assert normalize_function(curry(f2)) == normalize_function(curry(f2))
assert normalize_function(curry(f2)) != normalize_function(curry(f1))
assert normalize_function(curry(f2, b=1)) == normalize_function(curry(f2, b=1))
assert normalize_function(curry(f2, b=1)) != normalize_function(curry(f2, b=2))
def test_tokenize():
a = (1, 2, 3)
assert isinstance(tokenize(a), (str, bytes))
@pytest.mark.skipif("not np")
def test_tokenize_numpy_array_consistent_on_values():
assert tokenize(np.random.RandomState(1234).random_sample(1000)) == tokenize(
np.random.RandomState(1234).random_sample(1000)
)
@pytest.mark.skipif("not np")
def test_tokenize_numpy_array_supports_uneven_sizes():
tokenize(np.random.random(7).astype(dtype="i2"))
@pytest.mark.skipif("not np")
def test_tokenize_discontiguous_numpy_array():
tokenize(np.random.random(8)[::2])
@pytest.mark.skipif("not np")
def test_tokenize_numpy_datetime():
tokenize(np.array(["2000-01-01T12:00:00"], dtype="M8[ns]"))
@pytest.mark.skipif("not np")
def test_tokenize_numpy_scalar():
assert tokenize(np.array(1.0, dtype="f8")) == tokenize(np.array(1.0, dtype="f8"))
assert tokenize(
np.array([(1, 2)], dtype=[("a", "i4"), ("b", "i8")])[0]
) == tokenize(np.array([(1, 2)], dtype=[("a", "i4"), ("b", "i8")])[0])
@pytest.mark.skipif("not np")
def test_tokenize_numpy_scalar_string_rep():
# Test tokenizing numpy scalars doesn't depend on their string representation
try:
np.set_string_function(lambda x: "foo")
assert tokenize(np.array(1)) != tokenize(np.array(2))
finally:
# Reset back to default
np.set_string_function(None)
@pytest.mark.skipif("not np")
def test_tokenize_numpy_array_on_object_dtype():
a = np.array(["a", "aa", "aaa"], dtype=object)
assert tokenize(a) == tokenize(a)
assert tokenize(np.array(["a", None, "aaa"], dtype=object)) == tokenize(
np.array(["a", None, "aaa"], dtype=object)
)
assert tokenize(
np.array([(1, "a"), (1, None), (1, "aaa")], dtype=object)
) == tokenize(np.array([(1, "a"), (1, None), (1, "aaa")], dtype=object))
# Trigger non-deterministic hashing for object dtype
class NoPickle:
pass
x = np.array(["a", None, NoPickle], dtype=object)
assert tokenize(x) != tokenize(x)
with dask.config.set({"tokenize.ensure-deterministic": True}):
with pytest.raises(RuntimeError, match="cannot be deterministically hashed"):
tokenize(x)
@pytest.mark.skipif("not np")
def test_tokenize_numpy_memmap_offset(tmpdir):
# Test two different memmaps into the same numpy file
fn = str(tmpdir.join("demo_data"))
with open(fn, "wb") as f:
f.write(b"ashekwicht")
with open(fn, "rb") as f:
mmap1 = np.memmap(f, dtype=np.uint8, mode="r", offset=0, shape=5)
mmap2 = np.memmap(f, dtype=np.uint8, mode="r", offset=5, shape=5)
assert tokenize(mmap1) != tokenize(mmap2)
# also make sure that they tokenize correctly when taking sub-arrays
sub1 = mmap1[1:-1]
sub2 = mmap2[1:-1]
assert tokenize(sub1) != tokenize(sub2)
@pytest.mark.skipif("not np")
def test_tokenize_numpy_memmap():
with tmpfile(".npy") as fn:
x = np.arange(5)
np.save(fn, x)
y = tokenize(np.load(fn, mmap_mode="r"))
with tmpfile(".npy") as fn:
x = np.arange(5)
np.save(fn, x)
z = tokenize(np.load(fn, mmap_mode="r"))
assert y != z
with tmpfile(".npy") as fn:
x = np.random.normal(size=(10, 10))
np.save(fn, x)
mm = np.load(fn, mmap_mode="r")
mm2 = np.load(fn, mmap_mode="r")
a = tokenize(mm[0, :])
b = tokenize(mm[1, :])
c = tokenize(mm[0:3, :])
d = tokenize(mm[:, 0])
assert len({a, b, c, d}) == 4
assert tokenize(mm) == tokenize(mm2)
assert tokenize(mm[1, :]) == tokenize(mm2[1, :])
@pytest.mark.skipif("not np")
def test_tokenize_numpy_memmap_no_filename():
# GH 1562:
with tmpfile(".npy") as fn1, tmpfile(".npy") as fn2:
x = np.arange(5)
np.save(fn1, x)
np.save(fn2, x)
a = np.load(fn1, mmap_mode="r")
b = a + a
assert tokenize(b) == tokenize(b)
@pytest.mark.skipif("not np")
def test_tokenize_numpy_ufunc_consistent():
assert tokenize(np.sin) == "02106e2c67daf452fb480d264e0dac21"
assert tokenize(np.cos) == "c99e52e912e4379882a9a4b387957a0b"
# Make a ufunc that isn't in the numpy namespace. Similar to
# any found in other packages.
inc = np.frompyfunc(lambda x: x + 1, 1, 1)
assert tokenize(inc) == tokenize(inc)
def test_tokenize_partial_func_args_kwargs_consistent():
f = partial(f3, f2, c=f1)
res = normalize_token(f)
sol = (
b"\x80\x04\x95\x1f\x00\x00\x00\x00\x00\x00\x00\x8c\x14dask.tests.test_base\x94\x8c\x02f3\x94\x93\x94.",
(
b"\x80\x04\x95\x1f\x00\x00\x00\x00\x00\x00\x00\x8c\x14dask.tests.test_base\x94\x8c\x02f2\x94\x93\x94.",
),
(
(
"c",
b"\x80\x04\x95\x1f\x00\x00\x00\x00\x00\x00\x00\x8c\x14dask.tests.test_base\x94\x8c\x02f1\x94\x93\x94.",
),
),
)
assert res == sol
def test_normalize_base():
for i in [1, 1.1, "1", slice(1, 2, 3), datetime.date(2021, 6, 25)]:
assert normalize_token(i) is i
def test_tokenize_object():
o = object()
# Defaults to non-deterministic tokenization
assert normalize_token(o) != normalize_token(o)
with dask.config.set({"tokenize.ensure-deterministic": True}):
with pytest.raises(RuntimeError, match="cannot be deterministically hashed"):
normalize_token(o)
def test_tokenize_function_cloudpickle():
a, b = (lambda x: x, lambda x: x)
# No error by default
tokenize(a)
with dask.config.set({"tokenize.ensure-deterministic": True}):
with pytest.raises(RuntimeError, match="may not be deterministically hashed"):
tokenize(b)
def test_tokenize_callable():
def my_func(a, b, c=1):
return a + b + c
assert tokenize(my_func) == tokenize(my_func) # Consistent token
@pytest.mark.skipif("not pd")
def test_tokenize_pandas():
a = pd.DataFrame({"x": [1, 2, 3], "y": ["4", "asd", None]}, index=[1, 2, 3])
b = pd.DataFrame({"x": [1, 2, 3], "y": ["4", "asd", None]}, index=[1, 2, 3])
assert tokenize(a) == tokenize(b)
b.index.name = "foo"
assert tokenize(a) != tokenize(b)
a = pd.DataFrame({"x": [1, 2, 3], "y": ["a", "b", "a"]})
b = pd.DataFrame({"x": [1, 2, 3], "y": ["a", "b", "a"]})
a["z"] = a.y.astype("category")
assert tokenize(a) != tokenize(b)
b["z"] = a.y.astype("category")
assert tokenize(a) == tokenize(b)
@pytest.mark.skipif("not pd")
def test_tokenize_pandas_invalid_unicode():
# see https://github.com/dask/dask/issues/2713
df = pd.DataFrame(
{"x\ud83d": [1, 2, 3], "y\ud83d": ["4", "asd\ud83d", None]}, index=[1, 2, 3]
)
tokenize(df)
@pytest.mark.skipif("not pd")
def test_tokenize_pandas_mixed_unicode_bytes():
df = pd.DataFrame(
{"ö".encode(): [1, 2, 3], "ö": ["ö", "ö".encode(), None]},
index=[1, 2, 3],
)
tokenize(df)
@pytest.mark.skipif("not pd")
def test_tokenize_pandas_no_pickle():
class NoPickle:
# pickling not supported because it is a local class
pass
df = pd.DataFrame({"x": ["foo", None, NoPickle()]})
tokenize(df)
@pytest.mark.skipif("not dd")
def test_tokenize_pandas_extension_array():
arrays = [
pd.array([1, 0, None], dtype="Int64"),
pd.array(["2000"], dtype="Period[D]"),
pd.array([1, 0, 0], dtype="Sparse[int]"),
pd.array([pd.Timestamp("2000")], dtype="datetime64[ns]"),
pd.array([pd.Timestamp("2000", tz="CET")], dtype="datetime64[ns, CET]"),
pd.array(
["a", "b"],
dtype=pd.api.types.CategoricalDtype(["a", "b", "c"], ordered=False),
),
]
arrays.extend(
[
pd.array(["a", "b", None], dtype="string"),
pd.array([True, False, None], dtype="boolean"),
]
)
for arr in arrays:
assert tokenize(arr) == tokenize(arr)
@pytest.mark.skipif("not pd")
def test_tokenize_pandas_index():
idx = pd.Index(["a", "b"])
assert tokenize(idx) == tokenize(idx)
idx = pd.MultiIndex.from_product([["a", "b"], [0, 1]])
assert tokenize(idx) == tokenize(idx)
def test_tokenize_kwargs():
assert tokenize(5, x=1) == tokenize(5, x=1)
assert tokenize(5) != tokenize(5, x=1)
assert tokenize(5, x=1) != tokenize(5, x=2)
assert tokenize(5, x=1) != tokenize(5, y=1)
assert tokenize(5, foo="bar") != tokenize(5, {"foo": "bar"})
def test_tokenize_same_repr():
class Foo:
def __init__(self, x):
self.x = x
def __repr__(self):
return "a foo"
assert tokenize(Foo(1)) != tokenize(Foo(2))
def test_tokenize_method():
class Foo:
def __init__(self, x):
self.x = x
def __dask_tokenize__(self):
return self.x
a, b = Foo(1), Foo(2)
assert tokenize(a) == tokenize(a)
assert tokenize(a) != tokenize(b)
for ensure in [True, False]:
with dask.config.set({"tokenize.ensure-deterministic": ensure}):
assert tokenize(a) == tokenize(a)
# dispatch takes precedence
before = tokenize(a)
normalize_token.register(Foo, lambda self: self.x + 1)
after = tokenize(a)
assert before != after
@pytest.mark.skipif("not np")
def test_tokenize_sequences():
assert tokenize([1]) != tokenize([2])
assert tokenize([1]) != tokenize((1,))
assert tokenize([1]) == tokenize([1])
x = np.arange(2000) # long enough to drop information in repr
y = np.arange(2000)
y[1000] = 0 # middle isn't printed in repr
assert tokenize([x]) != tokenize([y])
def test_tokenize_dict():
assert tokenize({"x": 1, 1: "x"}) == tokenize({"x": 1, 1: "x"})
def test_tokenize_set():
assert tokenize({1, 2, "x", (1, "x")}) == tokenize({1, 2, "x", (1, "x")})
def test_tokenize_ordered_dict():
from collections import OrderedDict
a = OrderedDict([("a", 1), ("b", 2)])
b = OrderedDict([("a", 1), ("b", 2)])
c = OrderedDict([("b", 2), ("a", 1)])
assert tokenize(a) == tokenize(b)
assert tokenize(a) != tokenize(c)
def test_tokenize_timedelta():
assert tokenize(datetime.timedelta(days=1)) == tokenize(datetime.timedelta(days=1))
assert tokenize(datetime.timedelta(days=1)) != tokenize(datetime.timedelta(days=2))
@pytest.mark.parametrize("enum_type", [Enum, IntEnum, IntFlag, Flag])
def test_tokenize_enum(enum_type):
class Color(enum_type):
RED = 1
BLUE = 2
assert tokenize(Color.RED) == tokenize(Color.RED)
assert tokenize(Color.RED) != tokenize(Color.BLUE)
ADataClass = dataclasses.make_dataclass("ADataClass", [("a", int)])
BDataClass = dataclasses.make_dataclass("BDataClass", [("a", Union[int, float])]) # type: ignore
def test_tokenize_dataclass():
a1 = ADataClass(1)
a2 = ADataClass(2)
assert tokenize(a1) == tokenize(a1)
assert tokenize(a1) != tokenize(a2)
# Same field names and values, but dataclass types are different
b1 = BDataClass(1)
assert tokenize(a1) != tokenize(b1)
class SubA(ADataClass):
pass
assert dataclasses.is_dataclass(
SubA
), "Python regression: SubA should be considered a dataclass"
assert tokenize(SubA(1)) == tokenize(SubA(1))
assert tokenize(SubA(1)) != tokenize(a1)
# Same name, same values, new definition: tokenize differently
ADataClassRedefinedDifferently = dataclasses.make_dataclass(
"ADataClass", [("a", Union[int, str])]
)
assert tokenize(a1) != tokenize(ADataClassRedefinedDifferently(1))
def test_tokenize_range():
assert tokenize(range(5, 10, 2)) == tokenize(range(5, 10, 2)) # Identical ranges
assert tokenize(range(5, 10, 2)) != tokenize(range(1, 10, 2)) # Different start
assert tokenize(range(5, 10, 2)) != tokenize(range(5, 15, 2)) # Different stop
assert tokenize(range(5, 10, 2)) != tokenize(range(5, 10, 1)) # Different step
@pytest.mark.skipif("not np")
def test_tokenize_object_array_with_nans():
a = np.array(["foo", "Jos\xe9", np.nan], dtype="O")
assert tokenize(a) == tokenize(a)
@pytest.mark.parametrize(
"x", [1, True, "a", b"a", 1.0, 1j, 1.0j, [], (), {}, None, str, int]
)
def test_tokenize_base_types(x):
assert tokenize(x) == tokenize(x), x
def test_tokenize_literal():
assert tokenize(literal(["x", 1])) == tokenize(literal(["x", 1]))
@pytest.mark.skipif("not np")
@pytest.mark.filterwarnings("ignore:the matrix:PendingDeprecationWarning")
def test_tokenize_numpy_matrix():
rng = np.random.RandomState(1234)
a = np.asmatrix(rng.rand(100))
b = a.copy()
assert tokenize(a) == tokenize(b)
b[:10] = 1
assert tokenize(a) != tokenize(b)
@pytest.mark.skipif("not sp")
@pytest.mark.parametrize("cls_name", ("dia", "bsr", "coo", "csc", "csr", "dok", "lil"))
def test_tokenize_dense_sparse_array(cls_name):
rng = np.random.RandomState(1234)
a = sp.rand(10, 10000, random_state=rng).asformat(cls_name)
b = a.copy()
assert tokenize(a) == tokenize(b)
# modifying the data values
if hasattr(b, "data"):
b.data[:10] = 1
elif cls_name == "dok":
b[3, 3] = 1
else:
raise ValueError
assert tokenize(a) != tokenize(b)
# modifying the data indices
b = a.copy().asformat("coo")
b.row[:10] = np.arange(10)
b = b.asformat(cls_name)
assert tokenize(a) != tokenize(b)
@pytest.mark.skipif(
sys.platform == "win32" and sys.version_info[:2] == (3, 9),
reason="https://github.com/ipython/ipython/issues/12197",
)
def test_tokenize_object_with_recursion_error():
cycle = dict(a=None)
cycle["a"] = cycle
assert len(tokenize(cycle)) == 32
with dask.config.set({"tokenize.ensure-deterministic": True}):
with pytest.raises(RuntimeError, match="cannot be deterministically hashed"):
tokenize(cycle)
def test_tokenize_datetime_date():
# Same date
assert tokenize(datetime.date(2021, 6, 25)) == tokenize(datetime.date(2021, 6, 25))
# Different year
assert tokenize(datetime.date(2021, 6, 25)) != tokenize(datetime.date(2022, 6, 25))
# Different month
assert tokenize(datetime.date(2021, 6, 25)) != tokenize(datetime.date(2021, 7, 25))
# Different day
assert tokenize(datetime.date(2021, 6, 25)) != tokenize(datetime.date(2021, 6, 26))
def test_is_dask_collection():
class DummyCollection:
def __init__(self, dsk):
self.dask = dsk
def __dask_graph__(self):
return self.dask
x = delayed(1) + 2
assert is_dask_collection(x)
assert not is_dask_collection(2)
assert is_dask_collection(DummyCollection({}))
assert not is_dask_collection(DummyCollection)
def test_unpack_collections():
a = delayed(1) + 5
b = a + 1
c = a + 2
def build(a, b, c, iterator):
t = (
a,
b, # Top-level collections
{
"a": a, # dict
a: b, # collections as keys
"b": [1, 2, [b]], # list
"c": 10, # other builtins pass through unchanged
"d": (c, 2), # tuple
"e": {a, 2, 3}, # set
"f": OrderedDict([("a", a)]),
}, # OrderedDict
iterator,
) # Iterator
t[2]["f"] = ADataClass(a=a)
t[2]["g"] = (ADataClass, a)
return t
args = build(a, b, c, (i for i in [a, b, c]))
collections, repack = unpack_collections(*args)
assert len(collections) == 3
# Replace collections with `'~a'` strings
result = repack(["~a", "~b", "~c"])
sol = build("~a", "~b", "~c", ["~a", "~b", "~c"])
assert result == sol
# traverse=False
collections, repack = unpack_collections(*args, traverse=False)
assert len(collections) == 2 # just a and b
assert repack(collections) == args
# No collections
collections, repack = unpack_collections(1, 2, {"a": 3})
assert not collections
assert repack(collections) == (1, 2, {"a": 3})
# Result that looks like a task
def fail(*args):
raise ValueError("Shouldn't have been called") # pragma: nocover
collections, repack = unpack_collections(
a, (fail, 1), [(fail, 2, 3)], traverse=False
)
repack(collections) # Smoketest task literals
repack([(fail, 1)]) # Smoketest results that look like tasks
def test_get_collection_names():
class DummyCollection:
def __init__(self, dsk, keys):
self.dask = dsk
self.keys = keys
def __dask_graph__(self):
return self.dask
def __dask_keys__(self):
return self.keys
with pytest.raises(TypeError):
get_collection_names(object())
# Keys must either be a string or a tuple where the first element is a string
with pytest.raises(TypeError):
get_collection_names(DummyCollection({1: 2}, [1]))
with pytest.raises(TypeError):
get_collection_names(DummyCollection({(): 1}, [()]))
with pytest.raises(TypeError):
get_collection_names(DummyCollection({(1,): 1}, [(1,)]))
assert get_collection_names(DummyCollection({}, [])) == set()
# Arbitrary hashables
h1 = object()
h2 = object()
# __dask_keys__() returns a nested list
assert get_collection_names(
DummyCollection(
{("a-1", h1): 1, ("a-1", h2): 2, "b-2": 3, "c": 4},
[[[("a-1", h1), ("a-1", h2), "b-2", "c"]]],
)
) == {"a-1", "b-2", "c"}
def test_get_name_from_key():
# Arbitrary hashables
h1 = object()
h2 = object()
assert get_name_from_key("foo") == "foo"
assert get_name_from_key("foo-123"), "foo-123"
assert get_name_from_key(("foo-123", h1, h2)) == "foo-123"
with pytest.raises(TypeError):
get_name_from_key(1)
with pytest.raises(TypeError):
get_name_from_key(())
with pytest.raises(TypeError):
get_name_from_key((1,))
def test_replace_name_in_keys():
assert replace_name_in_key("foo", {}) == "foo"
assert replace_name_in_key("foo", {"bar": "baz"}) == "foo"
assert replace_name_in_key("foo", {"foo": "bar", "baz": "asd"}) == "bar"
assert replace_name_in_key("foo-123", {"foo-123": "bar-456"}) == "bar-456"
h1 = object() # Arbitrary hashables
h2 = object()
assert replace_name_in_key(("foo-123", h1, h2), {"foo-123": "bar"}) == (
"bar",
h1,
h2,
)
with pytest.raises(TypeError):
replace_name_in_key(1, {})
with pytest.raises(TypeError):
replace_name_in_key((), {})
with pytest.raises(TypeError):
replace_name_in_key((1,), {})
class Tuple(DaskMethodsMixin):
__slots__ = ("_dask", "_keys")
__dask_scheduler__ = staticmethod(dask.threaded.get)
def __init__(self, dsk, keys):
self._dask = dsk
self._keys = keys
def __add__(self, other):
if not isinstance(other, Tuple):
return NotImplemented # pragma: nocover
return Tuple(merge(self._dask, other._dask), self._keys + other._keys)
def __dask_graph__(self):
return self._dask
def __dask_keys__(self):
return self._keys
def __dask_layers__(self):
return tuple(get_collection_names(self))
def __dask_tokenize__(self):
return self._keys
def __dask_postcompute__(self):
return tuple, ()
def __dask_postpersist__(self):
return Tuple._rebuild, (self._keys,)
@staticmethod
def _rebuild(dsk, keys, *, rename=None):
if rename:
keys = [replace_name_in_key(key, rename) for key in keys]
return Tuple(dsk, keys)
def test_custom_collection():
# Arbitrary hashables
h1 = object()
h2 = object()
dsk = {("x", h1): 1, ("x", h2): 2}
dsk2 = {("y", h1): (add, ("x", h1), ("x", h2)), ("y", h2): (add, ("y", h1), 1)}
dsk2.update(dsk)
dsk3 = {"z": (add, ("y", h1), ("y", h2))}
dsk3.update(dsk2)
w = Tuple({}, []) # A collection can have no keys at all
x = Tuple(dsk, [("x", h1), ("x", h2)])
y = Tuple(dsk2, [("y", h1), ("y", h2)])
z = Tuple(dsk3, ["z"])
# Collection with multiple names
t = w + x + y + z
# __slots__ defined on base mixin class propagates
with pytest.raises(AttributeError):
x.foo = 1
# is_dask_collection
assert is_dask_collection(w)
assert is_dask_collection(x)
assert is_dask_collection(y)
assert is_dask_collection(z)
assert is_dask_collection(t)
# tokenize
assert tokenize(w) == tokenize(w)
assert tokenize(x) == tokenize(x)
assert tokenize(y) == tokenize(y)
assert tokenize(z) == tokenize(z)
assert tokenize(t) == tokenize(t)
# All tokens are unique
assert len({tokenize(coll) for coll in (w, x, y, z, t)}) == 5
# get_collection_names
assert get_collection_names(w) == set()
assert get_collection_names(x) == {"x"}
assert get_collection_names(y) == {"y"}
assert get_collection_names(z) == {"z"}
assert get_collection_names(t) == {"x", "y", "z"}
# compute
assert w.compute() == ()
assert x.compute() == (1, 2)
assert y.compute() == (3, 4)
assert z.compute() == (7,)
assert dask.compute(w, [{"x": x}, y, z]) == ((), [{"x": (1, 2)}, (3, 4), (7,)])
assert t.compute() == (1, 2, 3, 4, 7)
# persist
t2 = t.persist()
assert isinstance(t2, Tuple)
assert t2._keys == t._keys
assert sorted(t2._dask.values()) == [1, 2, 3, 4, 7]
assert t2.compute() == (1, 2, 3, 4, 7)
w2, x2, y2, z2 = dask.persist(w, x, y, z)
assert y2._keys == y._keys
assert y2._dask == {("y", h1): 3, ("y", h2): 4}
assert y2.compute() == (3, 4)
t3 = x2 + y2 + z2
assert t3.compute() == (1, 2, 3, 4, 7)
# __dask_postpersist__ with name change
rebuild, args = w.__dask_postpersist__()
w3 = rebuild({}, *args, rename={"w": "w3"})
assert w3.compute() == ()
rebuild, args = x.__dask_postpersist__()
x3 = rebuild({("x3", h1): 10, ("x3", h2): 20}, *args, rename={"x": "x3"})
assert x3.compute() == (10, 20)
rebuild, args = z.__dask_postpersist__()
z3 = rebuild({"z3": 70}, *args, rename={"z": "z3"})
assert z3.compute() == (70,)
def test_compute_no_opt():
# Bag does `fuse` by default. Test that with `optimize_graph=False` that
# doesn't get called. We check this by using a callback to track the keys
# that are computed.
from dask.callbacks import Callback
b = db.from_sequence(range(100), npartitions=4)
add1 = partial(add, 1)
mul2 = partial(mul, 2)
o = b.map(add1).map(mul2)
# Check that with the kwarg, the optimization doesn't happen
keys = []
with Callback(pretask=lambda key, *args: keys.append(key)):
o.compute(scheduler="single-threaded", optimize_graph=False)
assert len([k for k in keys if "mul" in k[0]]) == 4
assert len([k for k in keys if "add" in k[0]]) == 4
# Check that without the kwarg, the optimization does happen
keys = []
with Callback(pretask=lambda key, *args: keys.append(key)):
o.compute(scheduler="single-threaded")
# Names of fused tasks have been merged, and the original key is an alias.
# Otherwise, the lengths below would be 4 and 0.
assert len([k for k in keys if "mul" in k[0]]) == 8
assert len([k for k in keys if "add" in k[0]]) == 4
assert len([k for k in keys if "add-mul" in k[0]]) == 4 # See? Renamed
@pytest.mark.skipif("not da")
def test_compute_array():
arr = np.arange(100).reshape((10, 10))
darr = da.from_array(arr, chunks=(5, 5))
darr1 = darr + 1
darr2 = darr + 2
out1, out2 = compute(darr1, darr2)
assert np.allclose(out1, arr + 1)
assert np.allclose(out2, arr + 2)
@pytest.mark.skipif("not da")
def test_persist_array():
from dask.array.utils import assert_eq
arr = np.arange(100).reshape((10, 10))
x = da.from_array(arr, chunks=(5, 5))
x = (x + 1) - x.mean(axis=0)
y = x.persist()
assert_eq(x, y)
assert set(y.dask).issubset(x.dask)
assert len(y.dask) == y.npartitions
@pytest.mark.skipif("not da")
def test_persist_array_rename():
a = da.zeros(4, dtype=int, chunks=2)
rebuild, args = a.__dask_postpersist__()
dsk = {("b", 0): np.array([1, 2]), ("b", 1): np.array([3, 4])}
b = rebuild(dsk, *args, rename={a.name: "b"})
assert isinstance(b, da.Array)
assert b.name == "b"
assert b.__dask_keys__() == [("b", 0), ("b", 1)]
da.utils.assert_eq(b, [1, 2, 3, 4])
@pytest.mark.skipif("not dd")
def test_compute_dataframe():
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 5, 3, 3]})
ddf = dd.from_pandas(df, npartitions=2)
ddf1 = ddf.a + 1
ddf2 = ddf.a + ddf.b
out1, out2 = compute(ddf1, ddf2)
dd.utils.assert_eq(out1, df.a + 1)
dd.utils.assert_eq(out2, df.a + df.b)
@pytest.mark.skipif("not dd")
def test_persist_dataframe():
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
ddf1 = dd.from_pandas(df, npartitions=2) * 2
assert len(ddf1.__dask_graph__()) == 4
ddf2 = ddf1.persist()
assert isinstance(ddf2, dd.DataFrame)
assert len(ddf2.__dask_graph__()) == 2
dd.utils.assert_eq(ddf2, ddf1)
@pytest.mark.skipif("not dd")
def test_persist_series():
ds = pd.Series([1, 2, 3, 4])
dds1 = dd.from_pandas(ds, npartitions=2) * 2
assert len(dds1.__dask_graph__()) == 4
dds2 = dds1.persist()
assert isinstance(dds2, dd.Series)
assert len(dds2.__dask_graph__()) == 2
dd.utils.assert_eq(dds2, dds1)
@pytest.mark.skipif("not dd")
def test_persist_scalar():
ds = pd.Series([1, 2, 3, 4])
dds1 = dd.from_pandas(ds, npartitions=2).min()
assert len(dds1.__dask_graph__()) == 5
dds2 = dds1.persist()
assert isinstance(dds2, dd.core.Scalar)
assert len(dds2.__dask_graph__()) == 1
dd.utils.assert_eq(dds2, dds1)
@pytest.mark.skipif("not dd")
def test_persist_dataframe_rename():
df1 = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
df2 = pd.DataFrame({"a": [2, 3, 5, 6], "b": [6, 7, 9, 10]})
ddf1 = dd.from_pandas(df1, npartitions=2)
rebuild, args = ddf1.__dask_postpersist__()
dsk = {("x", 0): df2.iloc[:2], ("x", 1): df2.iloc[2:]}
ddf2 = rebuild(dsk, *args, rename={ddf1._name: "x"})
assert ddf2.__dask_keys__() == [("x", 0), ("x", 1)]
dd.utils.assert_eq(ddf2, df2)
@pytest.mark.skipif("not dd")
def test_persist_series_rename():
ds1 = pd.Series([1, 2, 3, 4])
ds2 = pd.Series([5, 6, 7, 8])
dds1 = dd.from_pandas(ds1, npartitions=2)
rebuild, args = dds1.__dask_postpersist__()
dsk = {("x", 0): ds2.iloc[:2], ("x", 1): ds2.iloc[2:]}
dds2 = rebuild(dsk, *args, rename={dds1._name: "x"})
assert dds2.__dask_keys__() == [("x", 0), ("x", 1)]
dd.utils.assert_eq(dds2, ds2)
@pytest.mark.skipif("not dd")
def test_persist_scalar_rename():
ds1 = pd.Series([1, 2, 3, 4])
dds1 = dd.from_pandas(ds1, npartitions=2).min()
rebuild, args = dds1.__dask_postpersist__()
dds2 = rebuild({("x", 0): 5}, *args, rename={dds1._name: "x"})
assert dds2.__dask_keys__() == [("x", 0)]
dd.utils.assert_eq(dds2, 5)
@pytest.mark.skipif("not dd or not da")
def test_compute_array_dataframe():
arr = np.arange(100).reshape((10, 10))
darr = da.from_array(arr, chunks=(5, 5)) + 1
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 5, 3, 3]})
ddf = dd.from_pandas(df, npartitions=2).a + 2
arr_out, df_out = compute(darr, ddf)
assert np.allclose(arr_out, arr + 1)
dd.utils.assert_eq(df_out, df.a + 2)
@pytest.mark.skipif("not dd")
def test_compute_dataframe_valid_unicode_in_bytes():
df = pd.DataFrame(data=np.random.random((3, 1)), columns=["ö".encode()])
dd.from_pandas(df, npartitions=4)
@pytest.mark.skipif("not dd")
def test_compute_dataframe_invalid_unicode():
# see https://github.com/dask/dask/issues/2713
df = pd.DataFrame(data=np.random.random((3, 1)), columns=["\ud83d"])
dd.from_pandas(df, npartitions=4)
@pytest.mark.skipif("not da")
def test_compute_array_bag():
x = da.arange(5, chunks=2)
b = db.from_sequence([1, 2, 3])
pytest.raises(ValueError, lambda: compute(x, b))
xx, bb = compute(x, b, scheduler="single-threaded")