-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
_expr.py
4115 lines (3268 loc) · 125 KB
/
_expr.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 datetime
import functools
import numbers
import operator
import warnings
from collections import defaultdict
from collections.abc import Callable, Mapping
import numpy as np
import pandas as pd
from dask._task_spec import Alias, DataNode, Task, TaskRef, execute_graph
from dask.array import Array
from dask.core import flatten
from dask.dataframe import methods
from dask.dataframe._pyarrow import to_pyarrow_string
from dask.dataframe.core import (
_concat,
_get_divisions_map_partitions,
_rename,
apply_and_enforce,
has_parallel_type,
is_dataframe_like,
is_index_like,
is_series_like,
make_meta,
pd_split,
safe_head,
total_mem_usage,
)
from dask.dataframe.dispatch import meta_nonempty
from dask.dataframe.rolling import CombinedOutput, _head_timedelta, overlap_chunk
from dask.dataframe.shuffle import drop_overlap, get_overlap
from dask.dataframe.utils import (
clear_known_categories,
drop_by_shallow_copy,
raise_on_meta_error,
valid_divisions,
)
from dask.tokenize import normalize_token
from dask.typing import Key, no_default
from dask.utils import (
M,
funcname,
get_meta_library,
has_keyword,
is_arraylike,
partial_by_order,
pseudorandom,
random_state_data,
)
from pandas.errors import PerformanceWarning
from tlz import merge_sorted, partition, unique
from dask_expr import _core as core
from dask_expr._util import (
_calc_maybe_new_divisions,
_convert_to_list,
_tokenize_deterministic,
_tokenize_partial,
is_scalar,
)
class Expr(core.Expr):
"""Primary class for all Expressions
This mostly includes Dask protocols and various Pandas-like method
definitions to make us look more like a DataFrame.
"""
_is_length_preserving = False
_filter_passthrough = False
def _filter_passthrough_available(self, parent, dependents):
return self._filter_passthrough and is_filter_pushdown_available(
self, parent, dependents
)
@functools.cached_property
def ndim(self):
meta = self._meta
try:
return meta.ndim
except AttributeError:
return 0
def __dask_keys__(self):
return [(self._name, i) for i in range(self.npartitions)]
def optimize(self, **kwargs):
return optimize(self, **kwargs)
def __hash__(self):
return hash(self._name)
@property
def index(self):
return Index(self)
@property
def size(self):
return Size(self)
@property
def nbytes(self):
return NBytes(self)
def __getitem__(self, other):
if isinstance(other, Expr):
if not are_co_aligned(self, other):
return FilterAlign(self, other)
return Filter(self, other)
else:
return Projection(self, other) # df[["a", "b", "c"]]
def __bool__(self):
raise ValueError(
f"The truth value of a {self.__class__.__name__} is ambiguous. "
"Use a.any() or a.all()."
)
def __add__(self, other):
return Add(self, other)
def __radd__(self, other):
return Add(other, self)
def __sub__(self, other):
return Sub(self, other)
def __rsub__(self, other):
return Sub(other, self)
def __mul__(self, other):
return Mul(self, other)
def __rmul__(self, other):
return Mul(other, self)
def __pow__(self, power):
return Pow(self, power)
def __rpow__(self, power):
return Pow(power, self)
def __truediv__(self, other):
return Div(self, other)
def __rtruediv__(self, other):
return Div(other, self)
def __lt__(self, other):
return LT(self, other)
def __rlt__(self, other):
return LT(other, self)
def __gt__(self, other):
return GT(self, other)
def __rgt__(self, other):
return GT(other, self)
def __le__(self, other):
return LE(self, other)
def __rle__(self, other):
return LE(other, self)
def __ge__(self, other):
return GE(self, other)
def __rge__(self, other):
return GE(other, self)
def __eq__(self, other):
return EQ(self, other)
def __ne__(self, other):
return NE(self, other)
def __and__(self, other):
return And(self, other)
def __rand__(self, other):
return And(other, self)
def __or__(self, other):
return Or(self, other)
def __ror__(self, other):
return Or(other, self)
def __xor__(self, other):
return XOr(self, other)
def __rxor__(self, other):
return XOr(other, self)
def __invert__(self):
return Invert(self)
def __neg__(self):
return Neg(self)
def __pos__(self):
return Pos(self)
def __mod__(self, other):
return Mod(self, other)
def __rmod__(self, other):
return Mod(other, self)
def __floordiv__(self, other):
return FloorDiv(self, other)
def __rfloordiv__(self, other):
return FloorDiv(other, self)
def __divmod__(self, other):
res1 = self // other
res2 = self % other
return res1, res2
def __rdivmod__(self, other):
res1 = other // self
res2 = other % self
return res1, res2
def sum(self, skipna=True, numeric_only=False, split_every=False, axis=0):
return Sum(self, skipna, numeric_only, split_every, axis)
def prod(self, skipna=True, numeric_only=False, split_every=False, axis=0):
return Prod(self, skipna, numeric_only, split_every, axis)
def var(self, axis=0, skipna=True, ddof=1, numeric_only=False, split_every=False):
if axis == 0:
return Var(self, skipna, ddof, numeric_only, split_every)
elif axis == 1:
return VarColumns(self, skipna, ddof, numeric_only)
else:
raise ValueError(f"axis={axis} not supported. Please specify 0 or 1")
def std(self, axis=0, skipna=True, ddof=1, numeric_only=False, split_every=False):
return Sqrt(self.var(axis, skipna, ddof, numeric_only, split_every=split_every))
def mean(self, skipna=True, numeric_only=False, split_every=False, axis=0):
return Mean(
self,
skipna=skipna,
numeric_only=numeric_only,
split_every=split_every,
axis=axis,
)
def max(self, skipna=True, numeric_only=False, split_every=False, axis=0):
return Max(self, skipna, numeric_only, split_every, axis)
def any(self, skipna=True, split_every=False):
return Any(self, skipna=skipna, split_every=split_every)
def all(self, skipna=True, split_every=False):
return All(self, skipna=skipna, split_every=split_every)
def idxmin(self, skipna=True, numeric_only=False, split_every=False):
return IdxMin(
self, skipna=skipna, numeric_only=numeric_only, split_every=split_every
)
def idxmax(self, skipna=True, numeric_only=False, split_every=False):
return IdxMax(
self, skipna=skipna, numeric_only=numeric_only, split_every=split_every
)
def mode(self, dropna=True, split_every=False):
return Mode(self, dropna=dropna, split_every=split_every)
def min(self, skipna=True, numeric_only=False, split_every=False, axis=0):
return Min(self, skipna, numeric_only, split_every=split_every, axis=axis)
def count(self, numeric_only=False, split_every=False):
return Count(self, numeric_only, split_every)
def cumsum(self, skipna=True):
from dask_expr._cumulative import CumSum
return CumSum(self, skipna=skipna)
def cumprod(self, skipna=True):
from dask_expr._cumulative import CumProd
return CumProd(self, skipna=skipna)
def cummax(self, skipna=True):
from dask_expr._cumulative import CumMax
return CumMax(self, skipna=skipna)
def cummin(self, skipna=True):
from dask_expr._cumulative import CumMin
return CumMin(self, skipna=skipna)
def abs(self):
return Abs(self)
def astype(self, dtypes):
return AsType(self, dtypes)
def clip(self, lower=None, upper=None, axis=None):
return Clip(self, lower=lower, upper=upper, axis=axis)
def combine_first(self, other):
if are_co_aligned(self, other):
return CombineFirst(self, other=other)
else:
return CombineFirstAlign(self, other)
def to_timestamp(self, freq=None, how="start"):
return ToTimestamp(self, freq=freq, how=how)
def isna(self):
return IsNa(self)
def isnull(self):
# These are the same anyway
return IsNa(self)
def round(self, decimals=0):
return Round(self, decimals=decimals)
def where(self, cond, other=np.nan):
if not are_co_aligned(self, *[c for c in [cond, other] if isinstance(c, Expr)]):
return WhereAlign(self, cond=cond, other=other)
return Where(self, cond=cond, other=other)
def mask(self, cond, other=np.nan):
if not are_co_aligned(self, *[c for c in [cond, other] if isinstance(c, Expr)]):
return MaskAlign(self, cond=cond, other=other)
return Mask(self, cond=cond, other=other)
def apply(self, function, *args, meta=None, **kwargs):
return Apply(self, function, args, meta, kwargs)
def replace(self, to_replace=None, value=no_default, regex=False):
return Replace(self, to_replace=to_replace, value=value, regex=regex)
def fillna(self, value=None):
if isinstance(value, Expr) and not are_co_aligned(self, value):
return FillnaAlign(self, value=value)
return Fillna(self, value=value)
def rename_axis(
self, mapper=no_default, index=no_default, columns=no_default, axis=0
):
return RenameAxis(self, mapper=mapper, index=index, columns=columns, axis=axis)
def align(self, other, join="outer", axis=None, fill_value=None):
from dask_expr._collection import new_collection
if not are_co_aligned(self, other):
aligned = AlignAlignPartitions(self, other, join, axis, fill_value)
else:
aligned = _Align(self, other, join, axis=axis, fill_value=fill_value)
return new_collection(AlignGetitem(aligned, position=0)), new_collection(
AlignGetitem(aligned, position=1)
)
def nunique_approx(self, split_every=None):
return NuniqueApprox(self, b=16, split_every=split_every)
def memory_usage_per_partition(self, index=True, deep=False):
return MemoryUsagePerPartition(self, index, deep)
@functools.cached_property
def divisions(self):
return tuple(self._divisions())
def _divisions(self):
raise NotImplementedError()
@property
def known_divisions(self):
"""Whether divisions are already known"""
return len(self.divisions) > 0 and self.divisions[0] is not None
@property
def npartitions(self):
if "npartitions" in self._parameters:
idx = self._parameters.index("npartitions")
return self.operands[idx]
else:
return len(self.divisions) - 1
@property
def columns(self) -> list:
try:
return list(self._meta.columns)
except AttributeError:
if self.ndim == 1:
return [self.name]
return []
except Exception:
raise
@functools.cached_property
def unique_partition_mapping_columns_from_shuffle(self) -> set:
"""Preserves the columns defining the partition mapping from shuffles.
This property specifies if a column or a set of columns have a unique
partition mapping that was defined by a shuffle operation. The mapping
is created by hasing the values and the separating them onto partitions.
It is important that this property is only propagated if the values
in those columns did not change in this expression. The property is
only populated if the mapping was created by the ``partitioning_index``
function.
Simply knowing that every value is in only one partition is not a
satisfying condition, because we also use this property on merge
operations, where we need these values to be in matching partitions.
This is also the reason why set_index or sort_values can't set the
property, they fullfil a weaker condition than what this property enforcey.
Normally, this set contains one tuple of either one or multiple columns.
It can contain 2, when the operation shuffles multiple columns of the
result, i.e. a merge operation and the left and right join columns.
Returns
-------
A set of column groups that have a unique partition mapping as
defined by a shuffle.
"""
return set()
@property
def _projection_columns(self):
return self.columns
@property
def name(self):
return self._meta.name
@property
def dtypes(self):
return self._meta.dtypes
def _filter_simplification(self, parent, predicate=None):
if predicate is None:
predicate = parent.predicate.substitute(self, self.frame)
return type(self)(self.frame[predicate], *self.operands[1:])
class Literal(Expr):
"""Represent a literal (known) value as an `Expr`"""
_parameters = ["value"]
def _divisions(self):
return (None, None)
@functools.cached_property
def _meta(self):
return make_meta(self.value)
def _task(self, name: Key, index: int) -> Task:
assert index == 0
return DataNode(name, self.value)
class Blockwise(Expr):
"""Super-class for block-wise operations
This is fairly generic, and includes definitions for `_meta`, `divisions`,
`_layer` that are often (but not always) correct. Mostly this helps us
avoid duplication in the future.
Note that `Fused` expressions rely on every `Blockwise`
expression defining a proper `_task` method.
"""
operation = None
_keyword_only = []
_projection_passthrough = False
_preserves_partitioning_information = False
@functools.cached_property
def _meta(self):
args = [op._meta if isinstance(op, Expr) else op for op in self._args]
return self.operation(*args, **self._kwargs)
@functools.cached_property
def _kwargs(self) -> dict:
if self._keyword_only:
return {
p: self.operand(p)
for p in self._parameters
if p in self._keyword_only and self.operand(p) is not no_default
}
return {}
@functools.cached_property
def _args(self) -> list:
if self._keyword_only:
args = [
self.operand(p) for p in self._parameters if p not in self._keyword_only
] + self.operands[len(self._parameters) :]
return args
return self.operands
def _broadcast_dep(self, dep: Expr):
# Checks if a dependency should be broadcasted to
# all partitions of this `Blockwise` operation
return dep.npartitions == 1 and dep.ndim < self.ndim
def _divisions(self):
# This is an issue. In normal Dask we re-divide everything in a step
# which combines divisions and graph.
# We either have to create a new Align layer (ok) or combine divisions
# and graph into a single operation.
dependencies = self.dependencies()
for arg in dependencies:
if not self._broadcast_dep(arg):
assert arg.divisions == dependencies[0].divisions
return dependencies[0].divisions
@functools.cached_property
def _name(self):
if self.operation:
head = funcname(self.operation)
else:
head = funcname(type(self)).lower()
return head + "-" + _tokenize_deterministic(*self.operands)
def _blockwise_arg(self, arg, i):
"""Return a Blockwise-task argument"""
if isinstance(arg, Expr):
# Make key for Expr-based argument
if self._broadcast_dep(arg):
return TaskRef((arg._name, 0))
else:
return TaskRef((arg._name, i))
else:
return arg
def _task(self, name: Key, index: int) -> Task:
"""Produce the task for a specific partition
Parameters
----------
index:
Partition index for this task.
Returns
-------
task: tuple
"""
args = [self._blockwise_arg(op, index) for op in self._args]
if self._kwargs:
return Task(name, self.operation, *args, **self._kwargs)
else:
return Task(name, self.operation, *args)
def _simplify_up(self, parent, dependents):
if self._projection_passthrough and isinstance(parent, Projection):
return plain_column_projection(self, parent, dependents)
@functools.cached_property
def unique_partition_mapping_columns_from_shuffle(self):
if self._preserves_partitioning_information:
return self.frame.unique_partition_mapping_columns_from_shuffle
return set()
class MapPartitions(Blockwise):
_parameters = [
"frame",
"func",
"meta",
"enforce_metadata",
"transform_divisions",
"clear_divisions",
"align_dataframes",
"parent_meta",
"token",
"kwargs",
]
_defaults = {
"kwargs": None,
"align_dataframes": True,
"parent_meta": None,
"token": None,
}
@functools.cached_property
def token(self):
if "token" in self._parameters:
return self.operand("token")
return None
def __str__(self):
return f"MapPartitions({funcname(self.func)})"
@functools.cached_property
def _name(self):
if self.token is not None:
head = self.token
else:
head = funcname(self.func).lower()
return head + "-" + _tokenize_deterministic(*self.operands)
def _broadcast_dep(self, dep: Expr):
# Always broadcast single-partition dependencies in MapPartitions
return dep.npartitions == 1
@functools.cached_property
def args(self):
return [self.frame] + self.operands[len(self._parameters) :]
@functools.cached_property
def _meta(self):
meta = self.operand("meta")
return _get_meta_map_partitions(
self.args,
[e for e in self.args if isinstance(e, Expr)],
self.func,
self.kwargs,
meta,
self.parent_meta,
)
def _divisions(self):
# Unknown divisions
dfs = [arg for arg in self.args if isinstance(arg, Expr)]
if self.clear_divisions:
max_partitions = max(df.npartitions for df in dfs)
return (None,) * (max_partitions + 1)
# (Possibly) known divisions
return _get_divisions_map_partitions(
self.align_dataframes,
self.transform_divisions,
dfs,
self.func,
self.args,
self.kwargs,
)
@functools.cached_property
def _has_partition_info(self):
return has_keyword(self.func, "partition_info")
def _task(self, name: Key, index: int) -> Task:
args = [self._blockwise_arg(op, index) for op in self.args]
kwargs = (self.kwargs if self.kwargs is not None else {}).copy()
if self._has_partition_info:
kwargs["partition_info"] = {
"number": index,
"division": self.divisions[index],
}
if self.enforce_metadata:
kwargs.update(
{
"_func": self.func,
"_meta": self._meta,
}
)
return Task(name, apply_and_enforce, *args, **kwargs)
else:
return Task(
name,
self.func,
*args,
**kwargs,
)
def _get_meta_ufunc(dfs, args, func):
dasks = [arg for arg in args if isinstance(arg, (Expr, Array))]
if len(dfs) >= 2 and not all(hasattr(d, "npartitions") for d in dasks):
# should not occur in current funcs
msg = "elemwise with 2 or more DataFrames and Scalar is not supported"
raise NotImplementedError(msg)
# For broadcastable series, use no rows.
parts = [
(
d._meta
if d.ndim == 0
else (
np.empty((), dtype=d.dtype)
if isinstance(d, Array)
else meta_nonempty(d._meta)
)
)
for d in dasks
]
other = [
(i, arg) for i, arg in enumerate(args) if not isinstance(arg, (Expr, Array))
]
return partial_by_order(*parts, function=func, other=other)
class UFuncElemwise(MapPartitions):
_parameters = [
"frame",
"func",
"meta",
"transform_divisions",
"kwargs",
]
enforce_metadata = False
def __str__(self):
return f"UFunc({funcname(self.func)})"
@functools.cached_property
def args(self):
return self.operands[len(self._parameters) :]
@functools.cached_property
def _dfs(self):
return [df for df in self.args if isinstance(df, Expr) and df.ndim > 0]
@functools.cached_property
def _meta(self):
if self.operand("meta") is not no_default:
meta = self.operand("meta")
else:
meta = _get_meta_ufunc(self._dfs, self.args, self.func)
return make_meta(meta)
def _divisions(self):
if (
self.transform_divisions
and isinstance(self._dfs[0], Index)
and len(self._dfs) == 1
):
try:
divisions = self.func(
*[
pd.Index(arg.divisions) if arg is self._dfs[0] else arg
for arg in self.args
],
**self.kwargs,
)
if isinstance(divisions, pd.Index):
divisions = methods.tolist(divisions)
except Exception:
pass
else:
if not valid_divisions(divisions):
divisions = [None] * (self._dfs[0].npartitions + 1)
return divisions
return self._dfs[0].divisions
class MapOverlapAlign(Expr):
_parameters = [
"frame",
"func",
"before",
"after",
"meta",
"enforce_metadata",
"transform_divisions",
"clear_divisions",
"align_dataframes",
"token",
"kwargs",
]
_defaults = {
"meta": None,
"enfore_metadata": True,
"transform_divisions": True,
"kwargs": None,
"clear_divisions": False,
"align_dataframes": False,
"token": None,
}
@functools.cached_property
def _meta(self):
meta = self.operand("meta")
args = [self.frame._meta] + [
arg._meta if isinstance(arg, Expr) else arg
for arg in self.operands[len(self._parameters) :]
]
return _get_meta_map_partitions(
args,
[self.dependencies()[0]],
self.func,
self.kwargs,
meta,
self.kwargs.pop("parent_meta", None),
)
def _divisions(self):
args = [self.frame] + self.operands[len(self._parameters) :]
return calc_divisions_for_align(*args, allow_shuffle=False)
def _lower(self):
args = [self.frame] + self.operands[len(self._parameters) :]
args = maybe_align_partitions(*args, divisions=self._divisions())
return MapOverlap(
args[0],
self.func,
self.before,
self.after,
self._meta,
self.enforce_metadata,
self.transform_divisions,
self.clear_divisions,
self.align_dataframes,
self.token,
self.kwargs,
*args[1:],
)
class MapOverlap(MapPartitions):
_parameters = [
"frame",
"func",
"before",
"after",
"meta",
"enforce_metadata",
"transform_divisions",
"clear_divisions",
"align_dataframes",
"token",
"kwargs",
]
_defaults = {
"meta": None,
"enfore_metadata": True,
"transform_divisions": True,
"kwargs": None,
"clear_divisions": False,
"align_dataframes": False,
"token": None,
}
@functools.cached_property
def _kwargs(self) -> dict:
kwargs = self.kwargs
if kwargs is None:
kwargs = {}
return kwargs
@property
def args(self):
return (
[self.frame]
+ [self.func, self.before, self.after]
+ self.operands[len(self._parameters) :]
)
@functools.cached_property
def _meta(self):
meta = self.operand("meta")
args = [self.frame._meta] + [
arg._meta if isinstance(arg, Expr) else arg
for arg in self.operands[len(self._parameters) :]
]
return _get_meta_map_partitions(
args,
[self.dependencies()[0]],
self.func,
self.kwargs,
meta,
self.kwargs.pop("parent_meta", None),
)
@functools.cached_property
def before(self):
before = self.operand("before")
if isinstance(before, str):
return pd.to_timedelta(before)
return before
@functools.cached_property
def after(self):
after = self.operand("after")
if isinstance(after, str):
return pd.to_timedelta(after)
return after
def _lower(self):
overlapped = CreateOverlappingPartitions(self.frame, self.before, self.after)
return MapPartitions(
overlapped,
_overlap_chunk,
self._meta,
self.enforce_metadata,
self.transform_divisions,
self.clear_divisions,
self.align_dataframes,
None,
self.token,
self._kwargs,
*self.args[1:],
)
class CreateOverlappingPartitions(Expr):
_parameters = ["frame", "before", "after"]
@functools.cached_property
def _meta(self):
return self.frame._meta
def _divisions(self):
# Keep divisions alive, MapPartitions will handle the actual division logic
return self.frame.divisions
def _layer(self) -> dict:
dsk, prevs, nexts = {}, [], []
name_prepend = "overlap-prepend" + self.frame._name
if self.before:
prevs.append(None)
if isinstance(self.before, numbers.Integral):
before = self.before
for i in range(self.frame.npartitions - 1):
dsk[(name_prepend, i)] = (M.tail, (self.frame._name, i), before)
prevs.append((name_prepend, i))
elif isinstance(self.before, datetime.timedelta):
# Assumes monotonic (increasing?) index
divs = pd.Series(self.frame.divisions)
deltas = divs.diff().iloc[1:-1]
# In the first case window-size is larger than at least one partition, thus it is
# necessary to calculate how many partitions must be used for each rolling task.
# Otherwise, these calculations can be skipped (faster)
if (self.before > deltas).any():
pt_z = divs[0]
for i in range(self.frame.npartitions - 1):
# Select all indexes of relevant partitions between the current partition and
# the partition with the highest division outside the rolling window (before)
pt_i = divs[i + 1]
# lower-bound the search to the first division
lb = max(pt_i - self.before, pt_z)
first, j = divs[i], i
while first > lb and j > 0:
first = first - deltas[j]
j = j - 1
dsk[(name_prepend, i)] = (
_tail_timedelta,
(self.frame._name, i + 1),
[(self.frame._name, k) for k in range(j, i + 1)],
self.before,
)
prevs.append((name_prepend, i))
else:
for i in range(self.frame.npartitions - 1):
dsk[(name_prepend, i)] = (
_tail_timedelta,
(self.frame._name, i + 1),
[(self.frame._name, i)],
self.before,
)
prevs.append((name_prepend, i))
else:
prevs.extend([None] * self.frame.npartitions)
name_append = "overlap-append" + self.frame._name
if self.after:
if isinstance(self.after, numbers.Integral):
after = self.after
for i in range(1, self.frame.npartitions):
dsk[(name_append, i)] = (M.head, (self.frame._name, i), after)
nexts.append((name_append, i))
else:
# We don't want to look at the divisions, so take twice the step and
# validate later.
after = 2 * self.after
for i in range(1, self.frame.npartitions):
dsk[(name_append, i)] = (
_head_timedelta,
(self.frame._name, i - 1),
(self.frame._name, i),
after,