/
operations.py
3429 lines (2353 loc) · 82.8 KB
/
operations.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 collections
import functools
import itertools
import operator
from contextlib import suppress
from typing import List
import toolz
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.rules as rlz
import ibis.expr.schema as sch
import ibis.expr.types as ir
from ibis import util
from ibis.expr.schema import HasSchema, Schema
from ibis.expr.signature import Annotable
from ibis.expr.signature import Argument as Arg
def _safe_repr(x, memo=None):
return x._repr(memo=memo) if isinstance(x, (ir.Expr, Node)) else repr(x)
# TODO: move to analysis
def distinct_roots(*expressions):
roots = toolz.concat(
expression._root_tables() for expression in expressions
)
return list(toolz.unique(roots))
class Node(Annotable):
__slots__ = '_expr_cached', '_hash'
def __repr__(self):
return self._repr()
def _repr(self, memo=None):
if memo is None:
from ibis.expr.format import FormatMemo
memo = FormatMemo()
opname = type(self).__name__
pprint_args = []
def _pp(x):
return _safe_repr(x, memo=memo)
for x in self.args:
if isinstance(x, (tuple, list)):
pp = repr(list(map(_pp, x)))
else:
pp = _pp(x)
pprint_args.append(pp)
return '{}({})'.format(opname, ', '.join(pprint_args))
@property
def inputs(self):
return tuple(self.args)
def blocks(self):
# The contents of this node at referentially distinct and may not be
# analyzed deeper
return False
def flat_args(self):
for arg in self.args:
if not isinstance(arg, str) and isinstance(
arg, collections.abc.Iterable
):
for x in arg:
yield x
else:
yield arg
def __hash__(self):
if not hasattr(self, '_hash'):
self._hash = hash(
(type(self),)
+ tuple(
element.op() if isinstance(element, ir.Expr) else element
for element in self.flat_args()
)
)
return self._hash
def __eq__(self, other):
return self.equals(other)
def equals(self, other, cache=None):
if cache is None:
cache = {}
key = self, other
try:
return cache[key]
except KeyError:
cache[key] = result = self is other or (
type(self) == type(other)
and all_equal(self.args, other.args, cache=cache)
)
return result
def compatible_with(self, other):
return self.equals(other)
def is_ancestor(self, other):
if isinstance(other, ir.Expr):
other = other.op()
return self.equals(other)
def to_expr(self):
if not hasattr(self, '_expr_cached'):
self._expr_cached = self._make_expr()
return self._expr_cached
def _make_expr(self):
klass = self.output_type()
return klass(self)
def output_type(self):
"""
This function must resolve the output type of the expression and return
the node wrapped in the appropriate ValueExpr type.
"""
raise NotImplementedError
class ValueOp(Node):
def root_tables(self):
exprs = [arg for arg in self.args if isinstance(arg, ir.Expr)]
return distinct_roots(*exprs)
def resolve_name(self):
raise com.ExpressionError('Expression is not named: %s' % repr(self))
def has_resolved_name(self):
return False
def all_equal(left, right, cache=None):
"""Check whether two objects `left` and `right` are equal.
Parameters
----------
left : Union[object, Expr, Node]
right : Union[object, Expr, Node]
cache : Optional[Dict[Tuple[Node, Node], bool]]
A dictionary indicating whether two Nodes are equal
"""
if cache is None:
cache = {}
if util.is_iterable(left):
# check that left and right are equal length iterables and that all
# of their elements are equal
return (
util.is_iterable(right)
and len(left) == len(right)
and all(
itertools.starmap(
functools.partial(all_equal, cache=cache), zip(left, right)
)
)
)
if hasattr(left, 'equals'):
return left.equals(right, cache=cache)
return left == right
_table_names = ('unbound_table_{:d}'.format(i) for i in itertools.count())
def genname():
return next(_table_names)
class TableNode(Node):
def get_type(self, name):
return self.schema[name]
def output_type(self):
return ir.TableExpr
def aggregate(self, this, metrics, by=None, having=None):
return Aggregation(this, metrics, by=by, having=having)
def sort_by(self, expr, sort_exprs):
return Selection(expr, [], sort_keys=sort_exprs)
def is_ancestor(self, other):
import ibis.expr.lineage as lin
if isinstance(other, ir.Expr):
other = other.op()
if self.equals(other):
return True
fn = lambda e: (lin.proceed, e.op()) # noqa: E731
expr = self.to_expr()
for child in lin.traverse(fn, expr):
if child.equals(other):
return True
return False
class TableColumn(ValueOp):
"""Selects a column from a TableExpr"""
name = Arg((str, int))
table = Arg(ir.TableExpr)
def __init__(self, name, table):
schema = table.schema()
if isinstance(name, int):
name = schema.name_at_position(name)
super().__init__(name, table)
def _validate(self):
if self.name not in self.table.schema():
raise com.IbisTypeError(
"'{}' is not a field in {}".format(
self.name, self.table.columns
)
)
def parent(self):
return self.table
def resolve_name(self):
return self.name
def has_resolved_name(self):
return True
def root_tables(self):
return self.table._root_tables()
def _make_expr(self):
dtype = self.table._get_type(self.name)
klass = dtype.column_type()
return klass(self, name=self.name)
def find_all_base_tables(expr, memo=None):
if memo is None:
memo = {}
node = expr.op()
if isinstance(expr, ir.TableExpr) and node.blocks():
if expr not in memo:
memo[node] = expr
return memo
for arg in expr.op().flat_args():
if isinstance(arg, ir.Expr):
find_all_base_tables(arg, memo)
return memo
class PhysicalTable(TableNode, HasSchema):
def blocks(self):
return True
class UnboundTable(PhysicalTable):
schema = Arg(sch.Schema)
name = Arg(str, default=genname)
class DatabaseTable(PhysicalTable):
name = Arg(str)
schema = Arg(sch.Schema)
source = Arg(rlz.client)
def change_name(self, new_name):
return type(self)(new_name, self.args[1], self.source)
class SQLQueryResult(TableNode, HasSchema):
"""A table sourced from the result set of a select query"""
query = Arg(rlz.noop)
schema = Arg(sch.Schema)
source = Arg(rlz.client)
def blocks(self):
return True
class TableArrayView(ValueOp):
"""
(Temporary?) Helper operation class for SQL translation (fully formed table
subqueries to be viewed as arrays)
"""
table = Arg(ir.TableExpr)
name = Arg(str)
def __init__(self, table):
schema = table.schema()
if len(schema) > 1:
raise com.ExpressionError('Table can only have a single column')
name = schema.names[0]
return super().__init__(table, name)
def _make_expr(self):
ctype = self.table._get_type(self.name)
klass = ctype.column_type()
return klass(self, name=self.name)
class UnaryOp(ValueOp):
arg = Arg(rlz.any)
class BinaryOp(ValueOp):
"""A binary operation"""
left = Arg(rlz.any)
right = Arg(rlz.any)
class Cast(ValueOp):
arg = Arg(rlz.any)
to = Arg(dt.dtype)
# see #396 for the issue preventing this
# def resolve_name(self):
# return self.args[0].get_name()
def output_type(self):
return rlz.shape_like(self.arg, dtype=self.to)
class TypeOf(UnaryOp):
output_type = rlz.shape_like('arg', dt.string)
class Negate(UnaryOp):
arg = Arg(rlz.one_of((rlz.numeric(), rlz.interval())))
output_type = rlz.typeof('arg')
class IsNull(UnaryOp):
"""Returns true if values are null
Returns
-------
isnull : boolean with dimension of caller
"""
output_type = rlz.shape_like('arg', dt.boolean)
class NotNull(UnaryOp):
"""Returns true if values are not null
Returns
-------
notnull : boolean with dimension of caller
"""
output_type = rlz.shape_like('arg', dt.boolean)
class ZeroIfNull(UnaryOp):
output_type = rlz.typeof('arg')
class IfNull(ValueOp):
"""Equivalent to (but perhaps implemented differently):
case().when(expr.notnull(), expr)
.else_(null_substitute_expr)
"""
arg = Arg(rlz.any)
ifnull_expr = Arg(rlz.any)
output_type = rlz.shape_like('args')
class NullIf(ValueOp):
"""Set values to NULL if they equal the null_if_expr"""
arg = Arg(rlz.any)
null_if_expr = Arg(rlz.any)
output_type = rlz.shape_like('args')
class NullIfZero(ValueOp):
"""
Set values to NULL if they equal to zero. Commonly used in cases where
divide-by-zero would produce an overflow or infinity.
Equivalent to (value == 0).ifelse(ibis.NA, value)
Returns
-------
maybe_nulled : type of caller
"""
arg = Arg(rlz.numeric)
output_type = rlz.typeof('arg')
class IsNan(ValueOp):
arg = Arg(rlz.floating)
output_type = rlz.shape_like('arg', dt.boolean)
class IsInf(ValueOp):
arg = Arg(rlz.floating)
output_type = rlz.shape_like('arg', dt.boolean)
class CoalesceLike(ValueOp):
# According to Impala documentation:
# Return type: same as the initial argument value, except that integer
# values are promoted to BIGINT and floating-point values are promoted to
# DOUBLE; use CAST() when inserting into a smaller numeric column
arg = Arg(rlz.list_of(rlz.any))
def output_type(self):
first = self.arg[0]
if isinstance(first, (ir.IntegerValue, ir.FloatingValue)):
dtype = first.type().largest
else:
dtype = first.type()
# self.arg is a list of value expressions
return rlz.shape_like(self.arg, dtype)
class Coalesce(CoalesceLike):
pass
class Greatest(CoalesceLike):
pass
class Least(CoalesceLike):
pass
class Abs(UnaryOp):
"""Absolute value"""
output_type = rlz.typeof('arg')
class Ceil(UnaryOp):
"""
Round up to the nearest integer value greater than or equal to this value
Returns
-------
ceiled : type depending on input
Decimal values: yield decimal
Other numeric values: yield integer (int32)
"""
arg = Arg(rlz.numeric)
def output_type(self):
if isinstance(self.arg.type(), dt.Decimal):
return self.arg._factory
return rlz.shape_like(self.arg, dt.int64)
class Floor(UnaryOp):
"""
Round down to the nearest integer value less than or equal to this value
Returns
-------
floored : type depending on input
Decimal values: yield decimal
Other numeric values: yield integer (int32)
"""
arg = Arg(rlz.numeric)
def output_type(self):
if isinstance(self.arg.type(), dt.Decimal):
return self.arg._factory
return rlz.shape_like(self.arg, dt.int64)
class Round(ValueOp):
arg = Arg(rlz.numeric)
digits = Arg(rlz.numeric, default=None)
def output_type(self):
if isinstance(self.arg, ir.DecimalValue):
return self.arg._factory
elif self.digits is None:
return rlz.shape_like(self.arg, dt.int64)
else:
return rlz.shape_like(self.arg, dt.double)
class Clip(ValueOp):
arg = Arg(rlz.strict_numeric)
lower = Arg(rlz.strict_numeric, default=None)
upper = Arg(rlz.strict_numeric, default=None)
output_type = rlz.typeof('arg')
class BaseConvert(ValueOp):
arg = Arg(rlz.one_of([rlz.integer, rlz.string]))
from_base = Arg(rlz.integer)
to_base = Arg(rlz.integer)
def output_type(self):
return rlz.shape_like(tuple(self.flat_args()), dt.string)
class MathUnaryOp(UnaryOp):
arg = Arg(rlz.numeric)
def output_type(self):
arg = self.arg
if isinstance(self.arg, ir.DecimalValue):
dtype = arg.type()
else:
dtype = dt.double
return rlz.shape_like(arg, dtype)
class ExpandingTypeMathUnaryOp(MathUnaryOp):
def output_type(self):
if not isinstance(self.arg, ir.DecimalValue):
return super().output_type()
arg = self.arg
return rlz.shape_like(arg, arg.type().largest)
class Exp(ExpandingTypeMathUnaryOp):
pass
class Sign(UnaryOp):
arg = Arg(rlz.numeric)
output_type = rlz.typeof('arg')
class Sqrt(MathUnaryOp):
pass
class Logarithm(MathUnaryOp):
arg = Arg(rlz.strict_numeric)
class Log(Logarithm):
arg = Arg(rlz.strict_numeric)
base = Arg(rlz.strict_numeric, default=None)
class Ln(Logarithm):
"""Natural logarithm"""
class Log2(Logarithm):
"""Logarithm base 2"""
class Log10(Logarithm):
"""Logarithm base 10"""
class Degrees(ExpandingTypeMathUnaryOp):
"""Converts radians to degrees"""
arg = Arg(rlz.numeric)
class Radians(MathUnaryOp):
"""Converts degrees to radians"""
arg = Arg(rlz.numeric)
# TRIGONOMETRIC OPERATIONS
class TrigonometricUnary(MathUnaryOp):
"""Trigonometric base unary"""
arg = Arg(rlz.numeric)
class TrigonometricBinary(BinaryOp):
"""Trigonometric base binary"""
left = Arg(rlz.numeric)
right = Arg(rlz.numeric)
output_type = rlz.shape_like('args', dt.float64)
class Acos(TrigonometricUnary):
"""Returns the arc cosine of x"""
class Asin(TrigonometricUnary):
"""Returns the arc sine of x"""
class Atan(TrigonometricUnary):
"""Returns the arc tangent of x"""
class Atan2(TrigonometricBinary):
"""Returns the arc tangent of x and y"""
class Cos(TrigonometricUnary):
"""Returns the cosine of x"""
class Cot(TrigonometricUnary):
"""Returns the cotangent of x"""
class Sin(TrigonometricUnary):
"""Returns the sine of x"""
class Tan(TrigonometricUnary):
"""Returns the tangent of x"""
class StringUnaryOp(UnaryOp):
arg = Arg(rlz.string)
output_type = rlz.shape_like('arg', dt.string)
class Uppercase(StringUnaryOp):
"""Convert string to all uppercase"""
class Lowercase(StringUnaryOp):
"""Convert string to all lowercase"""
class Reverse(StringUnaryOp):
"""Reverse string"""
class Strip(StringUnaryOp):
"""Remove whitespace from left and right sides of string"""
class LStrip(StringUnaryOp):
"""Remove whitespace from left side of string"""
class RStrip(StringUnaryOp):
"""Remove whitespace from right side of string"""
class Capitalize(StringUnaryOp):
"""Return a capitalized version of input string"""
class Substring(ValueOp):
arg = Arg(rlz.string)
start = Arg(rlz.integer)
length = Arg(rlz.integer, default=None)
output_type = rlz.shape_like('arg', dt.string)
class StrRight(ValueOp):
arg = Arg(rlz.string)
nchars = Arg(rlz.integer)
output_type = rlz.shape_like('arg', dt.string)
class Repeat(ValueOp):
arg = Arg(rlz.string)
times = Arg(rlz.integer)
output_type = rlz.shape_like('arg', dt.string)
class StringFind(ValueOp):
arg = Arg(rlz.string)
substr = Arg(rlz.string)
start = Arg(rlz.integer, default=None)
end = Arg(rlz.integer, default=None)
output_type = rlz.shape_like('arg', dt.int64)
class Translate(ValueOp):
arg = Arg(rlz.string)
from_str = Arg(rlz.string)
to_str = Arg(rlz.string)
output_type = rlz.shape_like('arg', dt.string)
class LPad(ValueOp):
arg = Arg(rlz.string)
length = Arg(rlz.integer)
pad = Arg(rlz.string, default=None)
output_type = rlz.shape_like('arg', dt.string)
class RPad(ValueOp):
arg = Arg(rlz.string)
length = Arg(rlz.integer)
pad = Arg(rlz.string, default=None)
output_type = rlz.shape_like('arg', dt.string)
class FindInSet(ValueOp):
needle = Arg(rlz.string)
values = Arg(rlz.list_of(rlz.string, min_length=1))
output_type = rlz.shape_like('needle', dt.int64)
class StringJoin(ValueOp):
sep = Arg(rlz.string)
arg = Arg(rlz.list_of(rlz.string, min_length=1))
def output_type(self):
return rlz.shape_like(tuple(self.flat_args()), dt.string)
class BooleanValueOp:
pass
class FuzzySearch(ValueOp, BooleanValueOp):
arg = Arg(rlz.string)
pattern = Arg(rlz.string)
output_type = rlz.shape_like('arg', dt.boolean)
class StringSQLLike(FuzzySearch):
arg = Arg(rlz.string)
pattern = Arg(rlz.string)
escape = Arg(str, default=None)
class StringSQLILike(StringSQLLike):
"""SQL ilike operation"""
class RegexSearch(FuzzySearch):
pass
class RegexExtract(ValueOp):
arg = Arg(rlz.string)
pattern = Arg(rlz.string)
index = Arg(rlz.integer)
output_type = rlz.shape_like('arg', dt.string)
class RegexReplace(ValueOp):
arg = Arg(rlz.string)
pattern = Arg(rlz.string)
replacement = Arg(rlz.string)
output_type = rlz.shape_like('arg', dt.string)
class StringReplace(ValueOp):
arg = Arg(rlz.string)
pattern = Arg(rlz.string)
replacement = Arg(rlz.string)
output_type = rlz.shape_like('arg', dt.string)
class StringSplit(ValueOp):
arg = Arg(rlz.string)
delimiter = Arg(rlz.string)
output_type = rlz.shape_like('arg', dt.Array(dt.string))
class StringConcat(ValueOp):
arg = Arg(rlz.list_of(rlz.string))
output_type = rlz.shape_like('arg', dt.string)
class ParseURL(ValueOp):
arg = Arg(rlz.string)
extract = Arg(
rlz.isin(
{
'PROTOCOL',
'HOST',
'PATH',
'REF',
'AUTHORITY',
'FILE',
'USERINFO',
'QUERY',
}
)
)
key = Arg(rlz.string, default=None)
output_type = rlz.shape_like('arg', dt.string)
class StringLength(UnaryOp):
"""
Compute length of strings
Returns
-------
length : int32
"""
output_type = rlz.shape_like('arg', dt.int32)
class StringAscii(UnaryOp):
output_type = rlz.shape_like('arg', dt.int32)
# ----------------------------------------------------------------------
class Reduction(ValueOp):
_reduction = True
class Count(Reduction):
arg = Arg((ir.ColumnExpr, ir.TableExpr))
where = Arg(rlz.boolean, default=None)
def output_type(self):
return functools.partial(ir.IntegerScalar, dtype=dt.int64)
class Arbitrary(Reduction):
arg = Arg(rlz.column(rlz.any))
how = Arg(rlz.isin({'first', 'last', 'heavy'}), default=None)
where = Arg(rlz.boolean, default=None)
output_type = rlz.scalar_like('arg')
class Sum(Reduction):
arg = Arg(rlz.column(rlz.numeric))
where = Arg(rlz.boolean, default=None)
def output_type(self):
if isinstance(self.arg, ir.BooleanValue):
dtype = dt.int64
else:
dtype = self.arg.type().largest
return dtype.scalar_type()
class Mean(Reduction):
arg = Arg(rlz.column(rlz.numeric))
where = Arg(rlz.boolean, default=None)
def output_type(self):
if isinstance(self.arg, ir.DecimalValue):
dtype = self.arg.type()
else:
dtype = dt.float64
return dtype.scalar_type()
class Quantile(Reduction):
arg = Arg(rlz.any)
quantile = Arg(rlz.strict_numeric)
interpolation = Arg(
rlz.isin({'linear', 'lower', 'higher', 'midpoint', 'nearest'}),
default='linear',
)
def output_type(self):
return dt.float64.scalar_type()
class MultiQuantile(Quantile):
arg = Arg(rlz.any)
quantile = Arg(rlz.value(dt.Array(dt.float64)))
interpolation = Arg(
rlz.isin({'linear', 'lower', 'higher', 'midpoint', 'nearest'}),
default='linear',
)
def output_type(self):
return dt.Array(dt.float64).scalar_type()
class VarianceBase(Reduction):
arg = Arg(rlz.column(rlz.numeric))
how = Arg(rlz.isin({'sample', 'pop'}), default=None)
where = Arg(rlz.boolean, default=None)
def output_type(self):
if isinstance(self.arg, ir.DecimalValue):
dtype = self.arg.type().largest
else:
dtype = dt.float64
return dtype.scalar_type()
class StandardDev(VarianceBase):
pass
class Variance(VarianceBase):
pass
class Correlation(Reduction):
"""Coefficient of correlation of a set of number pairs."""
left = Arg(rlz.column(rlz.numeric))
right = Arg(rlz.column(rlz.numeric))
how = Arg(rlz.isin({'sample', 'pop'}), default=None)
where = Arg(rlz.boolean, default=None)
def output_type(self):
return dt.float64.scalar_type()
class Covariance(Reduction):
"""Covariance of a set of number pairs."""
left = Arg(rlz.column(rlz.numeric))
right = Arg(rlz.column(rlz.numeric))
how = Arg(rlz.isin({'sample', 'pop'}), default=None)
where = Arg(rlz.boolean, default=None)
def output_type(self):
return dt.float64.scalar_type()
class Max(Reduction):
arg = Arg(rlz.column(rlz.any))
where = Arg(rlz.boolean, default=None)
output_type = rlz.scalar_like('arg')
class Min(Reduction):
arg = Arg(rlz.column(rlz.any))
where = Arg(rlz.boolean, default=None)
output_type = rlz.scalar_like('arg')
class HLLCardinality(Reduction):
"""Approximate number of unique values using HyperLogLog algorithm.
Impala offers the NDV built-in function for this.
"""
arg = Arg(rlz.column(rlz.any))
where = Arg(rlz.boolean, default=None)
def output_type(self):
# Impala 2.0 and higher returns a DOUBLE
# return ir.DoubleScalar
return functools.partial(ir.IntegerScalar, dtype=dt.int64)
class GroupConcat(Reduction):
arg = Arg(rlz.column(rlz.any))
sep = Arg(rlz.string, default=',')
where = Arg(rlz.boolean, default=None)
def output_type(self):
return dt.string.scalar_type()
class CMSMedian(Reduction):
"""
Compute the approximate median of a set of comparable values using the
Count-Min-Sketch algorithm. Exposed in Impala using APPX_MEDIAN.
"""
arg = Arg(rlz.column(rlz.any))
where = Arg(rlz.boolean, default=None)
output_type = rlz.scalar_like('arg')