-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathscalar_op_compiler.py
1618 lines (1273 loc) · 54.3 KB
/
scalar_op_compiler.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
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import functools
import typing
import bigframes_vendored.constants as constants
import bigframes_vendored.ibis.expr.operations as vendored_ibis_ops
import ibis
import ibis.common.exceptions
import ibis.expr.datatypes as ibis_dtypes
import ibis.expr.operations.generic
import ibis.expr.types as ibis_types
import numpy as np
import pandas as pd
import bigframes.core.compile.ibis_types
import bigframes.core.expression as ex
import bigframes.dtypes
import bigframes.operations as ops
_ZERO = typing.cast(ibis_types.NumericValue, ibis_types.literal(0))
_NAN = typing.cast(ibis_types.NumericValue, ibis_types.literal(np.nan))
_INF = typing.cast(ibis_types.NumericValue, ibis_types.literal(np.inf))
_NEG_INF = typing.cast(ibis_types.NumericValue, ibis_types.literal(-np.inf))
# Approx Highest number you can pass in to EXP function and get a valid FLOAT64 result
# FLOAT64 has 11 exponent bits, so max values is about 2**(2**10)
# ln(2**(2**10)) == (2**10)*ln(2) ~= 709.78, so EXP(x) for x>709.78 will overflow.
_FLOAT64_EXP_BOUND = typing.cast(ibis_types.NumericValue, ibis_types.literal(709.78))
# Datetime constants
UNIT_TO_US_CONVERSION_FACTORS = {
"W": 7 * 24 * 60 * 60 * 1000 * 1000,
"d": 24 * 60 * 60 * 1000 * 1000,
"D": 24 * 60 * 60 * 1000 * 1000,
"h": 60 * 60 * 1000 * 1000,
"m": 60 * 1000 * 1000,
"s": 1000 * 1000,
"ms": 1000,
"us": 1,
"ns": 1e-3,
}
class ScalarOpCompiler:
# Mapping of operation name to implemenations
_registry: dict[
str,
typing.Callable[
[typing.Sequence[ibis_types.Value], ops.RowOp], ibis_types.Value
],
] = {}
@functools.singledispatchmethod
def compile_expression(
self,
expression: ex.Expression,
bindings: typing.Dict[str, ibis_types.Value],
) -> ibis_types.Value:
raise NotImplementedError(f"Unrecognized expression: {expression}")
@compile_expression.register
def _(
self,
expression: ex.ScalarConstantExpression,
bindings: typing.Dict[str, ibis_types.Value],
) -> ibis_types.Value:
return bigframes.core.compile.ibis_types.literal_to_ibis_scalar(
expression.value, expression.dtype
)
@compile_expression.register
def _(
self,
expression: ex.UnboundVariableExpression,
bindings: typing.Dict[str, ibis_types.Value],
) -> ibis_types.Value:
if expression.id not in bindings:
raise ValueError(f"Could not resolve unbound variable {expression.id}")
else:
return bindings[expression.id]
@compile_expression.register
def _(
self,
expression: ex.OpExpression,
bindings: typing.Dict[str, ibis_types.Value],
) -> ibis_types.Value:
inputs = [
self.compile_expression(sub_expr, bindings)
for sub_expr in expression.inputs
]
return self.compile_row_op(expression.op, inputs)
def compile_row_op(
self, op: ops.RowOp, inputs: typing.Sequence[ibis_types.Value]
) -> ibis_types.Value:
impl = self._registry[op.name]
return impl(inputs, op)
def register_unary_op(
self,
op_ref: typing.Union[ops.UnaryOp, type[ops.UnaryOp]],
pass_op: bool = False,
):
"""
Decorator to register a unary op implementation.
Args:
op_ref (UnaryOp or UnaryOp type):
Class or instance of operator that is implemented by the decorated function.
pass_op (bool):
Set to true if implementation takes the operator object as the last argument.
This is needed for parameterized ops where parameters are part of op object.
"""
key = typing.cast(str, op_ref.name)
def decorator(impl: typing.Callable[..., ibis_types.Value]):
def normalized_impl(args: typing.Sequence[ibis_types.Value], op: ops.RowOp):
if pass_op:
return impl(args[0], op)
else:
return impl(args[0])
self._register(key, normalized_impl)
return impl
return decorator
def register_binary_op(
self,
op_ref: typing.Union[ops.BinaryOp, type[ops.BinaryOp]],
pass_op: bool = False,
):
"""
Decorator to register a binary op implementation.
Args:
op_ref (BinaryOp or BinaryOp type):
Class or instance of operator that is implemented by the decorated function.
pass_op (bool):
Set to true if implementation takes the operator object as the last argument.
This is needed for parameterized ops where parameters are part of op object.
"""
key = typing.cast(str, op_ref.name)
def decorator(impl: typing.Callable[..., ibis_types.Value]):
def normalized_impl(args: typing.Sequence[ibis_types.Value], op: ops.RowOp):
if pass_op:
return impl(args[0], args[1], op)
else:
return impl(args[0], args[1])
self._register(key, normalized_impl)
return impl
return decorator
def register_ternary_op(
self, op_ref: typing.Union[ops.TernaryOp, type[ops.TernaryOp]]
):
"""
Decorator to register a ternary op implementation.
Args:
op_ref (TernaryOp or TernaryOp type):
Class or instance of operator that is implemented by the decorated function.
"""
key = typing.cast(str, op_ref.name)
def decorator(impl: typing.Callable[..., ibis_types.Value]):
def normalized_impl(args: typing.Sequence[ibis_types.Value], op: ops.RowOp):
return impl(args[0], args[1], args[2])
self._register(key, normalized_impl)
return impl
return decorator
def register_nary_op(
self, op_ref: typing.Union[ops.NaryOp, type[ops.NaryOp]], pass_op: bool = False
):
"""
Decorator to register a nary op implementation.
Args:
op_ref (NaryOp or NaryOp type):
Class or instance of operator that is implemented by the decorated function.
pass_op (bool):
Set to true if implementation takes the operator object as the last argument.
This is needed for parameterized ops where parameters are part of op object.
"""
key = typing.cast(str, op_ref.name)
def decorator(impl: typing.Callable[..., ibis_types.Value]):
def normalized_impl(args: typing.Sequence[ibis_types.Value], op: ops.RowOp):
if pass_op:
return impl(*args, op=op)
else:
return impl(*args)
self._register(key, normalized_impl)
return impl
return decorator
def _register(
self,
op_name: str,
impl: typing.Callable[
[typing.Sequence[ibis_types.Value], ops.RowOp], ibis_types.Value
],
):
if op_name in self._registry:
raise ValueError(f"Operation name {op_name} already registered")
self._registry[op_name] = impl
# Singleton compiler
scalar_op_compiler = ScalarOpCompiler()
### Unary Ops
@scalar_op_compiler.register_unary_op(ops.isnull_op)
def isnull_op_impl(x: ibis_types.Value):
return x.isnull()
@scalar_op_compiler.register_unary_op(ops.notnull_op)
def notnull_op_impl(x: ibis_types.Value):
return x.notnull()
@scalar_op_compiler.register_unary_op(ops.hash_op)
def hash_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.IntegerValue, x).hash()
# Trig Functions
@scalar_op_compiler.register_unary_op(ops.sin_op)
def sin_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).sin()
@scalar_op_compiler.register_unary_op(ops.cos_op)
def cos_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).cos()
@scalar_op_compiler.register_unary_op(ops.tan_op)
def tan_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).tan()
# Inverse trig functions
@scalar_op_compiler.register_unary_op(ops.arcsin_op)
def arcsin_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value.abs() <= _ibis_num(1)
return (~domain).ifelse(_NAN, numeric_value.asin())
@scalar_op_compiler.register_unary_op(ops.arccos_op)
def arccos_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value.abs() <= _ibis_num(1)
return (~domain).ifelse(_NAN, numeric_value.acos())
@scalar_op_compiler.register_unary_op(ops.arctan_op)
def arctan_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).atan()
@scalar_op_compiler.register_binary_op(ops.arctan2_op)
def arctan2_op_impl(x: ibis_types.Value, y: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).atan2(
typing.cast(ibis_types.NumericValue, y)
)
# Hyperbolic trig functions
# BQ has these functions, but Ibis doesn't
@scalar_op_compiler.register_unary_op(ops.sinh_op)
def sinh_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
sinh_result = (numeric_value.exp() - (numeric_value.negate()).exp()) / _ibis_num(2)
domain = numeric_value.abs() < _FLOAT64_EXP_BOUND
return (~domain).ifelse(_INF * numeric_value.sign(), sinh_result)
@scalar_op_compiler.register_unary_op(ops.cosh_op)
def cosh_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
cosh_result = (numeric_value.exp() + (numeric_value.negate()).exp()) / _ibis_num(2)
domain = numeric_value.abs() < _FLOAT64_EXP_BOUND
return (~domain).ifelse(_INF, cosh_result)
@scalar_op_compiler.register_unary_op(ops.tanh_op)
def tanh_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
tanh_result = (numeric_value.exp() - (numeric_value.negate()).exp()) / (
numeric_value.exp() + (numeric_value.negate()).exp()
)
# Beyond +-20, is effectively just the sign function
domain = numeric_value.abs() < _ibis_num(20)
return (~domain).ifelse(numeric_value.sign(), tanh_result)
@scalar_op_compiler.register_unary_op(ops.arcsinh_op)
def arcsinh_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
sqrt_part = ((numeric_value * numeric_value) + _ibis_num(1)).sqrt()
return (numeric_value.abs() + sqrt_part).ln() * numeric_value.sign()
@scalar_op_compiler.register_unary_op(ops.arccosh_op)
def arccosh_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
sqrt_part = ((numeric_value * numeric_value) - _ibis_num(1)).sqrt()
acosh_result = (numeric_value + sqrt_part).ln()
domain = numeric_value >= _ibis_num(1)
return (~domain).ifelse(_NAN, acosh_result)
@scalar_op_compiler.register_unary_op(ops.arctanh_op)
def arctanh_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value.abs() < _ibis_num(1)
numerator = numeric_value + _ibis_num(1)
denominator = _ibis_num(1) - numeric_value
ln_input = typing.cast(ibis_types.NumericValue, numerator.div(denominator))
atanh_result = ln_input.ln().div(2)
out_of_domain = (numeric_value.abs() == _ibis_num(1)).ifelse(
_INF * numeric_value, _NAN
)
return (~domain).ifelse(out_of_domain, atanh_result)
# Numeric Ops
@scalar_op_compiler.register_unary_op(ops.floor_op)
def floor_op_impl(x: ibis_types.Value):
x_numeric = typing.cast(ibis_types.NumericValue, x)
if x_numeric.type().is_integer():
return x_numeric.cast(ibis_dtypes.Float64())
if x_numeric.type().is_floating():
# Default ibis impl tries to cast to integer, which doesn't match pandas and can overflow
return float_floor(x_numeric)
else: # numeric
return x_numeric.floor()
@scalar_op_compiler.register_unary_op(ops.ceil_op)
def ceil_op_impl(x: ibis_types.Value):
x_numeric = typing.cast(ibis_types.NumericValue, x)
if x_numeric.type().is_integer():
return x_numeric.cast(ibis_dtypes.Float64())
if x_numeric.type().is_floating():
# Default ibis impl tries to cast to integer, which doesn't match pandas and can overflow
return float_ceil(x_numeric)
else: # numeric
return x_numeric.ceil()
@scalar_op_compiler.register_unary_op(ops.abs_op)
def abs_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).abs()
@scalar_op_compiler.register_unary_op(ops.pos_op)
def pos_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x)
@scalar_op_compiler.register_unary_op(ops.neg_op)
def neg_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.NumericValue, x).negate()
@scalar_op_compiler.register_unary_op(ops.sqrt_op)
def sqrt_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value >= _ZERO
return (~domain).ifelse(_NAN, numeric_value.sqrt())
@scalar_op_compiler.register_unary_op(ops.log10_op)
def log10_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value > _ZERO
out_of_domain = (numeric_value == _ZERO).ifelse(_NEG_INF, _NAN)
return (~domain).ifelse(out_of_domain, numeric_value.log10())
@scalar_op_compiler.register_unary_op(ops.ln_op)
def ln_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value > _ZERO
out_of_domain = (numeric_value == _ZERO).ifelse(_NEG_INF, _NAN)
return (~domain).ifelse(out_of_domain, numeric_value.ln())
@scalar_op_compiler.register_unary_op(ops.log1p_op)
def log1p_op_impl(x: ibis_types.Value):
return ln_op_impl(_ibis_num(1) + x)
@scalar_op_compiler.register_unary_op(ops.exp_op)
def exp_op_impl(x: ibis_types.Value):
numeric_value = typing.cast(ibis_types.NumericValue, x)
domain = numeric_value < _FLOAT64_EXP_BOUND
return (~domain).ifelse(_INF, numeric_value.exp())
@scalar_op_compiler.register_unary_op(ops.expm1_op)
def expm1_op_impl(x: ibis_types.Value):
return exp_op_impl(x) - _ibis_num(1)
@scalar_op_compiler.register_unary_op(ops.invert_op)
def invert_op_impl(x: ibis_types.Value):
return x.__invert__()
## String Operation
@scalar_op_compiler.register_unary_op(ops.len_op)
def len_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).length().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.reverse_op)
def reverse_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).reverse()
@scalar_op_compiler.register_unary_op(ops.lower_op)
def lower_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).lower()
@scalar_op_compiler.register_unary_op(ops.upper_op)
def upper_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).upper()
@scalar_op_compiler.register_unary_op(ops.strip_op)
def strip_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).strip()
@scalar_op_compiler.register_unary_op(ops.isnumeric_op)
def isnumeric_op_impl(x: ibis_types.Value):
# catches all members of the Unicode number class, which matches pandas isnumeric
# see https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#regexp_contains
# TODO: Validate correctness, my miss eg ⅕ character
return typing.cast(ibis_types.StringValue, x).re_search(r"^(\pN+)$")
@scalar_op_compiler.register_unary_op(ops.isalpha_op)
def isalpha_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).re_search(
r"^(\p{Lm}|\p{Lt}|\p{Lu}|\p{Ll}|\p{Lo})+$"
)
@scalar_op_compiler.register_unary_op(ops.isdigit_op)
def isdigit_op_impl(x: ibis_types.Value):
# Based on docs, should include superscript/subscript-ed numbers
# Tests however pass only when set to Nd unicode class
return typing.cast(ibis_types.StringValue, x).re_search(r"^(\p{Nd})+$")
@scalar_op_compiler.register_unary_op(ops.isdecimal_op)
def isdecimal_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).re_search(r"^(\p{Nd})+$")
@scalar_op_compiler.register_unary_op(ops.isalnum_op)
def isalnum_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).re_search(
r"^(\p{N}|\p{Lm}|\p{Lt}|\p{Lu}|\p{Ll}|\p{Lo})+$"
)
@scalar_op_compiler.register_unary_op(ops.isspace_op)
def isspace_op_impl(x: ibis_types.Value):
# All characters are whitespace characters, False for empty string
return typing.cast(ibis_types.StringValue, x).re_search(r"^\s+$")
@scalar_op_compiler.register_unary_op(ops.islower_op)
def islower_op_impl(x: ibis_types.Value):
# No upper case characters, min one cased character
# See: https://docs.python.org/3/library/stdtypes.html#str
return typing.cast(ibis_types.StringValue, x).re_search(r"\p{Ll}") & ~typing.cast(
ibis_types.StringValue, x
).re_search(r"\p{Lu}|\p{Lt}")
@scalar_op_compiler.register_unary_op(ops.isupper_op)
def isupper_op_impl(x: ibis_types.Value):
# No lower case characters, min one cased character
# See: https://docs.python.org/3/library/stdtypes.html#str
return typing.cast(ibis_types.StringValue, x).re_search(r"\p{Lu}") & ~typing.cast(
ibis_types.StringValue, x
).re_search(r"\p{Ll}|\p{Lt}")
@scalar_op_compiler.register_unary_op(ops.rstrip_op)
def rstrip_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).rstrip()
@scalar_op_compiler.register_unary_op(ops.lstrip_op)
def lstrip_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).lstrip()
@scalar_op_compiler.register_unary_op(ops.capitalize_op)
def capitalize_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.StringValue, x).capitalize()
@scalar_op_compiler.register_unary_op(ops.StrContainsOp, pass_op=True)
def strcontains_op(x: ibis_types.Value, op: ops.StrContainsOp):
return typing.cast(ibis_types.StringValue, x).contains(op.pat)
@scalar_op_compiler.register_unary_op(ops.StrContainsRegexOp, pass_op=True)
def contains_regex_op_impl(x: ibis_types.Value, op: ops.StrContainsRegexOp):
return typing.cast(ibis_types.StringValue, x).re_search(op.pat)
@scalar_op_compiler.register_unary_op(ops.StrGetOp, pass_op=True)
def strget_op_impl(x: ibis_types.Value, op: ops.StrGetOp):
substr = typing.cast(
ibis_types.StringValue, typing.cast(ibis_types.StringValue, x)[op.i]
)
return substr.nullif(ibis_types.literal(""))
@scalar_op_compiler.register_unary_op(ops.StrPadOp, pass_op=True)
def strpad_op_impl(x: ibis_types.Value, op: ops.StrPadOp):
str_val = typing.cast(ibis_types.StringValue, x)
# SQL pad operations will truncate, we do not want to truncate though.
pad_length = ibis.greatest(str_val.length(), op.length)
if op.side == "left":
return str_val.lpad(pad_length, op.fillchar)
elif op.side == "right":
return str_val.rpad(pad_length, op.fillchar)
else: # side == both
# Pad more on right side if can't pad both sides equally
lpad_amount = ((pad_length - str_val.length()) // 2) + str_val.length()
return str_val.lpad(lpad_amount, op.fillchar).rpad(pad_length, op.fillchar)
@scalar_op_compiler.register_unary_op(ops.ReplaceStrOp, pass_op=True)
def replacestring_op_impl(x: ibis_types.Value, op: ops.ReplaceStrOp):
pat_str_value = typing.cast(ibis_types.StringValue, ibis_types.literal(op.pat))
repl_str_value = typing.cast(ibis_types.StringValue, ibis_types.literal(op.repl))
return typing.cast(ibis_types.StringValue, x).replace(pat_str_value, repl_str_value)
@scalar_op_compiler.register_unary_op(ops.RegexReplaceStrOp, pass_op=True)
def replaceregex_op_impl(x: ibis_types.Value, op: ops.RegexReplaceStrOp):
return typing.cast(ibis_types.StringValue, x).re_replace(op.pat, op.repl)
@scalar_op_compiler.register_unary_op(ops.StartsWithOp, pass_op=True)
def startswith_op_impl(x: ibis_types.Value, op: ops.StartsWithOp):
any_match = None
for pat in op.pat:
pat_match = typing.cast(ibis_types.StringValue, x).startswith(pat)
if any_match is not None:
any_match = any_match | pat_match
else:
any_match = pat_match
return any_match if any_match is not None else ibis_types.literal(False)
@scalar_op_compiler.register_unary_op(ops.EndsWithOp, pass_op=True)
def endswith_op_impl(x: ibis_types.Value, op: ops.EndsWithOp):
any_match = None
for pat in op.pat:
pat_match = typing.cast(ibis_types.StringValue, x).endswith(pat)
if any_match is not None:
any_match = any_match | pat_match
else:
any_match = pat_match
return any_match if any_match is not None else ibis_types.literal(False)
@scalar_op_compiler.register_unary_op(ops.StringSplitOp, pass_op=True)
def stringsplit_op_impl(x: ibis_types.Value, op: ops.StringSplitOp):
return typing.cast(ibis_types.StringValue, x).split(op.pat)
@scalar_op_compiler.register_unary_op(ops.ZfillOp, pass_op=True)
def zfill_op_impl(x: ibis_types.Value, op: ops.ZfillOp):
str_value = typing.cast(ibis_types.StringValue, x)
return (
ibis.case()
.when(
str_value[0] == "-",
"-"
+ strpad_op_impl(
str_value.substr(1),
ops.StrPadOp(length=op.width - 1, fillchar="0", side="left"),
),
)
.else_(
strpad_op_impl(
str_value, ops.StrPadOp(length=op.width, fillchar="0", side="left")
)
)
.end()
)
@scalar_op_compiler.register_unary_op(ops.StrFindOp, pass_op=True)
def find_op_impl(x: ibis_types.Value, op: ops.StrFindOp):
return typing.cast(ibis_types.StringValue, x).find(op.substr, op.start, op.end)
@scalar_op_compiler.register_unary_op(ops.StrExtractOp, pass_op=True)
def extract_op_impl(x: ibis_types.Value, op: ops.StrExtractOp):
return typing.cast(ibis_types.StringValue, x).re_extract(op.pat, op.n)
@scalar_op_compiler.register_unary_op(ops.StrSliceOp, pass_op=True)
def slice_op_impl(x: ibis_types.Value, op: ops.StrSliceOp):
return typing.cast(ibis_types.StringValue, x)[op.start : op.end]
@scalar_op_compiler.register_unary_op(ops.StrRepeatOp, pass_op=True)
def repeat_op_impl(x: ibis_types.Value, op: ops.StrRepeatOp):
return typing.cast(ibis_types.StringValue, x).repeat(op.repeats)
## Datetime Ops
@scalar_op_compiler.register_unary_op(ops.day_op)
def day_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).day().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.date_op)
def date_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).date()
@scalar_op_compiler.register_unary_op(ops.dayofweek_op)
def dayofweek_op_impl(x: ibis_types.Value):
return (
typing.cast(ibis_types.TimestampValue, x)
.day_of_week.index()
.cast(ibis_dtypes.int64)
)
@scalar_op_compiler.register_unary_op(ops.hour_op)
def hour_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).hour().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.minute_op)
def minute_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).minute().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.month_op)
def month_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).month().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.quarter_op)
def quarter_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).quarter().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.second_op)
def second_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).second().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.StrftimeOp, pass_op=True)
def strftime_op_impl(x: ibis_types.Value, op: ops.StrftimeOp):
return (
typing.cast(ibis_types.TimestampValue, x)
.strftime(op.date_format)
.cast(ibis_dtypes.str)
)
@scalar_op_compiler.register_unary_op(ops.FloorDtOp, pass_op=True)
def floor_dt_op_impl(x: ibis_types.Value, op: ops.FloorDtOp):
supported_freqs = ["Y", "Q", "M", "W", "D", "h", "min", "s", "ms", "us", "ns"]
pandas_to_ibis_freqs = {"min": "m"}
if op.freq not in supported_freqs:
raise NotImplementedError(
f"Unsupported freq paramater: {op.freq}"
+ " Supported freq parameters are: "
+ ",".join(supported_freqs)
)
if op.freq in pandas_to_ibis_freqs:
ibis_freq = pandas_to_ibis_freqs[op.freq]
else:
ibis_freq = op.freq
result_type = x.type()
result = typing.cast(ibis_types.TimestampValue, x)
result = result.truncate(ibis_freq)
return result.cast(result_type)
@scalar_op_compiler.register_unary_op(ops.time_op)
def time_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).time()
@scalar_op_compiler.register_unary_op(ops.year_op)
def year_op_impl(x: ibis_types.Value):
return typing.cast(ibis_types.TimestampValue, x).year().cast(ibis_dtypes.int64)
@scalar_op_compiler.register_unary_op(ops.normalize_op)
def normalize_op_impl(x: ibis_types.Value):
result_type = x.type()
result = x.truncate("D")
return result.cast(result_type)
# Parameterized ops
@scalar_op_compiler.register_unary_op(ops.StructFieldOp, pass_op=True)
def struct_field_op_impl(x: ibis_types.Value, op: ops.StructFieldOp):
struct_value = typing.cast(ibis_types.StructValue, x)
if isinstance(op.name_or_index, str):
name = op.name_or_index
else:
name = struct_value.names[op.name_or_index]
result = struct_value[name]
return result.cast(result.type()(nullable=True)).name(name)
def numeric_to_datetime(x: ibis_types.Value, unit: str) -> ibis_types.TimestampValue:
if not isinstance(x, ibis_types.IntegerValue) and not isinstance(
x, ibis_types.FloatingValue
):
raise TypeError("Non-numerical types are not supposed to reach this function.")
if unit not in UNIT_TO_US_CONVERSION_FACTORS:
raise ValueError(f"Cannot convert input with unit '{unit}'.")
x_converted = x * UNIT_TO_US_CONVERSION_FACTORS[unit]
x_converted = x_converted.cast(ibis_dtypes.int64)
# Note: Due to an issue where casting directly to a timestamp
# without a timezone does not work, we first cast to UTC. This
# approach appears to bypass a potential bug in Ibis's cast function,
# allowing for subsequent casting to a timestamp type without timezone
# information. Further investigation is needed to confirm this behavior.
return x_converted.to_timestamp(unit="us").cast(
ibis_dtypes.Timestamp(timezone="UTC")
)
@scalar_op_compiler.register_unary_op(ops.AsTypeOp, pass_op=True)
def astype_op_impl(x: ibis_types.Value, op: ops.AsTypeOp):
to_type = bigframes.core.compile.ibis_types.bigframes_dtype_to_ibis_dtype(
op.to_type
)
if isinstance(x, ibis_types.NullScalar):
return ibis_types.null().cast(to_type)
# When casting DATETIME column into INT column, we need to convert the column into TIMESTAMP first.
if to_type == ibis_dtypes.int64 and x.type() == ibis_dtypes.timestamp:
x_converted = x.cast(ibis_dtypes.Timestamp(timezone="UTC"))
return bigframes.core.compile.ibis_types.cast_ibis_value(x_converted, to_type)
if to_type == ibis_dtypes.int64 and x.type() == ibis_dtypes.time:
# The conversion unit is set to "us" (microseconds) for consistency
# with pandas converting time64[us][pyarrow] to int64[pyarrow].
return x.delta(ibis.time("00:00:00"), part="microsecond")
if x.type() == ibis_dtypes.int64:
# The conversion unit is set to "us" (microseconds) for consistency
# with pandas converting int64[pyarrow] to timestamp[us][pyarrow],
# timestamp[us, tz=UTC][pyarrow], and time64[us][pyarrow].
unit = "us"
x_converted = numeric_to_datetime(x, unit)
if to_type == ibis_dtypes.timestamp:
return x_converted.cast(ibis_dtypes.Timestamp())
elif to_type == ibis_dtypes.Timestamp(timezone="UTC"):
return x_converted
elif to_type == ibis_dtypes.time:
return x_converted.time()
return bigframes.core.compile.ibis_types.cast_ibis_value(x, to_type)
@scalar_op_compiler.register_unary_op(ops.IsInOp, pass_op=True)
def isin_op_impl(x: ibis_types.Value, op: ops.IsInOp):
contains_nulls = any(is_null(value) for value in op.values)
matchable_ibis_values = []
for item in op.values:
if not is_null(item):
try:
# we want values that *could* be cast to the dtype, but we don't want
# to actually cast it, as that could be lossy (eg float -> int)
item_inferred_type = ibis.literal(item).type()
if (
x.type() == item_inferred_type
or x.type().is_numeric()
and item_inferred_type.is_numeric()
):
matchable_ibis_values.append(item)
except TypeError:
pass
if op.match_nulls and contains_nulls:
return x.isnull() | x.isin(matchable_ibis_values)
else:
return x.isin(matchable_ibis_values)
@scalar_op_compiler.register_unary_op(ops.ToDatetimeOp, pass_op=True)
def to_datetime_op_impl(x: ibis_types.Value, op: ops.ToDatetimeOp):
if x.type() == ibis_dtypes.str:
return x.try_cast(ibis_dtypes.Timestamp(None))
else:
# Numerical inputs.
if op.format:
x = x.cast(ibis_dtypes.str).to_timestamp(op.format)
else:
# The default unit is set to "ns" (nanoseconds) for consistency
# with pandas, where "ns" is the default unit for datetime operations.
unit = op.unit or "ns"
x = numeric_to_datetime(x, unit)
return x.cast(ibis_dtypes.Timestamp(None))
@scalar_op_compiler.register_unary_op(ops.ToTimestampOp, pass_op=True)
def to_timestamp_op_impl(x: ibis_types.Value, op: ops.ToTimestampOp):
if x.type() == ibis_dtypes.str:
x = (
typing.cast(ibis_types.StringValue, x).to_timestamp(op.format)
if op.format
else timestamp(x)
)
else:
# Numerical inputs.
if op.format:
x = x.cast(ibis_dtypes.str).to_timestamp(op.format)
else:
# The default unit is set to "ns" (nanoseconds) for consistency
# with pandas, where "ns" is the default unit for datetime operations.
unit = op.unit or "ns"
x = numeric_to_datetime(x, unit)
return x.cast(ibis_dtypes.Timestamp(timezone="UTC"))
@scalar_op_compiler.register_unary_op(ops.RemoteFunctionOp, pass_op=True)
def remote_function_op_impl(x: ibis_types.Value, op: ops.RemoteFunctionOp):
ibis_node = getattr(op.func, "ibis_node", None)
if ibis_node is None:
raise TypeError(
f"only a bigframes remote function is supported as a callable. {constants.FEEDBACK_LINK}"
)
x_transformed = ibis_node(x)
if not op.apply_on_null:
x_transformed = ibis.case().when(x.isnull(), x).else_(x_transformed).end()
return x_transformed
@scalar_op_compiler.register_unary_op(ops.MapOp, pass_op=True)
def map_op_impl(x: ibis_types.Value, op: ops.MapOp):
case = ibis.case()
for mapping in op.mappings:
case = case.when(x == mapping[0], mapping[1])
return case.else_(x).end()
# Array Ops
@scalar_op_compiler.register_unary_op(ops.ArrayToStringOp, pass_op=True)
def array_to_string_op_impl(x: ibis_types.Value, op: ops.ArrayToStringOp):
return typing.cast(ibis_types.ArrayValue, x).join(op.delimiter)
@scalar_op_compiler.register_unary_op(ops.ArrayIndexOp, pass_op=True)
def array_index_op_impl(x: ibis_types.Value, op: ops.ArrayIndexOp):
res = typing.cast(ibis_types.ArrayValue, x)[op.index]
if x.type().is_string():
return _null_or_value(res, res != ibis.literal(""))
else:
return res
@scalar_op_compiler.register_unary_op(ops.ArraySliceOp, pass_op=True)
def array_slice_op_impl(x: ibis_types.Value, op: ops.ArraySliceOp):
res = typing.cast(ibis_types.ArrayValue, x)[op.start : op.stop : op.step]
if x.type().is_string():
return _null_or_value(res, res != ibis.literal(""))
else:
return res
# JSON Ops
@scalar_op_compiler.register_binary_op(ops.JSONSet, pass_op=True)
def json_set_op_impl(x: ibis_types.Value, y: ibis_types.Value, op: ops.JSONSet):
if x.type().is_json():
return json_set(
json_obj=x,
json_path=op.json_path,
json_value=y,
).to_expr()
else:
# Enabling JSON type eliminates the need for less efficient string conversions.
return vendored_ibis_ops.ToJsonString(
json_set(
json_obj=parse_json(x),
json_path=op.json_path,
json_value=y,
)
).to_expr()
@scalar_op_compiler.register_unary_op(ops.JSONExtract, pass_op=True)
def json_extract_op_impl(x: ibis_types.Value, op: ops.JSONExtract):
return json_extract(json_obj=x, json_path=op.json_path)
@scalar_op_compiler.register_unary_op(ops.JSONExtractArray, pass_op=True)
def json_extract_array_op_impl(x: ibis_types.Value, op: ops.JSONExtractArray):
return json_extract_array(json_obj=x, json_path=op.json_path)
### Binary Ops
def short_circuit_nulls(type_override: typing.Optional[ibis_dtypes.DataType] = None):
"""Wraps a binary operator to generate nulls of the expected type if either input is a null scalar."""
def short_circuit_nulls_inner(binop):
@functools.wraps(binop)
def wrapped_binop(x: ibis_types.Value, y: ibis_types.Value):
if isinstance(x, ibis_types.NullScalar):
return ibis_types.null().cast(type_override or y.type())
elif isinstance(y, ibis_types.NullScalar):
return ibis_types.null().cast(type_override or x.type())
else:
return binop(x, y)
return wrapped_binop
return short_circuit_nulls_inner
@scalar_op_compiler.register_binary_op(ops.strconcat_op)
def concat_op(
x: ibis_types.Value,
y: ibis_types.Value,
):
x_string = typing.cast(ibis_types.StringValue, x)
y_string = typing.cast(ibis_types.StringValue, y)
return x_string.concat(y_string)
@scalar_op_compiler.register_binary_op(ops.eq_op)
def eq_op(
x: ibis_types.Value,
y: ibis_types.Value,
):
return x == y
@scalar_op_compiler.register_binary_op(ops.eq_null_match_op)
def eq_nulls_match_op(
x: ibis_types.Value,
y: ibis_types.Value,
):
"""Variant of eq_op where nulls match each other. Only use where dtypes are known to be same."""
literal = ibis_types.literal("$NULL_SENTINEL$")
if hasattr(x, "fill_null"):
left = x.cast(ibis_dtypes.str).fill_null(literal)