-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmetrics.py
More file actions
2759 lines (2462 loc) · 98.7 KB
/
metrics.py
File metadata and controls
2759 lines (2462 loc) · 98.7 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
#
# https://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.
"""Base classes for Meterstick."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import datetime
import itertools
from typing import Any, Iterable, List, Optional, Sequence, Text, Union
from meterstick import sql
from meterstick import utils
import numpy as np
import pandas as pd
def compute_on(df,
split_by=None,
melted=False,
return_dataframe=True,
cache_key=None,
cache=None,
**kwargs):
# pylint: disable=g-long-lambda
return lambda x: x.compute_on(df, split_by, melted, return_dataframe,
cache_key, cache, **kwargs)
# pylint: enable=g-long-lambda
# pylint: disable=g-long-lambda
def compute_on_sql(
table,
split_by=None,
execute=None,
melted=False,
mode=None,
cache_key=None,
cache=None,
return_dataframe=True,
**kwargs):
"""A wrapper that metric | compute_on_sql() === metric.compute_on_sql()."""
return lambda m: m.compute_on_sql(
table,
split_by,
execute,
melted,
mode,
cache_key,
cache=cache,
return_dataframe=return_dataframe,
**kwargs)
def compute_on_beam(
table,
split_by=None,
execute=None,
melted=False,
mode=None,
cache_key=None,
cache=None,
sql_transform_kwargs=None,
dialect=None,
**kwargs,
):
"""A wrapper for metric.compute_on_beam()."""
return lambda m: m.compute_on_beam(
table,
split_by,
execute,
melted,
mode,
cache_key,
cache=cache,
sql_transform_kwargs=sql_transform_kwargs,
dialect=dialect,
**kwargs,
)
# pylint: enable=g-long-lambda
def to_sql(table, split_by=None):
return lambda metric: metric.to_sql(table, split_by)
# Classes we built so caching across instances can be enabled with confidence.
BUILT_INS = [
# Metrics
'MetricList',
'CompositeMetric',
'Ratio',
'Count',
'Sum',
'Dot',
'Mean',
'Max',
'Min',
'Nth',
'Quantile',
'Variance',
'StandardDeviation',
'CV',
'Correlation',
'Cov',
# Operations
'Distribution',
'Normalize',
'CumulativeDistribution',
'PercentChange',
'AbsoluteChange',
'PrePostChange',
'CUPED',
'MH',
'Jackknife',
'Bootstrap',
'PoissonBootstrap',
'LogTransform',
'ExponentialTransform',
'ExponentialPercentTransform',
'LogTransformedPercentChangeWithCI',
# Diversity Operations
'HHI',
'Entropy',
'TopK',
'Nxx',
# Models
'LinearRegression',
'Ridge',
'Lasso',
'ElasticNet',
'LogisticRegression',
]
class Metric(object):
"""Core class of Meterstick.
A Metric is defined broadly in Meterstick. It could be a routine metric like
CTR, or an operation like Bootstrap. As long as it taks a DataFrame and
returns a number or a pd.Series, it can be treated as a Metric.
The relations of methods of Metric are
<------------------------------------------------------compute_on-------------------------------------------------------->
<------------------------------compute_through----------------------------> |
| <-------compute_slices-------> | |
| |-> slice1 -> compute | | | |
df -> df.query(where) -> precompute -|-> slice2 -> compute | -> concat -> postcompute -> manipulate -> final_compute -> clean_up_cache # pylint: disable=line-too-long
|-> ...
In summary, compute() operates on a slice of data. precompute(),
postcompute(), compute_slices(), compute_through() and final_compute() operate
on the whole data. manipulate() does common data manipulation like melting
and cleaning. Caching is handled in compute_on().
If Metric has children Metrics, then compute_slices is further decomposed to
compute_children() -> compute_on_children(), if they are implemented. For such
Metrics, the decomposition makes the 'mixed' mode of compute_on_sql() simple.
The `mixed` mode computes children in SQL and the rest in Python, so as long
as a compute_children_sql() is implemented and has a similar return to
compute_children(), the compute_on_children() is reused and the `mixed` mode
automatically works.
Depending on your case, you can overwrite most of them, but we suggest you NOT
to overwrite compute_on because it might mess up the caching mechanism. Here
are some rules to help you to decide.
1. If your Metric has no vectorization over slices, overwrite compute(). To
overwrite, you can either create a new class inheriting from Metric or just
pass a lambda function into Metric.
2. If you have vectorization logic over slices, overwrite compute_slices().
See Sum() for an example.
3. As compute() operates on a slice of data, it doesn't have access to the
columns to split_by and the index value of the slice. If you need them, check
out compute_with_split_by(). See Jackknife for a real example.
4. The data passed into manipulate() should be a number, a pd.Series, or a
wide/unmelted pd.DataFrame.
It's possible to cache your result. However, as DataFrame is mutable, it's
slow to hash it (O(shape) complexity). To avoid hashing, for most cases you'd
rely on our MetricList() and CompositeMetric() which we know in one round
of their computation, the DataFrame doesn't change. Or if you have to run
many rounds of computation on the same DataFrame, you can directly assign a
cache_key in compute_on(), then it's your responsibility to ensure
same key always corresponds to the same DataFrame and split_by.
Your Metric shouldn't rely on the index of the input DataFrame. We might
set/reset the index during the computation so put all the information you need
in the columns.
Attributes:
name: Name of the Metric.
children: An iterable of Metric(s) this Metric based upon.
cache: A dict to store cached results.
where_: A string or list/tuple of strings to be concatenated that will be
passed to df.query() as a prefilter.
where: A string that will be passed to df.query() as a prefilter. It's ' and
'.join(where_).
additional_fingerprint_attrs: Additional attributes to be encoded into the
fingerprint. The attribute value must be hashable, or a list/dict of
hashables. See get_fingerprint() for how it's used.
extra_split_by: Used by Operation. See the doc there.
extra_index: Used by Operation. See the doc there.
name_tmpl: Used by Metrics that have children. It's applied to children's
names in the output.
is_operation: If this instance is an Operation.
cache_across_instances: If this Metric class will be cached across
instances, namely, different instances with same attributes that matter
can share the same place in cache. All the classes listed in BUILT_INS
have the feature enabled. For custom Metrics, by default different
instances don't share the same place in cache, because we don't know what
attributes matter. If you want to enable the feature for a custom Metric,
make sure you read the 'Custom Metric' and 'Caching' sections in the demo
notebook and understand the `additional_fingerprint_attrs` attribute
before setting this attribute to True.
cache: A dict to store the result. It's shared across the Metric tree.
cache_key: The key currently being used in computation.
"""
def __init__(self,
name: Text,
children: Optional[Union['Metric', Sequence[Union['Metric', int,
float]]]] = (),
where: Optional[Union[Text, Sequence[Text]]] = None,
name_tmpl=None,
extra_split_by: Optional[Union[Text, Iterable[Text]]] = None,
extra_index: Optional[Union[Text, Iterable[Text]]] = None,
additional_fingerprint_attrs: Optional[List[str]] = None):
self.name = name
self.cache = {}
self.cache_key = None
self.children = [children] if isinstance(children,
Metric) else children or []
self.where_ = None
self.where = where
self.extra_split_by = [extra_split_by] if isinstance(
extra_split_by, str) else extra_split_by or []
if extra_index is None:
self.extra_index = self.extra_split_by
else:
self.extra_index = [extra_index] if isinstance(extra_index,
str) else extra_index
self.additional_fingerprint_attrs = set(additional_fingerprint_attrs or ())
self.name_tmpl = name_tmpl
self.is_operation = False
self.cache_across_instances = False
self.cache_key = None
@property
def where(self):
if isinstance(self.where_, (list, tuple)):
where_ = self.where_
if len(where_) > 1:
where_ = (f'({i})' for i in sorted(where_))
return ' and '.join(where_)
return self.where_
@where.setter
def where(self, where):
if where is None:
self.where_ = None
elif isinstance(where, str):
self.where_ = (where,)
else:
self.where_ = tuple(where)
def add_where(self, where):
if where is None:
return self
where = [where] if isinstance(where, str) else list(where) or []
if not self.where_:
self.where = where
else:
self.where = tuple(set(list(self.where_) + where))
return self
def _compute_with_caching_and_postprocessing(
self,
compute_fn,
df,
split_by,
melted,
return_dataframe,
apply_name_tmpl,
cache_key,
cache,
*args,
**kwargs,
):
"""Wraps computation logic with caching and common postprocessing.
This function does:
1. Initializes a cache if it doesn't eixst.
2. Reads from cache if possible.
3. Otherwise calls compute_fn(df, split_by, *args, **kwargs).
4. Postprocesses the result like melting and converting to pandas DataFrame.
5. Cleans up cache if needed.
Args:
compute_fn: A function that compute_fn(df, split_by, *args, **kwargs)
returns a number, pd.Series or a melted DataFrame. See compute_through
and compute_through_sql for examples.
df: The DataFrame to compute on.
split_by: The columns that we use to split the data.
melted: Whether to transform the result to long format.
return_dataframe: Whether to convert the result to DataFrame if it's not.
If False, it could still return a DataFrame.
apply_name_tmpl: If to apply name_tmpl to the result. For example, in
Distribution('country', Sum('X')).compute_on(df), we first compute
Sum('X').compute_on(df, 'country'), then normalize, and finally apply
the name_tmpl 'Distribution of {}' to all column names.
cache_key: What key to use to cache the df. You can use anything that can
be a key of a dict except '_RESERVED' and tuples like ('_RESERVED', ..).
cache: The cache the whole Metric tree shares during one round of
computation. If it's None, we initiate an empty dict.
*args: Args passed to compute_fn.
**kwargs: Args passed to compute_fn.
Returns:
Final result returned to user. If split_by, it's a pd.Series or a
pd.DataFrame, otherwise it could be a base type.
"""
self.cache = {} if cache is None else cache
split_by = [split_by] if isinstance(split_by, str) else list(split_by or [])
try:
key = self.wrap_cache_key(cache_key or self.cache_key, split_by)
if self.in_cache(key):
raw_res = self.get_cached(key)
else:
self.cache_key = key
raw_res = compute_fn(df, split_by, *args, **kwargs)
self.save_to_cache(key, raw_res)
res = self.manipulate(raw_res, melted, return_dataframe, apply_name_tmpl)
return self.final_compute(res, melted, return_dataframe, split_by, df)
finally:
if cache_key is None: # Only root metric can have None as cache_key
self.clean_up_cache()
def wrap_cache_key(self, key, split_by=None, where=None, slice_val=None):
if key and not isinstance(key, utils.CacheKey) and self.cache_key:
key = self.cache_key.replace_key(key)
key = key or self.cache_key
return utils.CacheKey(self, key, where or self.where_, split_by, slice_val)
def save_to_cache(self, key, val, split_by=None):
if not isinstance(key, utils.CacheKey):
key = self.wrap_cache_key(key, split_by)
val = val.copy() if isinstance(val, (pd.Series, pd.DataFrame)) else val
self.cache[key] = val
def get_cached(self, key):
key = key if isinstance(key, utils.CacheKey) else self.wrap_cache_key(key)
return self.cache[key]
def in_cache(self, key):
key = key if isinstance(key, utils.CacheKey) else self.wrap_cache_key(key)
return key in self.cache
def find_all_in_cache_by_metric_type(self, metric):
"""Retrieves results from a certain type of metric from cache."""
return {k: v for k, v in self.cache.items() if k.metric.__class__ == metric}
def manipulate(
self,
res,
melted: bool = False,
return_dataframe: bool = True,
apply_name_tmpl=None,
):
"""Common adhoc data manipulation.
It does
1. Converts res to a DataFrame if asked.
2. Melts res to long format if asked.
3. Removes redundant index levels in res.
4. Apply self.name_tmpl to the output name or columns if asked.
Args:
res: Returned by compute_through(). Usually a DataFrame, but could be a
pd.Series or a base type.
melted: Whether to transform the result to long format.
return_dataframe: Whether to convert the result to DataFrame if it's not.
If False, it could still return a DataFrame if the input is already a
DataFrame.
apply_name_tmpl: If to apply name_tmpl to the result. For example, in
Distribution('country', Sum('X')).compute_on(df), we first compute
Sum('X').compute_on(df, 'country'), then normalize, and finally apply
the name_tmpl 'Distribution of {}' to all column names.
Returns:
Final result returned to user. If split_by, it's a pd.Series or a
pd.DataFrame, otherwise it could be a base type.
"""
if isinstance(res, pd.Series):
res.name = self.name
if not isinstance(res, pd.DataFrame) and return_dataframe:
res = self.to_dataframe(res)
if melted:
res = utils.melt(res)
if apply_name_tmpl:
res = utils.apply_name_tmpl(self.name_tmpl, res, melted)
return utils.remove_empty_level(res)
def to_dataframe(self, res):
if isinstance(res, pd.DataFrame):
return res
elif isinstance(res, pd.Series):
return pd.DataFrame(res)
return pd.DataFrame({self.name: [res]})
def final_compute(self, res, melted, return_dataframe, split_by, df):
del melted, return_dataframe, split_by, df # Useful in derived classes.
return res
def clean_up_cache(self):
"""Flushes the cache when a Metric tree has been computed.
A Metric and all the descendants form a tree. When a computation is started
from a MetricList or CompositeMetric, we know the input DataFrame is not
going to change in the computation. So even if user doesn't ask for caching,
we still enable it, but we need to clean things up when done. As the results
need to be cached until all Metrics in the tree have been computed, we
should only clean up at the end of the computation of the entry/top Metric.
We recognize the top Metric by looking at the cache_key. All descendants
will have it assigned as RESERVED_KEY but the entry Metric's will be None.
"""
self.cache.clear()
for m in self.traverse():
m.cache_key = None
def compute_on(
self,
df: pd.DataFrame,
split_by: Optional[Union[Text, List[Text]]] = None,
melted: bool = False,
return_dataframe: bool = True,
cache_key: Any = None,
cache=None,
):
"""Key API of Metric.
This is what you should call to use Metric. As caching is the shared part of
Metric, we suggest you NOT to overwrite this method. Overwriting
compute_slices and/or final_compute should be enough. If not, contact us
with your use cases.
Args:
df: The DataFrame to compute on.
split_by: The columns that we use to split the data.
melted: Whether to transform the result to long format.
return_dataframe: Whether to convert the result to DataFrame if it's not.
If False, it could still return a DataFrame.
cache_key: What key to use to cache the df. You can use anything that can
be a key of a dict except '_RESERVED' and tuples like ('_RESERVED', ..).
cache: The cache the whole Metric tree shares during one round of
computation. If it's None, we initiate an empty dict.
Returns:
Final result returned to user. If split_by, it's a pd.Series or a
pd.DataFrame, otherwise it could be a base type.
"""
return self._compute_with_caching_and_postprocessing(
self.compute_through,
df,
split_by,
melted,
return_dataframe,
None,
cache_key,
cache,
)
def compute_through(self, df, split_by: Optional[List[Text]] = None):
"""Precomputes df -> split df and apply compute() -> postcompute."""
df = df.query(self.where) if df is not None and self.where else df
res = self.precompute(df, split_by)
res = self.compute_slices(res, split_by)
return self.postcompute(res, split_by)
def precompute(self, df, split_by):
del split_by # Useful in derived classes.
return df
def postcompute(self, df, split_by):
del split_by # Useful in derived classes.
return df
def compute_slices(self, df, split_by: Optional[List[Text]] = None):
"""Applies compute() to all slices. Each slice needs a unique cache_key."""
if self.children:
try:
children = self.compute_children(df, split_by + self.extra_split_by)
return self.compute_on_children(children, split_by)
except NotImplementedError:
pass
if split_by:
# Adapted from http://esantorella.com/2016/06/16/groupby. This is faster
# than df.groupby(split_by).apply(self.compute).
slices = []
result = []
# Different DataFrames need to have different cache_keys. Here as we split
# the df so each slice need to has its own key. And we need to make sure
# the key is recovered so when we continue to compute other Metrics that
# might be vectoriezed, the key we use is the one for the whole df.
for df_slice, slice_i in self.split_data(df, split_by):
cache_key = self.cache_key
slice_i_iter = slice_i if isinstance(slice_i, tuple) else [slice_i]
self.cache_key = self.wrap_cache_key(
cache_key, slice_val=dict(zip(split_by, slice_i_iter)))
try:
result.append(self.compute_with_split_by(df_slice, split_by, slice_i))
slices.append(slice_i)
finally:
self.cache_key = cache_key
if isinstance(result[0], (pd.Series, pd.DataFrame)):
try:
return pd.concat(result, keys=slices, names=split_by, sort=False)
except ValueError:
if len(split_by) == 1:
# slices are tuples so pd unpacked it then the lengths didn't match.
split = split_by[0]
for r, s in zip(result, slices):
r[split] = [s] * len(r)
r.set_index(split, append=True, inplace=True)
res = pd.concat(result, sort=False)
if len(res.index.names) > 1:
res = res.reorder_levels(np.roll(res.index.names, 1))
return res
else:
if len(split_by) == 1:
ind = pd.Index(slices, name=split_by[0])
else:
ind = pd.MultiIndex.from_tuples(slices, names=split_by)
return pd.Series(result, index=ind)
else:
# Derived Metrics might do something in split_data().
df, _ = next(self.split_data(df, split_by))
return self.compute_with_split_by(df)
def compute_children(
self, df, split_by, melted=False, return_dataframe=True, cache_key=None
):
raise NotImplementedError
def compute_on_children(self, children, split_by):
"""Computes the return using the result returned by children Metrics.
Args:
children: The return of compute_children() or compute_children_sql().
split_by: The columns that we use to split the data.
Returns:
Almost the final result. Only some manipulations are still needed.
"""
if len(self.children) != 1:
raise ValueError('We can only handle one child Metric!')
if not split_by:
return self.compute(children)
result = []
slices = []
for d, i in self.split_data(children, split_by):
result.append(self.compute(d))
slices.append(i)
return pd.concat(result, keys=slices, names=split_by, sort=False)
@staticmethod
def split_data(df, split_by=None):
if not split_by:
yield df, None
else:
for k, idx in df.groupby(split_by, observed=True).indices.items():
# Use iloc rather than loc because indexes can have duplicates.
yield df.iloc[idx], k
def compute_with_split_by(
self, df, split_by: Optional[List[Text]] = None, slice_value=None
):
del split_by, slice_value # In case users need them in derived classes.
return self.compute(df)
def compute(self, df):
raise NotImplementedError
def compute_on_sql(
self,
table,
split_by=None,
execute=None,
melted=False,
mode=None,
cache_key=None,
cache=None,
return_dataframe=True,
):
"""Computes self in pure SQL or a mixed of SQL and Python.
Args:
table: The table we want to query from.
split_by: The columns that we use to split the data.
execute: A function that can executes a SQL query and returns a DataFrame.
melted: Whether to transform the result to long format.
mode: For Metrics with children, there are different ways to split the
computation into SQL and Python. For example, we can compute everything
in SQL, or the children in SQL and the parent in Python, or
grandchildren in SQL and the rest in Python. Here we support two modes.
The default mode where `mode` is None is recommend. This mode computes
maximizes the SQL usage, namely, everything can be computed in SQL is
computed in SQL. The opposite mode is called `mixed` where the SQL usage
is minimized, namely, only leaf Metrics are computed in SQL. There is
another `magic` mode which only applies to Models. The mode computes
sufficient statistics in SQL then use them to solve the coefficients in
Python. It's faster then the regular mode when fitting Models on large
data.
cache_key: What key to use to cache the result. You can use anything that
can be a key of a dict except '_RESERVED' and tuples like ('_RESERVED',
..).
cache: The cache the whole Metric tree shares during one round of
computation. If it's None, we initiate an empty dict.
return_dataframe: If False, result of simple Metric will be a number or
pd.Series (when has split_by).
Returns:
A pandas DataFrame. It's the computeation of self in SQL.
"""
return self._compute_with_caching_and_postprocessing(
self.compute_through_sql,
table,
split_by,
melted,
return_dataframe,
False,
cache_key,
cache,
execute,
mode,
)
def compute_through_sql(self, table, split_by, execute, mode):
"""Delegeates the computation to different modes."""
if mode not in (None, 'mixed', 'magic'):
raise ValueError('Mode %s is not supported!' % mode)
if not self.children:
res = self.compute_on_sql_sql_mode(table, split_by, execute)
return self.to_series_or_number_if_not_operation(res)
if not mode:
try:
res = self.compute_on_sql_sql_mode(table, split_by, execute)
return self.to_series_or_number_if_not_operation(res)
except NotImplementedError:
pass
if self.where:
table = sql.Sql(None, table, self.where)
try:
res = self.compute_on_sql_mixed_mode(table, split_by, execute, mode)
return self.to_series_or_number_if_not_operation(res)
except NotImplementedError:
raise
except Exception as e: # pylint: disable=broad-except
if mode:
raise ValueError(
'Please see the root cause of the failure above. You can try'
' `mode=None` to see if it helps.'
) from e
else:
raise
def to_series_or_number_if_not_operation(self, df):
return self.to_series_or_number(df) if not self.is_operation else df
def to_series_or_number(self, df):
if not isinstance(df, pd.DataFrame):
return df
df = df.squeeze(axis=1) # squeeze to a Series if possible
if (
isinstance(df, pd.Series)
and len(df.index.names) == 1
and not df.index.name
): # squeeze to a number if applicable
df = df.squeeze()
return df
def compute_on_sql_sql_mode(self, table, split_by=None, execute=None):
"""Executes the query from to_sql() and process the result."""
query = self.to_sql(table, split_by)
res = execute(str(query))
extra_idx = list(self.get_extra_idx(return_superset=True))
indexes = split_by + extra_idx if split_by else extra_idx
columns = [a.alias_raw for a in query.groupby.add(query.columns)]
columns[:len(indexes)] = indexes
res.columns = columns
if indexes:
res.set_index(indexes, inplace=True)
if split_by: # Use a stable sort.
res.sort_values(split_by, kind='mergesort', inplace=True)
return res
def to_sql(
self,
table,
split_by: Optional[Union[Text, List[Text]]] = None,
):
"""Generates SQL query for the metric.
Args:
table: The table or subquery we want to query from.
split_by: The columns that we use to split the data.
Returns:
The SQL query for the metric as a SQL instance, which is similar to a str.
Calling str() on it will get the query in string.
"""
global_filter = utils.get_global_filter(self)
indexes = sql.Columns(split_by).add(
self.get_extra_idx(return_superset=True)
)
with_data = sql.Datasources()
if isinstance(table, sql.Sql) and table.with_data:
table = copy.deepcopy(table)
with_data = table.with_data
table.with_data = None
if not sql.Datasource(table).is_table:
table = with_data.add(sql.Datasource(table, 'Data'))
query, with_data = self.get_sql_and_with_clause(table,
sql.Columns(split_by),
global_filter, indexes,
sql.Filters(), with_data)
query.with_data = with_data
# We try to avoid using CREATE TEMP TABLE when possible. It's only used when
# - the query contains RAND();
# - VOLATILE_RAND_IN_WITH_CLAUSE is True.
try:
if sql.VOLATILE_RAND_IN_WITH_CLAUSE and sql.RAND_FN() in str(query):
with_data.temp_tables = sql.get_temp_tables(with_data)
return query
except NotImplementedError:
# if RAND_FN is not implemented and we are here, that means the query
# never needs a random function so no need to create a temp table.
return query
return query
def get_sql_and_with_clause(self, table: sql.Datasource,
split_by: sql.Columns, global_filter: sql.Filters,
indexes: sql.Columns, local_filter: sql.Filters,
with_data: sql.Datasources):
"""Gets the SQL query for metric and its WITH clause separately.
Args:
table: The table we want to query from.
split_by: The columns that we use to split the data. Note it could be
different to the split_by passed to the root Metric. For example, in the
call of get_sql(AbsoluteChange('platform', 'tablet', Distribution(...)),
'country') the split_by Distribution gets will be ('country',
'platform') because AbsoluteChange adds an extra index.
global_filter: The filters that can be applied to the whole Metric tree.It
will be passed down all the way to the leaf Metrics and become the WHERE
clause in the query of root table.
indexes: The columns that we shouldn't apply any arithmetic operation. For
most of the time they are the indexes you would see in the result of
metric.compute_on(df).
local_filter: The filters that have been accumulated as we walk down the
metric tree. It's the collection of all filters of the ancestor Metrics
along the path so far. More filters might be added as we walk down to
the leaf Metrics. It's used there as inline filters like
IF(local_filter, value, NULL).
with_data: A global variable that contains all the WITH clauses we need.
It's being passed around and Metrics add the datasources they need to
it. It's added to the SQL instance eventually in get_sql() once we have
walked through the whole metric tree.
Returns:
The SQL instance for metric, without the WITH clause component.
The global with_data which holds all datasources we need in the WITH
clause.
"""
raise NotImplementedError('SQL generator is not implemented for %s.' %
type(self))
def compute_on_sql_mixed_mode(self, table, split_by, execute, mode=None):
"""Computes the child in SQL and the rest in Python."""
children = self.compute_children_sql(table, split_by, execute, mode)
return self.compute_on_children(children, split_by)
def compute_children_sql(
self, table, split_by, execute, mode, *args, **kwargs
):
"""The return should be similar to compute_children()."""
del args, kwargs # unused
children = []
for c in self.children:
if not isinstance(c, Metric):
children.append(c)
else:
children.append(
self.compute_util_metric_on_sql(
c, table, split_by + self.extra_split_by, execute, False, mode
)
)
return children[0] if len(self.children) == 1 else children
def compute_on_beam(
self,
pcol,
split_by=None,
execute=None,
melted=False,
mode=None,
cache_key=None,
cache=None,
sql_transform_kwargs=None,
dialect=None,
**kwargs,
):
"""Computes on an Apache Beam PCollection input.
Args:
pcol: An apache_beam.pvalue.PCollection instance we want to compute on. It
needs to have a schema so it's queryable.
split_by: The columns that we use to split the data.
execute: A function that can executes PCollection with a SqlTransform and
returns a DataFrame.
melted: Whether to transform the result to long format.
mode: Similar to the one in compute_on_sql(). `None` maximizes Beam usage
while 'mixed' minimizes the usage.
cache_key: What key to use to cache the result. You can use anything that
can be a key of a dict except '_RESERVED' and tuples like ('_RESERVED',
..).
cache: The cache the whole Metric tree shares during one round of
computation. If it's None, we initiate an empty dict.
sql_transform_kwargs: A dict that holds the kwargs to be passed to
SqlTransform defined in
https://beam.apache.org/releases/pydoc/2.30.0/apache_beam.transforms.sql.html.
dialect: The dialect of the SQL query. If not specified, it will be
the current DIALECT variable in sql.py. The DIALECT variable will be
changed during the computation of this metric and restored after that.
**kwargs: Other kwargs passed to compute_on_sql.
Returns:
A pandas DataFrame.
"""
# pylint: disable=g-import-not-at-top
from apache_beam import pvalue
from apache_beam.transforms import sql as beam_sql
if not isinstance(pcol, pvalue.PCollection):
raise ValueError(
'The input must be a PCollection but got %s!' % type(pcol)
)
def e(q):
label = f'Meterstick at {datetime.datetime.now()} runs {q}'
res = execute(
pcol
| label
>> beam_sql.SqlTransform(str(q), **(sql_transform_kwargs or {}))
)
return res
# pylint: disable=g-import-not-at-top
current_dialect = sql.DIALECT
try:
sql.set_dialect(dialect)
return self.compute_on_sql(
'PCOLLECTION', split_by, e, melted, mode, cache_key, cache, **kwargs
)
except Exception as e: # pylint: disable=broad-except
if not mode:
raise ValueError(
"Please see the root cause of the failure above. If it's caused by "
'the SQL query not being supported, try '
"compute_on_beam(..., mode='mixed')."
) from e
raise
finally:
sql.set_dialect(current_dialect)
def compute_equivalent(self, df, split_by=None):
equiv, df = utils.get_fully_expanded_equivalent_metric_tree(self, df)
return self.compute_util_metric_on(
equiv, df, split_by, return_dataframe=False
)
def compute_util_metric_on(
self,
metric,
df,
split_by,
melted=False,
return_dataframe=True,
cache_key=None,
):
"""Computes a util metric with caching and filtering handled correctly."""
cache_key = self.wrap_cache_key(cache_key, split_by)
return metric.compute_on(
df, split_by, melted, return_dataframe, cache_key, self.cache
)
def compute_util_metric_on_sql(
self,
metric,
table,
split_by=None,
execute=None,
melted=False,
mode=None,
cache_key=None,
return_dataframe=True,
):
"""Computes a util metric with caching and filtering handled correctly."""
cache_key = self.wrap_cache_key(cache_key, split_by)
return metric.compute_on_sql(
table,
split_by,
execute,
melted,
mode,
cache_key,
self.cache,
return_dataframe,
)
def get_equivalent(self, *auxiliary_cols):
"""Gets a Metric that is equivalent to self."""
res = self.get_equivalent_without_filter(*auxiliary_cols) # pylint: disable=assignment-from-none
if res:
res.name = self.name
res.add_where(self.where_)
return res
def get_equivalent_without_filter(self, *auxiliary_cols):
"""Gets a Metric that is equivalent to self but ignoring the filter."""
del auxiliary_cols # might be used in derived classes
return
def get_auxiliary_cols(self):
"""Returns the auxiliary columns required by the equivalent Metric.
See utils.add_auxiliary_cols() for the format of the return.
"""
return ()
@staticmethod
def group(df, split_by=None):
return df.groupby(split_by, observed=True) if split_by else df
def visualize_metric_tree(self, rendering_fn, strict=True):
"""Renders the Metric tree.
Args:
rendering_fn: A function that takes a string of DOT representation of the
Metric and renders it as side effect.
strict: If to make the DOT language graph strict. The strict mode will
dedupe duplicated edges.
"""
rendering_fn(self.to_dot(strict))
def to_dot(self, strict=True):
"""Represents the Metric in DOT language.
Args:
strict: If to make the DOT language graph strict. The strict mode will
dedupe duplicated edges.
Returns:
A string representing the Metric tree in DOT language.
"""
import pydot # pylint: disable=g-import-not-at-top
dot = pydot.Dot(self.name, graph_type='graph', strict=strict)
for m in self.traverse(include_constants=True):
label = str(getattr(m, 'name', m))
if getattr(m, 'where', ''):
label += ' where %s' % m.where
dot.add_node(pydot.Node(id(m), label=label))
def add_edges(metric):
if isinstance(metric, Metric):
for c in metric.children:
dot.add_edge(pydot.Edge(id(metric), id(c)))
add_edges(c)
add_edges(self)
return dot.to_string()
def get_extra_idx(self, return_superset=False):
"""Collects the extra indexes added by self and its descendants.