-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathoperations.py
More file actions
4376 lines (3993 loc) · 168 KB
/
operations.py
File metadata and controls
4376 lines (3993 loc) · 168 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.
"""Operation classes for Meterstick."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from typing import Any, Iterable, List, Literal, Optional, Sequence, Text, Tuple, Union
import warnings
from meterstick import confidence_interval_display
from meterstick import metrics
from meterstick import sql
from meterstick import utils
import numpy as np
import pandas as pd
from scipy import stats
def count_features(m: metrics.Metric):
"""Gets the width of the result of m.compute_on()."""
if not m:
return 0
if isinstance(m, metrics.MetricList):
return sum([count_features(i) for i in m])
if isinstance(m, MetricWithCI):
return (
count_features(m.children[0]) * 3
if m.confidence
else count_features(m.children[0]) * 2
)
if isinstance(m, (CUPED, PrePostChange)):
return count_features(m.children[0][0])
if isinstance(m, Operation):
return count_features(m.children[0])
if isinstance(m, metrics.CompositeMetric):
return max([count_features(i) for i in m.children])
if isinstance(m, metrics.Quantile):
if m.one_quantile:
return 1
return len(m.quantile)
return 1
class Operation(metrics.Metric):
"""A special kind of Metric that operates on other Metric instance(s).
The differences between Metric and Operation are
1. Operation must take other Metric(s) as the children to operate on.
2. The name of Operation is reflected in the result differently. A Metric
usually returns a 1D data and its name could just be used as the column.
However, Operation often operates on MetricList and one name doesn't fit
all. What we do is we apply the name_tmpl of Operation to all Metric names
Attributes:
name: Name of the Metric.
name_tmpl: The template to generate the name from child Metrics' names.
children: A Length-1 tuple of the child Metric(s) whose results will be the
input to the Operation. Might be None in __init__, but must be assigned
before compute().
extra_split_by: Many Operations rely on adding extra split_by columns to
child Metric. For example, PercentChange('condition', base_value,
Sum('X')).compute_on(df, 'grp') would compute Sum('X').compute_on(df,
['grp', 'condition']) then get the change. As the result, the CacheKey
used in PercentChange is different to that used in Sum('X'). The latter
has more columns in the split_by. extra_split_by records what columns need
to be added to children Metrics so we can flush the cache correctly. The
convention is extra_split_by comes after split_by.
extra_index: Not every extra_split_by show up in the result. For example,
the group_by columns in Models don't show up in the final output.
extra_index stores the columns that will show up and should be a subset of
extra_split_by. If not given, it's same as extra_split_by.
precomputable_in_jk_bs: Indicates whether it is possible to cut corners in
Jackknife and Bootstrap with unit. During the precomputation the leaf
Metrics might get modified. If the computation of the Operation won't get
impacted by that, it's precomputable. More precisely, the default
compute_children() returns children.compute_on(df, split_by +
extra_split_by). If all the Operation need from the descendants are
included in the result of compute_children(), the intermediate results it
cached during the computation, and the name of the descendants, then it's
precomputable. For examplem PercentChange(unit, 0, Sum(x)).compute_on(df)
needs Sum(x).compute_on(df, unit) and nothing more from the Sum, so it's
precomputable. Everything MH(unit, 0, Sum(x), grp).compute_on(df) needs
from Sum have been computed and cached during the computation of
Sum(x).compute_on(df, unit + grp) so MH is precomputable. The easiest way
to check if an Operation is precomputable is that you just set the
attribute to True and try Metrics like Jackknife(..., Operation(Dot('x',
'y', where='x>2'))) and Jackknife(..., Operation(Dot('x', 'y',
where='x>2')), enable_optimization=False). If the first one computes and
gives the same result to the second one, the Operation is precomputable.
where: A string or list of strings to be concatenated that will be passed to
df.query() as a prefilter.
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', ...). And
all other attributes inherited from Metric.
"""
def __init__(self,
child: Optional[metrics.Metric] = None,
name_tmpl: Optional[Text] = None,
extra_split_by: Optional[Union[Text, Iterable[Text]]] = None,
extra_index: Optional[Union[Text, Iterable[Text]]] = None,
name: Optional[Text] = None,
where: Optional[Union[Text, Sequence[Text]]] = None,
additional_fingerprint_attrs: Optional[List[str]] = None,
**kwargs):
if name_tmpl and not name:
name = name_tmpl.format(utils.get_name(child))
super(Operation,
self).__init__(name, child or (), where, name_tmpl, extra_split_by,
extra_index, additional_fingerprint_attrs, **kwargs)
self.precomputable_in_jk_bs = True
self.is_operation = True
def compute_slices(self, df, split_by: Optional[List[Text]] = None):
try:
children = self.compute_children(df, split_by + self.extra_split_by)
res = self.compute_on_children(children, split_by)
if isinstance(res, pd.Series):
return pd.DataFrame([res], columns=children.columns)
return res
except NotImplementedError:
return super(Operation, self).compute_slices(df, split_by)
def compute_children(self,
df: pd.DataFrame,
split_by=None,
melted=False,
return_dataframe=True,
cache_key=None):
return self.compute_child(df, split_by, melted, return_dataframe, cache_key)
def compute_child(self,
df: pd.DataFrame,
split_by=None,
melted=False,
return_dataframe=True,
cache_key=None):
child = self.children[0]
return self.compute_util_metric_on(child, df, split_by, melted,
return_dataframe, cache_key)
def compute_child_sql(self,
table,
split_by,
execute,
melted=False,
mode=None,
cache_key=None):
child = self.children[0]
cache_key = self.wrap_cache_key(cache_key, split_by)
return self.compute_util_metric_on_sql(child, table, split_by, execute,
melted, mode, cache_key)
def compute_on_sql_mixed_mode(self, table, split_by, execute, mode=None):
res = super(Operation,
self).compute_on_sql_mixed_mode(table, split_by, execute, mode)
return utils.apply_name_tmpl(self.name_tmpl, res)
def split_data(self, df, split_by=None):
"""Splits the DataFrame returned by the children."""
for k, idx in df.groupby(split_by, observed=True).indices.items():
# split_by will be added back later during the concatenation.
# Use iloc rather than loc because indexes can have duplicates.
yield df.iloc[idx].droplevel(split_by), k
def manipulate(
self,
res,
melted: bool = False,
return_dataframe: bool = True,
apply_name_tmpl=None,
):
apply_name_tmpl = True if apply_name_tmpl is None else apply_name_tmpl
return super(Operation, self).manipulate(
res, melted, return_dataframe, apply_name_tmpl
)
def __call__(self, child: metrics.Metric):
op = copy.deepcopy(self) if self.children else self
op.name = op.name_tmpl.format(utils.get_name(child))
op.children = (child,)
return op
class Distribution(Operation):
"""Computes the normalized values of a Metric over column(s).
Attributes:
extra_split_by: A list of column(s) to normalize over.
children: A tuple of a Metric whose result we normalize on.
And all other attributes inherited from Operation.
"""
def __init__(self,
over: Union[Text, List[Text]],
child: Optional[metrics.Metric] = None,
name_tmpl: Text = 'Distribution of {}',
**kwargs):
super(Distribution, self).__init__(child, name_tmpl, over, **kwargs)
def compute_on_children(self, children, split_by):
total = (
children.groupby(level=split_by, observed=True).sum()
if split_by
else children.sum()
)
res = children / total
# The order might get messed up for MultiIndex.
if len(children.index.names) > 1:
return res.reorder_levels(children.index.names)
return res
def get_sql_and_with_clause(self, table, split_by, global_filter, indexes,
local_filter, with_data):
"""Gets the SQL query and WITH clause.
The query is constructed by
1. Get the query for the child metric.
2. Keep all indexing/groupby columns unchanged.
3. For all value columns, get
value / SUM(value) OVER (PARTITION BY split_by).
Args:
table: The table we want to query from.
split_by: The columns that we use to split the data.
global_filter: The sql.Filters that can be applied to the whole Metric
tree.
indexes: The columns that we shouldn't apply any arithmetic operation.
local_filter: The sql.Filters that have been accumulated so far.
with_data: A global variable that contains all the WITH clauses we need.
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.
"""
local_filter = (
sql.Filters(self.where_).add(local_filter).remove(global_filter)
)
all_split_by = sql.Columns(split_by).add(self.extra_split_by)
child_sql, with_data = self.children[0].get_sql_and_with_clause(
table, all_split_by, global_filter, indexes, local_filter, with_data)
child_table = sql.Datasource(child_sql, 'DistributionRaw')
child_table_alias = with_data.merge(child_table)
groupby = sql.Columns(all_split_by.aliases)
columns = sql.Columns()
for c in child_sql.columns:
if c.alias in groupby:
continue
col = sql.Column(c.alias) / sql.Column(
c.alias, 'SUM({})', partition=split_by.aliases
)
col.set_alias('Distribution of %s' % c.alias_raw)
columns.add(col)
return sql.Sql(groupby.add(columns), child_table_alias), with_data
Normalize = Distribution # An alias.
class CumulativeDistribution(Distribution):
"""Computes the normalized cumulative sum.
Attributes:
extra_split_by: A list of column(s) to normalize over.
children: A tuple of a Metric whose result we compute the cumulative
distribution on.
order: An iterable. The over column will be ordered by it before computing
cumsum.
ascending: Sort ascending or descending.
sort_by_values: Boolean that indicates whether or not to sort by the
computed distribution values instead of the `over` column. It works with
`ascending` but not `order`.
And all other attributes inherited from Distribution.
"""
def __init__(
self,
over: Text,
child: Optional[metrics.Metric] = None,
order=None,
ascending: bool = True,
sort_by_values: bool = False,
name_tmpl: Text = 'Cumulative Distribution of {}',
additional_fingerprint_attrs=None,
**kwargs,
):
self.order = order
self.ascending = ascending
self.sort_by_values = sort_by_values
super(CumulativeDistribution, self).__init__(
over,
child,
name_tmpl,
additional_fingerprint_attrs=['order', 'ascending', 'sort_by_values']
+ (additional_fingerprint_attrs or []),
**kwargs,
)
if order and len(self.extra_index) > 1:
raise ValueError(
'Only one column is supported when "order" is specified.'
)
if order and sort_by_values:
raise ValueError('Custom order is not allowed when sorting by values!')
def compute_on_children(self, children, split_by):
dist = super(CumulativeDistribution, self).compute_on_children(
children, split_by
)
if self.order:
order = self.order if self.ascending else reversed(self.order)
level = None if len(dist.index.names) == 1 else self.extra_index[0]
dist = dist.reindex(order, level=level).dropna()
res = self.group(dist, split_by).cumsum()
elif not self.sort_by_values:
dist.sort_values(self.extra_index, ascending=self.ascending, inplace=True)
res = self.group(dist, split_by).cumsum()
else:
cumsum = []
for col in dist:
cumsum.append(
self.group(
dist[col].sort_values(ascending=self.ascending), split_by
).cumsum()
)
res = pd.concat(cumsum, axis=1)
if split_by:
res.sort_index(level=split_by, sort_remaining=False, inplace=True)
return res
def get_sql_and_with_clause(self, table, split_by, global_filter, indexes,
local_filter, with_data):
"""Gets the SQL query and WITH clause.
The query is constructed by
1. Get the query for the Distribution of the child Metric.
2. Keep all indexing/groupby columns unchanged.
3. For all value columns, get the cumulative sum by summing over
'ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW'.
Args:
table: The table we want to query from.
split_by: The columns that we use to split the data.
global_filter: The sql.Filters that can be applied to the whole Metric
tree.
indexes: The columns that we shouldn't apply any arithmetic operation.
local_filter: The sql.Filters that have been accumulated so far.
with_data: A global variable that contains all the WITH clauses we need.
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.
"""
dist_sql, with_data = super(
CumulativeDistribution, self
).get_sql_and_with_clause(
table, split_by, global_filter, indexes, local_filter, with_data
)
child_table = sql.Datasource(dist_sql, 'CumulativeDistributionRaw')
child_table_alias = with_data.merge(child_table)
columns = sql.Columns(indexes.aliases)
order = list(self.get_extra_idx(self))
order = [
sql.Column(self.get_ordered_col(sql.Column(o).alias), auto_alias=False)
for o in order
]
for c in dist_sql.columns:
if c in columns:
continue
col = sql.Column(
c.alias,
'SUM({})',
partition=split_by.aliases,
order=self.get_ordered_col(c.alias) if self.sort_by_values else order,
window_frame='ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW',
)
col.set_alias('Cumulative %s' % c.alias_raw)
columns.add(col)
return sql.Sql(columns, child_table_alias), with_data
def get_ordered_col(self, over):
if self.order:
over = 'CASE %s\n' % over
tmpl = 'WHEN %s THEN %s'
over += '\n'.join(
tmpl % (_format_to_condition(o), i) for i, o in enumerate(self.order)
)
over += '\nELSE %s\nEND' % len(self.order)
return over if self.ascending else over + ' DESC'
def _format_to_condition(val):
if isinstance(val, str) and not val.startswith('$'):
# Use single quotes instead of double quotes for string literals as it's
# compatible with more SQL engines.
return "'%s'" % val
return '%s' % val
class Comparison(Operation):
"""Base class for comparisons like percent/absolute change."""
def __init__(self,
condition_column,
baseline_key,
child: Optional[metrics.Metric] = None,
include_base: bool = False,
name_tmpl: Optional[Text] = None,
additional_fingerprint_attrs=None,
**kwargs):
self.baseline_key = baseline_key
self.include_base = include_base
additional_fingerprint_attrs = additional_fingerprint_attrs or []
super(Comparison, self).__init__(
child,
name_tmpl,
extra_split_by=condition_column,
additional_fingerprint_attrs=['baseline_key', 'include_base'] +
additional_fingerprint_attrs,
**kwargs)
@property
def stratified_by(self):
return self.extra_split_by[len(self.extra_index):]
@stratified_by.setter
def stratified_by(self, stratified_by):
stratified_by = (
stratified_by if isinstance(stratified_by, list) else [stratified_by]
)
self.extra_split_by[len(self.extra_index):] = stratified_by
def get_sql_and_with_clause(self, table, split_by, global_filter, indexes,
local_filter, with_data):
"""Gets the SQL for PercentChange or AbsoluteChange.
The query is constructed by
1. Get the query for the child metric and add it to with_data, we call it
raw_value_table.
2. Query the rows that only has the base value from raw_value_table, add it
to with_data too. We call it base_value_table.
3. sql.Join the two tables and computes the change for all value columns.
For example, the query for
AbsoluteChange('condition', 'base_value', metrics.Mean('click'))
will look like this:
WITH
ChangeRaw AS (SELECT
split_by,
condition,
AVG(click) AS `mean(click)`
FROM $DATA
GROUP BY split_by, condition),
ChangeBase AS (SELECT
split_by,
`mean(click)`
FROM ChangeRaw
WHERE
condition = "base_value")
SELECT
split_by,
condition,
ChangeRaw.`mean(click)` - ChangeBase.`mean(click)`
AS `mean(click) Absolute Change`
FROM ChangeRaw
JOIN
ChangeBase
USING (split_by)
WHERE
condition != "base_value"
Args:
table: The table we want to query from.
split_by: The columns that we use to split the data.
global_filter: The sql.Filters that can be applied to the whole Metric
tree.
indexes: The columns that we shouldn't apply any arithmetic operation.
local_filter: The sql.Filters that have been accumulated so far.
with_data: A global variable that contains all the WITH clauses we need.
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.
"""
cond_cols = sql.Columns(self.extra_index)
raw_table_sql, with_data = self.get_change_raw_sql(
table, split_by, global_filter, indexes, local_filter, with_data
)
raw_table = sql.Datasource(raw_table_sql, 'ChangeRaw')
raw_table_alias = with_data.merge(raw_table)
base = self.baseline_key if isinstance(self.baseline_key,
tuple) else [self.baseline_key]
base_cond = ('%s = %s' % (c, _format_to_condition(b))
for c, b in zip(cond_cols.aliases, base))
base_cond = ' AND '.join(base_cond)
cols = sql.Columns(raw_table_sql.groupby.aliases)
cols.add(raw_table_sql.columns.aliases)
base_value = sql.Sql(
cols.difference(cond_cols.aliases), raw_table_alias, base_cond)
base_table = sql.Datasource(base_value, 'ChangeBase')
base_table_alias = with_data.merge(base_table)
cond = None if self.include_base else sql.Filters([f'NOT ({base_cond})'])
sql_template_for_comparison = self.get_sql_template_for_comparison(
raw_table_alias, base_table_alias
)
columns = sql.Columns()
val_col_len = len(raw_table_sql.all_columns) - len(indexes)
for r, b in zip(
raw_table_sql.all_columns[-val_col_len:],
base_value.columns[-val_col_len:],
):
col = sql.Column(
sql_template_for_comparison % {'r': r.alias, 'b': b.alias},
alias=self.name_tmpl.format(r.alias_raw),
)
columns.add(col)
using = indexes.difference(cond_cols)
return (
sql.Sql(
sql.Columns(indexes.aliases).add(columns),
sql.Join(raw_table_alias, base_table_alias, using=using),
cond,
),
with_data,
)
def get_change_raw_sql(
self, table, split_by, global_filter, indexes, local_filter, with_data
):
"""Gets the query where the comparison will be carried out."""
local_filter = (
sql.Filters(self.where_).add(local_filter).remove(global_filter)
)
groupby = sql.Columns(split_by).add(self.extra_split_by)
raw_table_sql, with_data = self.children[0].get_sql_and_with_clause(
table, groupby, global_filter, indexes, local_filter, with_data
)
return raw_table_sql, with_data
def get_sql_template_for_comparison(self, raw_table_alias, base_table_alias):
"""Gets a string template to compute the comparison between columns.
The template needs to use "%(r)s" to represent the column from
raw_table_alias and "%(b)s" to represent that from base_table_alias.
For example, AbsoluteChange returns
f'{raw_table_alias}.%(r)s - {base_table_alias}.%(b)s'.
Args:
raw_table_alias: The alias of the raw table for comparison.
base_table_alias: The alias of the base table for comparison.
Returns:
A string template to compute the comparison between two columns.
"""
raise NotImplementedError
class PercentChange(Comparison):
"""Percent change estimator on a Metric.
Attributes:
extra_split_by: The column(s) that contains the conditions.
baseline_key: The value of the condition that represents the baseline (e.g.,
"Control"). All conditions will be compared to this baseline. If
condition_column contains multiple columns, then baseline_key should be a
tuple.
children: A tuple of a Metric whose result we compute percentage change on.
include_base: A boolean for whether the baseline condition should be
included in the output.
And all other attributes inherited from Operation.
"""
def __init__(self,
condition_column: Text,
baseline_key,
child: Optional[metrics.Metric] = None,
include_base: bool = False,
name_tmpl: Text = '{} Percent Change',
**kwargs):
super(PercentChange, self).__init__(condition_column, baseline_key, child,
include_base, name_tmpl, **kwargs)
def compute_on_children(self, children, split_by):
level = None
if split_by:
level = self.extra_index[0] if len(
self.extra_index) == 1 else self.extra_index
# Avoid ZeroDivisionError when input is object dytpe.
children = children.astype(float)
res = (children / children.xs(self.baseline_key, level=level) - 1) * 100
if len(children.index.names) > 1: # xs might mess up the level order.
res = res.reorder_levels(children.index.names)
if not self.include_base:
to_drop = [i for i in res.index.names if i not in self.extra_index]
idx_to_match = res.index.droplevel(to_drop) if to_drop else res.index
res = res[~idx_to_match.isin([self.baseline_key])]
return res
def get_sql_template_for_comparison(self, raw_table_alias, base_table_alias):
return (
sql.SAFE_DIVIDE_FN(
numer=f'{raw_table_alias}.%(r)s',
denom=f'{base_table_alias}.%(b)s',
)
+ ' * 100 - 100'
)
class AbsoluteChange(Comparison):
"""Absolute change estimator on a Metric.
Attributes:
extra_index: The column(s) that contains the conditions.
baseline_key: The value of the condition that represents the baseline (e.g.,
"Control"). All conditions will be compared to this baseline. If
condition_column contains multiple columns, then baseline_key should be a
tuple.
children: A tuple of a Metric whose result we compute absolute change on.
include_base: A boolean for whether the baseline condition should be
included in the output.
And all other attributes inherited from Operation.
"""
def __init__(self,
condition_column: Text,
baseline_key,
child: Optional[metrics.Metric] = None,
include_base: bool = False,
name_tmpl: Text = '{} Absolute Change',
**kwargs):
super(AbsoluteChange, self).__init__(condition_column, baseline_key, child,
include_base, name_tmpl, **kwargs)
def compute_on_children(self, children, split_by):
level = None
if split_by:
level = self.extra_index[0] if len(
self.extra_index) == 1 else self.extra_index
# Don't use "-=". For multiindex it might go wrong. The reason is DataFrame
# has different implementations for __sub__ and __isub__. ___isub__ tries
# to reindex to update in place which sometimes lead to lots of NAs.
res = children - children.xs(self.baseline_key, level=level)
if len(children.index.names) > 1: # xs might mess up the level order.
res = res.reorder_levels(children.index.names)
if not self.include_base:
to_drop = [i for i in res.index.names if i not in self.extra_index]
idx_to_match = res.index.droplevel(to_drop) if to_drop else res.index
res = res[~idx_to_match.isin([self.baseline_key])]
return res
def get_sql_template_for_comparison(self, raw_table_alias, base_table_alias):
return f'{raw_table_alias}.%(r)s - {base_table_alias}.%(b)s'
def _check_covariates_match_base(base, cov):
len_base = len(base) if isinstance(base, metrics.MetricList) else 1
len_cov = len(cov) if isinstance(cov, metrics.MetricList) else 1
if len_cov != len_base:
raise ValueError(
'Covariates and base metric must have the same length. Got'
f' {len_cov} and {len_base}'
)
class PrePostChange(PercentChange):
"""PrePost Percent change estimator on a Metric.
Computes the percent change after controlling for preperiod metrics.
Essentially, if the data only has a baseline and a treatment slice, PrePost
1. centers the covariates
2. fit child ~ intercept + was_treated * covariate.
As covariate is centered, the intercept is the mean value for the baseline.
The coefficient for the was_treated term is the mean effect of treatment.
PrePostChange returns the latter / the former * 100.
See https://arxiv.org/pdf/1711.00562.pdf for more details.
For data with multiple treatments, the result is same as applying the method
to every pair of baseline and treatment.
If child returns multiple columns, the result is same as applying the method
to every column in it.
Attributes:
extra_split_by: The column(s) that contains the conditions.
baseline_key: The value of the condition that represents the baseline (e.g.,
"Control"). All conditions will be compared to this baseline. If
condition_column contains multiple columns, then baseline_key should be a
tuple.
child: A Metric(List) we want to compute change on. If it returns multiple
columns, the result is same as applying the method to every column in it.
covariates: A MetricList of the covariates for adjustment.
children: MetricList([child, covariates]).
include_base: A boolean for whether the baseline condition should be
included in the output.
multiple_covariates: If True, all covariates are used together as in the
adjustment. If False, we zip the child and covariates and create a list of
one-covariate PrePostChange. Namely,
PrePostChange(child=[x1, x2], covariates=[y1, y2],
multiple_covariates=False) is equivalent to
MetricList([PrePostChange(x1, y1), PrePostChange(x2, y2)]).
k_covariates: The length of covariates.
And all other attributes inherited from Operation.
"""
def __init__(self,
condition_column,
baseline_key,
child=None,
covariates=None,
stratified_by=None,
include_base=False,
multiple_covariates=True,
name_tmpl: Text = '{} PrePost Percent Change',
**kwargs):
if isinstance(child, (List, Tuple)):
child = metrics.MetricList(child)
if isinstance(covariates, (List, Tuple)):
covariates = metrics.MetricList(covariates)
if child and covariates:
if not multiple_covariates:
_check_covariates_match_base(child, covariates)
child = metrics.MetricList((child, covariates))
else:
child = None
self.multiple_covariates = multiple_covariates
stratified_by = [stratified_by] if isinstance(stratified_by,
str) else stratified_by or []
condition_column = [condition_column] if isinstance(
condition_column, str) else condition_column
additional_fingerprint_attrs = kwargs.pop(
'additional_fingerprint_attrs', []
)
additional_fingerprint_attrs += ['multiple_covariates']
super(PrePostChange, self).__init__(
condition_column + stratified_by,
baseline_key,
child,
include_base,
name_tmpl,
additional_fingerprint_attrs=additional_fingerprint_attrs,
**kwargs,
)
self.extra_index = condition_column
@property
def child(self):
return self.children[0][0] if self.children else None
@property
def covariates(self):
return self.children[0][1] if self.children else None
@property
def k_covariates(self) -> int:
return count_features(self.covariates)
def compute_slices(self, df, split_by=None):
if self.multiple_covariates:
return super(PrePostChange, self).compute_slices(df, split_by)
equiv, _ = utils.get_equivalent_metric(self)
res = self.compute_util_metric_on(equiv, df, split_by)
tmpl_len = len(self.name_tmpl.format(''))
res.columns = [c[:-tmpl_len] for c in res.columns]
return res
def compute_children(
self,
df,
split_by=None,
melted=False,
return_dataframe=True,
cache_key=None,
):
if not self.multiple_covariates:
raise NotImplementedError # shouldn't be called.
child, covariates = super(PrePostChange, self).compute_children(
df, split_by, return_dataframe=False, cache_key=cache_key)
original_split_by = [s for s in split_by if s not in self.extra_split_by]
return self.adjust_value(child, covariates, original_split_by)
def adjust_value(self, child, covariates, split_by):
"""Adjust the raw value by controlling for Pre-metrics.
As described in the class doc, PrePost fits a linear model,
child ~ β0 + β1 * treated + β2 * covariate + β3 * treated * covariate,
to adjust the effect, where β0 is the average effect of the control while
β0 + β1 is that of the treatment group. Note that we center covariate first
so in practice β0 and β1 can be achieved by fitting small models. β0_c in
child ~ β0_c + β1_c * covariate,
when fitted on control data only, would be equal to β0. And β0_t in
child ~ β0_t + β1_t * covariate, when fitted on treatment data only, would
equal to β0 + β1. The principle holds for multiple treatments. Here we fit
child ~ 1 + covariate
on every slice of data instead of fitting a large model on the whole data.
Args:
child: A pandas DataFrame. The result of the child Metric.
covariates: A pandas DataFrame. The result of the covariates Metric.
split_by: The split_by passed to self.compute_on().
Returns:
The adjusted values of the child (post metrics).
"""
from sklearn import linear_model # pylint: disable=g-import-not-at-top
# Don't use "-=". For multiindex it might go wrong. The reason is DataFrame
# has different implementations for __sub__ and __isub__. ___isub__ tries
# to reindex to update in place which sometimes lead to lots of NAs.
if split_by:
covariates = (
covariates - covariates.groupby(split_by, observed=True).mean()
)
else:
covariates = covariates - covariates.mean()
# Align child with covariates in case there is any missing slices.
covariates = covariates.reorder_levels(child.index.names)
aligned = pd.concat([child, covariates], axis=1)
len_child = child.shape[1]
lm = linear_model.LinearRegression()
# Define a custom Metric instead of using df.groupby().apply() because
# 1. It's faster. See the comments in Metric.compute_slices().
# 2. It ensures that the result is formatted correctly.
class Adjust(metrics.Metric):
"""Adjusts the value by fitting controlling for the covariates.
See the class doc for adjustment details. Essentially for every slice for
comparison, we fit a linear regression child = c + θ * covariate and use c
as the adjusted value for PercentChange computation later.
Because we center covariate first, when there is only one covariate, θ can
be computed as Covariance(child, covariate) / Var(covariate) and
c = avg(child) - θ * avg(covariate).
"""
def compute_slices(self, df, split_by: Optional[List[Text]] = None):
child = df.iloc[:, :len_child]
prefix = utils.get_unique_prefix(child)
df.columns = list(child.columns) + [
prefix + c for c in df.columns[len_child:]
]
covariate = df.iloc[:, len_child:]
if len(covariate.columns) > 1:
return super(Adjust, self).compute_slices(df, split_by)
adjusted = df.groupby(split_by, observed=True).mean()
covariate_col = covariate.columns[0]
covariate_adjusted = adjusted.iloc[:, -1]
for c in child:
theta = (
metrics.Cov(c, covariate_col) / metrics.Variance(covariate_col)
).compute_on(df, split_by, return_dataframe=False)
adjusted[c] = adjusted[c] - covariate_adjusted * theta
return adjusted.iloc[:, :-1]
def compute(self, df_slice):
child_slice = df_slice.iloc[:, :len_child]
covariate = df_slice.iloc[:, len_child:]
adjusted = [
lm.fit(covariate, child_slice[c]).intercept_ for c in child_slice
]
return pd.DataFrame([adjusted], columns=child_slice.columns)
return Adjust('').compute_on(aligned, split_by + self.extra_index)
def compute_through_sql(self, table, split_by, execute, mode):
if self.multiple_covariates:
return super(PrePostChange, self).compute_through_sql(
table, split_by, execute, mode
)
equiv, _ = utils.get_equivalent_metric(self)
res = self.compute_util_metric_on_sql(
equiv, table, split_by, execute, False, mode
)
# The column name got messed up when there is only one base metric because
# we squeeze the dataframe to a series.
if len(res.columns) == 1:
res.columns = [self.name_tmpl.format(self.children[0][0].name)]
return res
def compute_children_sql(self, table, split_by, execute, mode=None):
if not self.multiple_covariates:
raise NotImplementedError # shouldn't be called.
child = super(PrePostChange,
self).compute_children_sql(table, split_by, execute, mode)
covariates = child.iloc[:, -self.k_covariates:]
child = child.iloc[:, :-self.k_covariates]
return self.adjust_value(child, covariates, split_by)
def get_sql_and_with_clause(self, table, split_by, global_filter, indexes,
local_filter, with_data):
if self.multiple_covariates:
return super(PrePostChange, self).get_sql_and_with_clause(
table, split_by, global_filter, indexes, local_filter, with_data
)
equiv, _ = utils.get_equivalent_metric(self)
return equiv.get_sql_and_with_clause(
table, split_by, global_filter, indexes, local_filter, with_data
)
def get_change_raw_sql(
self, table, split_by, global_filter, indexes, local_filter, with_data
):
"""Generates PrePost-adjusted values for PercentChange computation.
This function generates subqueries like
WITH PrePostRaw AS (SELECT
split_by,
stratified_by,
condition_column,
child_metric,
covariate
FROM T
GROUP BY split_by, stratified_by, condition_column),
PrePostcovariateCentered AS (SELECT
split_by,
stratified_by,
condition_column,
child_metric,
covariate - AVG(covariate) OVER (PARTITION BY split_by) AS covariate
FROM PrePostRaw),
ChangeRaw AS (SELECT
split_by,
condition_column,
AVG(child_metric) - SAFE_DIVIDE(AVG(covariate) * COVAR_SAMP(child_metric,
covariate), VAR_SAMP(covariate)) AS child_metric
FROM PrePostcovariateCentered
GROUP BY split_by, condition_column)
Args:
table: The table we want to query from.
split_by: The columns that we use to split the data.
global_filter: The sql.Filters that can be applied to the whole Metric
tree.
indexes: The columns that we shouldn't apply any arithmetic operation.
local_filter: The sql.Filters that have been accumulated so far.
with_data: A global variable that contains all the WITH clauses we need.
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.
"""
if count_features(self.children[0][1]) > 1:
raise NotImplementedError
local_filter = (
sql.Filters(self.where_).add(local_filter).remove(global_filter)
)
all_split_by = sql.Columns(split_by).add(self.extra_split_by)
all_indexes = sql.Columns(split_by).add(self.extra_index)
child_sql, with_data = self.children[0].get_sql_and_with_clause(
table, all_split_by, global_filter, indexes, local_filter, with_data)
child_table = sql.Datasource(child_sql, 'PrePostRaw')
child_table_alias = with_data.merge(child_table)
split_by = split_by.aliases
all_split_by = all_split_by.aliases
all_indexes = all_indexes.aliases
cols = [
sql.Column(c.alias, alias=c.alias_raw)
for c in child_sql.all_columns[:-1]
]
covariate = child_sql.all_columns[-1].alias
covariate_mean = sql.Column(covariate, 'AVG({})', partition=split_by)
covariate_centered = (sql.Column(covariate) - covariate_mean).set_alias(
covariate
)
cols.append(covariate_centered)
covariate_centered_sql = sql.Sql(cols, child_table_alias)
covariate_centered_table = sql.Datasource(
covariate_centered_sql, 'PrePostcovariateCentered'
)
covariate_centered_table_alias = with_data.merge(covariate_centered_table)
to_adjust = []
for c in child_sql.all_columns[:-1]:
if c.alias in all_split_by:
continue
adjusted = metrics.Mean(c.alias) - metrics.Mean(covariate) * metrics.Cov(
c.alias, covariate
) / metrics.Variance(covariate)
to_adjust.append(adjusted.set_name(c.alias_raw))
return metrics.MetricList(to_adjust).get_sql_and_with_clause(
covariate_centered_table_alias,
all_indexes,