This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathtest_managed_function.py
More file actions
1288 lines (1046 loc) · 46.4 KB
/
test_managed_function.py
File metadata and controls
1288 lines (1046 loc) · 46.4 KB
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.
import warnings
import google.api_core.exceptions
import pandas
import pyarrow
import pytest
import test_utils.prefixer
import bigframes
import bigframes.dataframe
import bigframes.dtypes
import bigframes.exceptions as bfe
import bigframes.pandas as bpd
from bigframes.testing.utils import cleanup_function_assets
prefixer = test_utils.prefixer.Prefixer("bigframes", "")
def test_managed_function_array_output(session, scalars_dfs, dataset_id):
try:
with warnings.catch_warnings(record=True) as record:
@session.udf(
dataset=dataset_id,
name=prefixer.create_prefix(),
)
def featurize(x: int) -> list[float]:
return [float(i) for i in [x, x + 1, x + 2]]
# No following conflict warning when there is no redundant type hints.
input_type_warning = "Conflicting input types detected"
return_type_warning = "Conflicting return type detected"
assert not any(input_type_warning in str(warning.message) for warning in record)
assert not any(
return_type_warning in str(warning.message) for warning in record
)
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_too"]
bf_result = bf_int64_col.apply(featurize).to_pandas()
pd_int64_col = scalars_pandas_df["int64_too"]
pd_result = pd_int64_col.apply(featurize)
# Ignore any dtype disparity.
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
# Make sure the read_gbq_function path works for this function.
featurize_ref = session.read_gbq_function(featurize.bigframes_bigquery_function)
assert hasattr(featurize_ref, "bigframes_bigquery_function")
assert featurize_ref.bigframes_remote_function is None
assert (
featurize_ref.bigframes_bigquery_function
== featurize.bigframes_bigquery_function
)
# Test on the function from read_gbq_function.
got = featurize_ref(10)
assert got == [10.0, 11.0, 12.0]
bf_result_gbq = bf_int64_col.apply(featurize_ref).to_pandas()
pandas.testing.assert_series_equal(bf_result_gbq, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(featurize, session.bqclient, ignore_failures=False)
def test_managed_function_series_apply(session, dataset_id, scalars_dfs):
try:
# An explicit name with "def" in it is used to test the robustness of
# the user code extraction logic, which depends on that term.
bq_name = f"{prefixer.create_prefix()}_def_to_test_code_extraction"
assert "def" in bq_name, "The substring 'def' was not found in 'bq_name'"
@session.udf(dataset=dataset_id, name=bq_name)
def foo(x: int) -> bytes:
return bytes(abs(x))
# Function should still work normally.
assert foo(-2) == bytes(2)
assert hasattr(foo, "bigframes_bigquery_function")
assert hasattr(foo, "input_dtypes")
assert hasattr(foo, "output_dtype")
assert hasattr(foo, "bigframes_bigquery_function_output_dtype")
scalars_df, scalars_pandas_df = scalars_dfs
bf_result_col = scalars_df["int64_too"].apply(foo)
bf_result = (
scalars_df["int64_too"].to_frame().assign(result=bf_result_col).to_pandas()
)
pd_result_col = scalars_pandas_df["int64_too"].apply(foo)
pd_result = (
scalars_pandas_df["int64_too"].to_frame().assign(result=pd_result_col)
)
pandas.testing.assert_frame_equal(bf_result, pd_result, check_dtype=False)
# Make sure the read_gbq_function path works for this function.
foo_ref = session.read_gbq_function(
function_name=foo.bigframes_bigquery_function, # type: ignore
)
assert hasattr(foo_ref, "bigframes_bigquery_function")
assert foo_ref.bigframes_remote_function is None
assert foo.bigframes_bigquery_function == foo_ref.bigframes_bigquery_function # type: ignore
bf_result_col_gbq = scalars_df["int64_too"].apply(foo_ref)
bf_result_gbq = (
scalars_df["int64_too"]
.to_frame()
.assign(result=bf_result_col_gbq)
.to_pandas()
)
pandas.testing.assert_frame_equal(bf_result_gbq, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(foo, session.bqclient, ignore_failures=False)
def test_managed_function_series_apply_array_output(
session,
dataset_id,
scalars_dfs,
):
try:
with pytest.warns(bfe.PreviewWarning, match="udf is in preview."):
@session.udf(dataset=dataset_id, name=prefixer.create_prefix())
def foo_list(x: int) -> list[float]:
return [float(abs(x)), float(abs(x) + 1)]
scalars_df, scalars_pandas_df = scalars_dfs
bf_result_col = scalars_df["int64_too"].apply(foo_list)
bf_result = (
scalars_df["int64_too"].to_frame().assign(result=bf_result_col).to_pandas()
)
pd_result_col = scalars_pandas_df["int64_too"].apply(foo_list)
pd_result = (
scalars_pandas_df["int64_too"].to_frame().assign(result=pd_result_col)
)
# Ignore any dtype difference.
pandas.testing.assert_frame_equal(bf_result, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(foo_list, session.bqclient, ignore_failures=False)
def test_managed_function_series_combine(session, dataset_id, scalars_dfs):
try:
# This function is deliberately written to not work with NA input.
def add(x: int, y: int) -> int:
return x + y
scalars_df, scalars_pandas_df = scalars_dfs
int_col_name_with_nulls = "int64_col"
int_col_name_no_nulls = "int64_too"
bf_df = scalars_df[[int_col_name_with_nulls, int_col_name_no_nulls]]
pd_df = scalars_pandas_df[[int_col_name_with_nulls, int_col_name_no_nulls]]
# make sure there are NA values in the test column.
assert any([pandas.isna(val) for val in bf_df[int_col_name_with_nulls]])
add_managed_func = session.udf(
dataset=dataset_id, name=prefixer.create_prefix()
)(add)
# with nulls in the series the managed function application would fail.
with pytest.raises(
google.api_core.exceptions.BadRequest, match="unsupported operand"
):
bf_df[int_col_name_with_nulls].combine(
bf_df[int_col_name_no_nulls], add_managed_func
).to_pandas()
# after filtering out nulls the managed function application should work
# similar to pandas.
pd_filter = pd_df[int_col_name_with_nulls].notnull()
pd_result = pd_df[pd_filter][int_col_name_with_nulls].combine(
pd_df[pd_filter][int_col_name_no_nulls], add
)
bf_filter = bf_df[int_col_name_with_nulls].notnull()
bf_result = (
bf_df[bf_filter][int_col_name_with_nulls]
.combine(bf_df[bf_filter][int_col_name_no_nulls], add_managed_func)
.to_pandas()
)
# ignore any dtype difference.
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
# Make sure the read_gbq_function path works for this function.
add_managed_func_ref = session.read_gbq_function(
add_managed_func.bigframes_bigquery_function
)
bf_result = (
bf_df[bf_filter][int_col_name_with_nulls]
.combine(bf_df[bf_filter][int_col_name_no_nulls], add_managed_func_ref)
.to_pandas()
)
pandas.testing.assert_series_equal(bf_result, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(
add_managed_func, session.bqclient, ignore_failures=False
)
def test_managed_function_series_combine_array_output(session, dataset_id, scalars_dfs):
try:
# The type hints in this function's signature has conflicts. The
# `input_types` and `output_type` arguments from udf decorator take
# precedence and will be used instead.
def add_list(x, y: bool) -> list[bool]:
return [x, y]
scalars_df, scalars_pandas_df = scalars_dfs
int_col_name_with_nulls = "int64_col"
int_col_name_no_nulls = "int64_too"
bf_df = scalars_df[[int_col_name_with_nulls, int_col_name_no_nulls]]
pd_df = scalars_pandas_df[[int_col_name_with_nulls, int_col_name_no_nulls]]
# Make sure there are NA values in the test column.
assert any([pandas.isna(val) for val in bf_df[int_col_name_with_nulls]])
with warnings.catch_warnings(record=True) as record:
add_list_managed_func = session.udf(
input_types=[int, int],
output_type=list[int],
dataset=dataset_id,
name=prefixer.create_prefix(),
)(add_list)
input_type_warning = "Conflicting input types detected"
assert any(input_type_warning in str(warning.message) for warning in record)
return_type_warning = "Conflicting return type detected"
assert any(return_type_warning in str(warning.message) for warning in record)
# After filtering out nulls the managed function application should work
# similar to pandas.
pd_filter = pd_df[int_col_name_with_nulls].notnull()
pd_result = pd_df[pd_filter][int_col_name_with_nulls].combine(
pd_df[pd_filter][int_col_name_no_nulls], add_list
)
bf_filter = bf_df[int_col_name_with_nulls].notnull()
bf_result = (
bf_df[bf_filter][int_col_name_with_nulls]
.combine(bf_df[bf_filter][int_col_name_no_nulls], add_list_managed_func)
.to_pandas()
)
# Ignore any dtype difference.
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
# Make sure the read_gbq_function path works for this function.
add_list_managed_func_ref = session.read_gbq_function(
function_name=add_list_managed_func.bigframes_bigquery_function, # type: ignore
)
assert hasattr(add_list_managed_func_ref, "bigframes_bigquery_function")
assert add_list_managed_func_ref.bigframes_remote_function is None
assert (
add_list_managed_func_ref.bigframes_bigquery_function
== add_list_managed_func.bigframes_bigquery_function
)
# Test on the function from read_gbq_function.
got = add_list_managed_func_ref(10, 38)
assert got == [10, 38]
bf_result_gbq = (
bf_df[bf_filter][int_col_name_with_nulls]
.combine(bf_df[bf_filter][int_col_name_no_nulls], add_list_managed_func_ref)
.to_pandas()
)
pandas.testing.assert_series_equal(bf_result_gbq, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(
add_list_managed_func, session.bqclient, ignore_failures=False
)
def test_managed_function_dataframe_map(session, dataset_id, scalars_dfs):
try:
def add_one(x):
return x + 1
mf_add_one = session.udf(
input_types=[int],
output_type=int,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(add_one)
scalars_df, scalars_pandas_df = scalars_dfs
int64_cols = ["int64_col", "int64_too"]
bf_int64_df = scalars_df[int64_cols]
bf_int64_df_filtered = bf_int64_df.dropna()
bf_result = bf_int64_df_filtered.map(mf_add_one).to_pandas()
pd_int64_df = scalars_pandas_df[int64_cols]
pd_int64_df_filtered = pd_int64_df.dropna()
pd_result = pd_int64_df_filtered.map(add_one)
# TODO(shobs): Figure why pandas .map() changes the dtype, i.e.
# pd_int64_df_filtered.dtype is Int64Dtype()
# pd_int64_df_filtered.map(lambda x: x).dtype is int64.
# For this test let's force the pandas dtype to be same as input.
for col in pd_result:
pd_result[col] = pd_result[col].astype(pd_int64_df_filtered[col].dtype)
pandas.testing.assert_frame_equal(bf_result, pd_result)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(mf_add_one, session.bqclient, ignore_failures=False)
def test_managed_function_dataframe_map_array_output(session, scalars_dfs, dataset_id):
try:
def add_one_list(x):
return [x + 1] * 3
mf_add_one_list = session.udf(
input_types=[int],
output_type=list[int],
dataset=dataset_id,
name=prefixer.create_prefix(),
)(add_one_list)
scalars_df, scalars_pandas_df = scalars_dfs
int64_cols = ["int64_col", "int64_too"]
bf_int64_df = scalars_df[int64_cols]
bf_int64_df_filtered = bf_int64_df.dropna()
bf_result = bf_int64_df_filtered.map(mf_add_one_list).to_pandas()
pd_int64_df = scalars_pandas_df[int64_cols]
pd_int64_df_filtered = pd_int64_df.dropna()
pd_result = pd_int64_df_filtered.map(add_one_list)
# Ignore any dtype difference.
pandas.testing.assert_frame_equal(bf_result, pd_result, check_dtype=False)
# Make sure the read_gbq_function path works for this function.
mf_add_one_list_ref = session.read_gbq_function(
function_name=mf_add_one_list.bigframes_bigquery_function, # type: ignore
)
bf_result_gbq = bf_int64_df_filtered.map(mf_add_one_list_ref).to_pandas()
pandas.testing.assert_frame_equal(bf_result_gbq, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(
mf_add_one_list, session.bqclient, ignore_failures=False
)
def test_managed_function_dataframe_apply_axis_1(session, dataset_id, scalars_dfs):
try:
scalars_df, scalars_pandas_df = scalars_dfs
series = scalars_df["int64_too"]
series_pandas = scalars_pandas_df["int64_too"]
def add_ints(x, y):
return x + y
add_ints_mf = session.udf(
input_types=[int, int],
output_type=int,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(add_ints)
assert add_ints_mf.bigframes_bigquery_function # type: ignore
with pytest.warns(
bigframes.exceptions.PreviewWarning, match="axis=1 scenario is in preview."
):
bf_result = (
bpd.DataFrame({"x": series, "y": series})
.apply(add_ints_mf, axis=1)
.to_pandas()
)
pd_result = pandas.DataFrame({"x": series_pandas, "y": series_pandas}).apply(
lambda row: add_ints(row["x"], row["y"]), axis=1
)
pandas.testing.assert_series_equal(
pd_result, bf_result, check_dtype=False, check_exact=True
)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(add_ints_mf, session.bqclient, ignore_failures=False)
def test_managed_function_dataframe_apply_axis_1_array_output(session, dataset_id):
bf_df = bigframes.dataframe.DataFrame(
{
"Id": [1, 2, 3],
"Age": [22.5, 23, 23.5],
"Name": ["alpha", "beta", "gamma"],
}
)
expected_dtypes = (
bigframes.dtypes.INT_DTYPE,
bigframes.dtypes.FLOAT_DTYPE,
bigframes.dtypes.STRING_DTYPE,
)
# Assert the dataframe dtypes.
assert tuple(bf_df.dtypes) == expected_dtypes
@session.udf(
input_types=[int, float, str],
output_type=list[str],
dataset=dataset_id,
name=prefixer.create_prefix(),
)
def foo(x, y, z):
return [str(x), str(y), z]
try:
assert getattr(foo, "is_row_processor") is False
assert getattr(foo, "input_dtypes") == expected_dtypes
assert getattr(foo, "output_dtype") == pandas.ArrowDtype(
pyarrow.list_(
bigframes.dtypes.bigframes_dtype_to_arrow_dtype(
bigframes.dtypes.STRING_DTYPE
)
)
)
assert getattr(foo, "output_dtype") == getattr(
foo, "bigframes_bigquery_function_output_dtype"
)
# Fails to apply on dataframe with incompatible number of columns.
with pytest.raises(
ValueError,
match="^Parameter count mismatch:.* expected 3 parameters but received 2 DataFrame columns.",
):
bf_df[["Id", "Age"]].apply(foo, axis=1)
with pytest.raises(
ValueError,
match="^Parameter count mismatch:.* expected 3 parameters but received 4 DataFrame columns.",
):
bf_df.assign(Country="lalaland").apply(foo, axis=1)
# Fails to apply on dataframe with incompatible column datatypes.
with pytest.raises(
ValueError,
match="^Data type mismatch for DataFrame columns: Expected .* Received .*",
):
bf_df.assign(Age=bf_df["Age"].astype("Int64")).apply(foo, axis=1)
# Successfully applies to dataframe with matching number of columns.
# and their datatypes.
with pytest.warns(
bigframes.exceptions.PreviewWarning,
match="axis=1 scenario is in preview.",
):
bf_result = bf_df.apply(foo, axis=1).to_pandas()
# Since this scenario is not pandas-like, let's handcraft the
# expected result.
expected_result = pandas.Series(
[
["1", "22.5", "alpha"],
["2", "23.0", "beta"],
["3", "23.5", "gamma"],
]
)
pandas.testing.assert_series_equal(
expected_result, bf_result, check_dtype=False, check_index_type=False
)
# Make sure the read_gbq_function path works for this function.
foo_ref = session.read_gbq_function(foo.bigframes_bigquery_function)
assert hasattr(foo_ref, "bigframes_bigquery_function")
assert foo_ref.bigframes_remote_function is None
assert foo_ref.bigframes_bigquery_function == foo.bigframes_bigquery_function
# Test on the function from read_gbq_function.
got = foo_ref(10, 38, "hello")
assert got == ["10", "38.0", "hello"]
with pytest.warns(
bigframes.exceptions.PreviewWarning,
match="axis=1 scenario is in preview.",
):
bf_result_gbq = bf_df.apply(foo_ref, axis=1).to_pandas()
pandas.testing.assert_series_equal(
bf_result_gbq, expected_result, check_dtype=False, check_index_type=False
)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(foo, session.bqclient, ignore_failures=False)
@pytest.mark.parametrize(
"connection_fixture",
[
"bq_connection_name",
"bq_connection",
],
)
def test_managed_function_with_connection(
session, scalars_dfs, dataset_id, request, connection_fixture
):
try:
bigquery_connection = request.getfixturevalue(connection_fixture)
@session.udf(
bigquery_connection=bigquery_connection,
dataset=dataset_id,
name=prefixer.create_prefix(),
)
def foo(x: int) -> int:
return x + 10
# Function should still work normally.
assert foo(-2) == 8
scalars_df, scalars_pandas_df = scalars_dfs
bf_result_col = scalars_df["int64_too"].apply(foo)
bf_result = (
scalars_df["int64_too"].to_frame().assign(result=bf_result_col).to_pandas()
)
pd_result_col = scalars_pandas_df["int64_too"].apply(foo)
pd_result = (
scalars_pandas_df["int64_too"].to_frame().assign(result=pd_result_col)
)
pandas.testing.assert_frame_equal(bf_result, pd_result, check_dtype=False)
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(foo, session.bqclient, ignore_failures=False)
def test_managed_function_options(session, dataset_id, scalars_dfs):
try:
def multiply_five(x: int) -> int:
return x * 5
mf_multiply_five = session.udf(
dataset=dataset_id,
name=prefixer.create_prefix(),
max_batching_rows=100,
container_cpu=2,
container_memory="2Gi",
)(multiply_five)
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_df = scalars_df["int64_col"]
bf_int64_df_filtered = bf_int64_df.dropna()
bf_result = bf_int64_df_filtered.apply(mf_multiply_five).to_pandas()
pd_int64_df = scalars_pandas_df["int64_col"]
pd_int64_df_filtered = pd_int64_df.dropna()
pd_result = pd_int64_df_filtered.apply(multiply_five)
pandas.testing.assert_series_equal(bf_result, pd_result, check_dtype=False)
# Make sure the read_gbq_function path works for this function.
multiply_five_ref = session.read_gbq_function(
function_name=mf_multiply_five.bigframes_bigquery_function, # type: ignore
)
assert mf_multiply_five.bigframes_bigquery_function == multiply_five_ref.bigframes_bigquery_function # type: ignore
bf_result = bf_int64_df_filtered.apply(multiply_five_ref).to_pandas()
pandas.testing.assert_series_equal(bf_result, pd_result, check_dtype=False)
# Retrieve the routine and validate its runtime configuration.
routine = session.bqclient.get_routine(
mf_multiply_five.bigframes_bigquery_function
)
# TODO(jialuo): Use the newly exposed class properties instead of
# accessing the hidden _properties after resolve of this issue:
# https://github.com/googleapis/python-bigquery/issues/2240.
assert routine._properties["externalRuntimeOptions"]["maxBatchingRows"] == "100"
assert routine._properties["externalRuntimeOptions"]["containerCpu"] == 2
assert routine._properties["externalRuntimeOptions"]["containerMemory"] == "2Gi"
finally:
# Clean up the gcp assets created for the managed function.
cleanup_function_assets(
mf_multiply_five, session.bqclient, ignore_failures=False
)
def test_managed_function_options_errors(session, dataset_id):
def foo(x: int) -> int:
return 0
with pytest.raises(
google.api_core.exceptions.BadRequest,
# For CPU Value >= 1.0, the value must be one of [1, 2, ...].
match="Invalid container_cpu function OPTIONS value",
):
session.udf(
dataset=dataset_id,
name=prefixer.create_prefix(),
max_batching_rows=100,
container_cpu=2.5,
container_memory="2Gi",
)(foo)
with pytest.raises(
google.api_core.exceptions.BadRequest,
# For less than 1.0 CPU, the value must be no less than 0.33.
match="Invalid container_cpu function OPTIONS value",
):
session.udf(
dataset=dataset_id,
name=prefixer.create_prefix(),
max_batching_rows=100,
container_cpu=0.10,
container_memory="512Mi",
)(foo)
with pytest.raises(
google.api_core.exceptions.BadRequest,
# For 2.00 CPU, the memory must be in the range of [256Mi, 8Gi].
match="Invalid container_memory function OPTIONS value",
):
session.udf(
dataset=dataset_id,
name=prefixer.create_prefix(),
max_batching_rows=100,
container_cpu=2,
container_memory="64Mi",
)(foo)
def test_managed_function_df_apply_axis_1(session, dataset_id, scalars_dfs):
columns = ["bool_col", "int64_col", "int64_too", "float64_col", "string_col"]
scalars_df, scalars_pandas_df = scalars_dfs
try:
def serialize_row(row):
# TODO(b/435021126): Remove explicit type conversion of the field
# "name" after the issue has been addressed. It is added only to
# accept partial pandas parity for the time being.
custom = {
"name": int(row.name),
"index": [idx for idx in row.index],
"values": [
val.item() if hasattr(val, "item") else val for val in row.values
],
}
return str(
{
"default": row.to_json(),
"split": row.to_json(orient="split"),
"records": row.to_json(orient="records"),
"index": row.to_json(orient="index"),
"table": row.to_json(orient="table"),
"custom": custom,
}
)
serialize_row_mf = session.udf(
input_types=bigframes.series.Series,
output_type=str,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(serialize_row)
assert getattr(serialize_row_mf, "is_row_processor")
bf_result = scalars_df[columns].apply(serialize_row_mf, axis=1).to_pandas()
pd_result = scalars_pandas_df[columns].apply(serialize_row, axis=1)
# bf_result.dtype is 'string[pyarrow]' while pd_result.dtype is 'object'
# , ignore this mismatch by using check_dtype=False.
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
# Let's make sure the read_gbq_function path works for this function.
serialize_row_reuse = session.read_gbq_function(
serialize_row_mf.bigframes_bigquery_function, is_row_processor=True
)
bf_result = scalars_df[columns].apply(serialize_row_reuse, axis=1).to_pandas()
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
finally:
# clean up the gcp assets created for the managed function.
cleanup_function_assets(
serialize_row_mf, session.bqclient, ignore_failures=False
)
def test_managed_function_df_apply_axis_1_aggregates(session, dataset_id, scalars_dfs):
columns = ["int64_col", "int64_too", "float64_col"]
scalars_df, scalars_pandas_df = scalars_dfs
try:
def analyze(row):
# TODO(b/435021126): Remove explicit type conversion of the fields
# after the issue has been addressed. It is added only to accept
# partial pandas parity for the time being.
return str(
{
"dtype": row.dtype,
"count": int(row.count()),
"min": int(row.min()),
"max": int(row.max()),
"mean": float(row.mean()),
"std": float(row.std()),
"var": float(row.var()),
}
)
with pytest.warns(
bfe.FunctionPackageVersionWarning,
match=(
"numpy, pandas, and pyarrow versions in the function execution"
"\nenvironment may not precisely match your local environment."
),
):
analyze_mf = session.udf(
input_types=bigframes.series.Series,
output_type=str,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(analyze)
assert getattr(analyze_mf, "is_row_processor")
bf_result = scalars_df[columns].dropna().apply(analyze_mf, axis=1).to_pandas()
pd_result = scalars_pandas_df[columns].dropna().apply(analyze, axis=1)
# bf_result.dtype is 'string[pyarrow]' while pd_result.dtype is 'object'
# , ignore this mismatch by using check_dtype=False.
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
finally:
# clean up the gcp assets created for the managed function.
cleanup_function_assets(analyze_mf, session.bqclient, ignore_failures=False)
@pytest.mark.parametrize(
("pd_df",),
[
pytest.param(
pandas.DataFrame(
{
"2": [1, 2, 3],
2: [1.5, 3.75, 5],
"name, [with. special'- chars\")/\\": [10, 20, 30],
(3, 4): ["pq", "rs", "tu"],
(5.0, "six", 7): [8, 9, 10],
'raise Exception("hacked!")': [11, 12, 13],
},
# Default pandas index has non-numpy type, whereas bigframes is
# always numpy-based type, so let's use the index compatible
# with bigframes. See more details in b/369689696.
index=pandas.Index([0, 1, 2], dtype=pandas.Int64Dtype()),
),
id="all-kinds-of-column-names",
),
pytest.param(
pandas.DataFrame(
{
"x": [1, 2, 3],
"y": [1.5, 3.75, 5],
"z": ["pq", "rs", "tu"],
},
index=pandas.MultiIndex.from_frame(
pandas.DataFrame(
{
"idx0": pandas.Series(
["a", "a", "b"], dtype=pandas.StringDtype()
),
"idx1": pandas.Series(
[100, 200, 300], dtype=pandas.Int64Dtype()
),
}
)
),
),
id="multiindex",
marks=pytest.mark.skip(
reason="TODO: revert this skip after this pandas bug is fixed: https://github.com/pandas-dev/pandas/issues/59908"
),
),
pytest.param(
pandas.DataFrame(
[
[10, 1.5, "pq"],
[20, 3.75, "rs"],
[30, 8.0, "tu"],
],
# Default pandas index has non-numpy type, whereas bigframes is
# always numpy-based type, so let's use the index compatible
# with bigframes. See more details in b/369689696.
index=pandas.Index([0, 1, 2], dtype=pandas.Int64Dtype()),
columns=pandas.MultiIndex.from_arrays(
[
["first", "last_two", "last_two"],
[1, 2, 3],
]
),
),
id="column-multiindex",
),
],
)
def test_managed_function_df_apply_axis_1_complex(session, dataset_id, pd_df):
bf_df = session.read_pandas(pd_df)
try:
def serialize_row(row):
# TODO(b/435021126): Remove explicit type conversion of the field
# "name" after the issue has been addressed. It is added only to
# accept partial pandas parity for the time being.
custom = {
"name": int(row.name),
"index": [idx for idx in row.index],
"values": [
val.item() if hasattr(val, "item") else val for val in row.values
],
}
return str(
{
"default": row.to_json(),
"split": row.to_json(orient="split"),
"records": row.to_json(orient="records"),
"index": row.to_json(orient="index"),
"custom": custom,
}
)
serialize_row_mf = session.udf(
input_types=bigframes.series.Series,
output_type=str,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(serialize_row)
assert getattr(serialize_row_mf, "is_row_processor")
bf_result = bf_df.apply(serialize_row_mf, axis=1).to_pandas()
pd_result = pd_df.apply(serialize_row, axis=1)
# ignore known dtype difference between pandas and bigframes.
pandas.testing.assert_series_equal(
pd_result, bf_result, check_dtype=False, check_index_type=False
)
finally:
# clean up the gcp assets created for the managed function.
cleanup_function_assets(
serialize_row_mf, session.bqclient, ignore_failures=False
)
@pytest.mark.skip(reason="Revert after this bug b/435018880 is fixed.")
def test_managed_function_df_apply_axis_1_na_nan_inf(dataset_id, session):
"""This test is for special cases of float values, to make sure any (nan,
inf, -inf) produced by user code is honored.
"""
bf_df = session.read_gbq(
"""\
SELECT "1" AS text, 1 AS num
UNION ALL
SELECT "2.5" AS text, 2.5 AS num
UNION ALL
SELECT "nan" AS text, IEEE_DIVIDE(0, 0) AS num
UNION ALL
SELECT "inf" AS text, IEEE_DIVIDE(1, 0) AS num
UNION ALL
SELECT "-inf" AS text, IEEE_DIVIDE(-1, 0) AS num
UNION ALL
SELECT "numpy nan" AS text, IEEE_DIVIDE(0, 0) AS num
UNION ALL
SELECT "pandas na" AS text, NULL AS num
"""
)
pd_df = bf_df.to_pandas()
try:
def float_parser(row):
import numpy as mynp
import pandas as mypd
if row["text"] == "pandas na":
return mypd.NA
if row["text"] == "numpy nan":
return mynp.nan
return float(row["text"])
float_parser_mf = session.udf(
input_types=bigframes.series.Series,
output_type=float,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(float_parser)
assert getattr(float_parser_mf, "is_row_processor")
pd_result = pd_df.apply(float_parser, axis=1)
bf_result = bf_df.apply(float_parser_mf, axis=1).to_pandas()
# bf_result.dtype is 'Float64' while pd_result.dtype is 'object'
# , ignore this mismatch by using check_dtype=False.
pandas.testing.assert_series_equal(pd_result, bf_result, check_dtype=False)
# Let's also assert that the data is consistent in this round trip
# (BQ -> BigFrames -> BQ -> GCF -> BQ -> BigFrames) w.r.t. their
# expected values in BQ.
bq_result = bf_df["num"].to_pandas()
bq_result.name = None
pandas.testing.assert_series_equal(bq_result, bf_result)
finally:
# clean up the gcp assets created for the managed function.
cleanup_function_assets(
float_parser_mf, session.bqclient, ignore_failures=False
)
def test_managed_function_df_apply_axis_1_args(session, dataset_id, scalars_dfs):
columns = ["int64_col", "int64_too"]
scalars_df, scalars_pandas_df = scalars_dfs
try:
def the_sum(s1, s2, x):
return s1 + s2 + x
the_sum_mf = session.udf(
input_types=[int, int, int],
output_type=int,
dataset=dataset_id,
name=prefixer.create_prefix(),
)(the_sum)
args1 = (1,)
# Fails to apply on dataframe with incompatible number of columns and args.
with pytest.raises(
ValueError,
match="^Parameter count mismatch:.* expected 3 parameters but received 4 values \\(3 DataFrame columns and 1 args\\)",
):
scalars_df[columns + ["float64_col"]].apply(the_sum_mf, axis=1, args=args1)
# Fails to apply on dataframe with incompatible column datatypes.
with pytest.raises(
ValueError,
match="^Data type mismatch for DataFrame columns: Expected .* Received .*",
):
scalars_df[columns].assign(
int64_col=lambda df: df["int64_col"].astype("Float64")
).apply(the_sum_mf, axis=1, args=args1)