-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathpre_test_power.R
More file actions
2052 lines (1879 loc) · 77.7 KB
/
pre_test_power.R
File metadata and controls
2052 lines (1879 loc) · 77.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 (c) Meta Platforms, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Includes function MarketSelection, stochastic_market_selector, pvalueCalc,
# type_of_test, run_simulations, GeoLiftMarketSelection, GeoLiftPowerFinder,
# GeoLiftPower.search, NumberLocations, GeoLiftPower.
#' Market selection tool.
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' `MarketSelection` helps calculate the best markets based
#' on Dynamic Time Warping between the locations' time-series.
#'
#' @param data A data.frame containing the historical conversions by
#' geographic unit. It requires a "locations" column with the geo name,
#' a "Y" column with the outcome data (units), a time column with the indicator
#' of the time period (starting at 1), and covariates.
#' @param location_id Name of the location variable (String).
#' @param time_id Name of the time variable (String).
#' @param Y_id Name of the outcome variable (String).
#' @param dtw Emphasis on Dynamic Time Warping (DTW), dtw = 1 focuses exclusively
#' on this metric while dtw = 0 (default) relies on correlations only.
#' @param exclude_markets A list of markets or locations that won't be considered
#' for the test market selection, but will remain in the pool of controls. Empty
#' list by default.
#'
#' @return
#' Matrix of the best markets. The second to last columns show
#' the best to worst market matches for the location in the first
#' column.
#'
#' @export
MarketSelection <- function(data,
location_id = "location",
time_id = "time",
Y_id = "Y",
dtw = 0,
exclude_markets = c()) {
data <- data %>% dplyr::rename(Y = paste(Y_id), location = paste(location_id), time = paste(time_id))
data$location <- tolower(data$location)
astime <- seq(as.Date("2000/1/1"), by = "day", length.out = max(data$time))
data$astime <- astime[data$time]
exclude_markets <- tolower(exclude_markets)
# Check that the provided markets exist in the data.
if (!all(exclude_markets %in% tolower(unique(data$location)))) {
message(paste0(
"Error: One or more markets in exclude_markets were not",
" found in the data. Check the provided list and try again."
))
return(NULL)
}
# Exclude markets input by user by filter them out from the uploaded file data
if (length(exclude_markets) > 0) {
data <- data[!data$location %in% exclude_markets, ]
}
if (dtw == 0) {
best_controls <- MarketCorrelations(data)
} else {
# Find the best matches based on DTW
mm <- MarketMatching::best_matches(
data = data,
id_variable = "location",
date_variable = "astime",
matching_variable = "Y",
parallel = FALSE,
warping_limit = 1,
dtw_emphasis = dtw,
start_match_period = min(data$astime),
end_match_period = max(data$astime),
matches = length(unique(data$location)) - 1
)
# Create a matrix with each row being the raked best controls for each location
best_controls <- mm$BestMatches %>% tidyr::pivot_wider(
id_cols = location,
names_from = rank,
values_from = BestControl
)
}
best_controls <- as.matrix(best_controls)
colnames(best_controls) <- NULL
return(best_controls)
}
#' Stochastic Market Selector.
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' `stochastic_market_selector` selects the markets to be tested
#' by randomly sampling from the `similarity_matrix`.
#' It gets groups of 2 elements and samples one of them. It repeats
#' this process until the `treatment_size` is equal to the sample.
#'
#' @param treatment_size Is the amount of location units within the
#' treatment group.
#' @param similarity_matrix Matrix that sorts each location in terms
#' of descending correlation.
#' @param run_stochastic_process A logic flag indicating whether to select test
#' markets through random sampling of the the similarity matrix. Given that
#' interpolation biases may be relevant if the synthetic control matches
#' the characteristics of the test unit by averaging away large discrepancies
#' between the characteristics of the test and the units in the synthetic controls,
#' it is recommended to only use random sampling after making sure all units are
#' similar. This parameter is set by default to FALSE.
#'
#' @return
#' Returns a matrix of sampled combinations of treatments.
#' Each row represents a different treatment.
#'
#' @export
stochastic_market_selector <- function(treatment_size,
similarity_matrix,
run_stochastic_process = FALSE) {
if (!run_stochastic_process) {
message("\nDeterministic setup with ", treatment_size, " locations in treatment.")
sample_matrix <- matrix(similarity_matrix[, 1:treatment_size], ncol = treatment_size)
} else {
message("\nRandom setup with ", treatment_size, " locations in treatment.")
if (treatment_size > 0.5 * ncol(similarity_matrix)) {
stop(paste0(
"Treatment size (",
treatment_size,
") should be <= to half the amount of units: ",
ncol(similarity_matrix)
))
}
sample_size <- round(ncol(similarity_matrix) / treatment_size)
sample_matrix <- c()
i <- 0
while ((i / 2) < treatment_size) {
sampled_number <- sample(1:2, 1) + i
sample_matrix <- cbind(sample_matrix, similarity_matrix[, sampled_number])
i <- i + 2
}
}
for (row in 1:nrow(sample_matrix)) { # Sort rows.
sample_matrix[row, ] <- sort(sample_matrix[row, ])
}
return(matrix(unique(sample_matrix), ncol = treatment_size))
}
#' Decides type of statistical function being applied for Conformal
#' Inference.
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' `type_of_test` returns stat_func being used for GeoLiftPower;
#' GeoLiftPowerFinder & GeoLift.
#'
#' @param side_of_test A string indicating whether confidence will be determined
#' using a one sided or a two sided test.
#' \itemize{
#' \item{"two_sided":}{ The test statistic is the sum of all treatment effects, i.e. sum(abs(x)). Defualt.}
#' \item{"one_sided":}{ One-sided test against positive or negaative effects i.e.
#' If the effect being applied is negative, then defaults to -sum(x). H0: ES >= 0; HA: ES < 0.
#' If the effect being applied is positive, then defaults to sum(x). H0: ES <= 0; HA: ES > 0.}
#' }
#' @param alternative_hypothesis A string indicating what is the alternative hypothesis being tested. Defaults to NULL.
#' \itemize{
#' \item{"negative":}{ H0: ES >= 0; HA: ES < 0.}
#' \item{"positive":}{ H0: ES <= 0; HA: ES > 0.}
#' }
#' @return
#' Statistical function being used to sum ATT effects over all treatment periods.
#'
#' @export
type_of_test <- function(side_of_test = "two_sided", alternative_hypothesis = NULL) {
if (side_of_test == "two_sided") {
stat_func <- function(x) sum(abs(x))
} else if (side_of_test == "one_sided") {
if (is.null(alternative_hypothesis)) {
stop("If running a one sided test, please define alternative_hypotehsis parameter.
Either 'positive' or 'negative'")
}
if (tolower(alternative_hypothesis) == "negative") {
stat_func <- function(x) -sum(x)
} else if (tolower(alternative_hypothesis) == "positive") {
stat_func <- function(x) sum(x)
} else {
stop("Please define a valid alternative_hypothesis. Can be either {'Negative', 'Positive'}.")
}
} else {
stop("Please define a valid side_of_test. Can be either {'one_sided', 'two_sided'}.")
}
return(stat_func)
}
#' Calculate p-value for GeoLift.
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' `pvalueCalc` calculates the p-value for a GeoLift object.
#'
#' @param data A data.frame containing the historical conversions by
#' geographic unit. It requires a "locations" column with the geo name,
#' a "Y" column with the outcome data (units), a time column with the indicator
#' of the time period (starting at 1), and covariates.
#' @param sim Time simulation index.
#' @param max_time Treatment end index.
#' @param tp Time period index.
#' @param es Effect Size.
#' @param locations List of test locations.
#' @param cpic Cost Per Incremental Conversion.
#' @param X List of names of covariates.
#' @param type Method of inference used in the analysis.
#' pValue=Provides conformal inference to provide the aggregate
#' p-value for the null hypothesis of no effect from the intervention.
#' The Default type is pValue.
#' Imbalance=Uses the model's Scaled L2 Imbalance metric.
#' @param normalize A logic flag indicating whether to scale the outcome which is
#' useful to accelerate computing speed when the magnitude of the data is large. The
#' default is FALSE.
#' @param fixed_effects A logic flag indicating whether to include unit fixed
#' effects in the model. Set to FALSE by default.
#' @param stat_func Function to compute test statistic. NULL by default.
#' @param model A string indicating the outcome model used in the Augmented Synthetic
#' Control Method. Set to Generalized Synthetic Controls "none" by default.
#' @param conformal_type Type of conformal inference used. Can be either "iid" for Independent and identically
#' distributed or "block" for moving block permutations. Set to "iid" by default.
#' @param ns Number of resamples for "iid" permutations if `conformal_type = "iid`. Set to 1000 by default.
#'
#' @return
#' List that contains:
#' \itemize{
#' \item{"location":}{ Test locations.}
#' \item{"pvalue":}{ P Value.}
#' \item{"tp":}{ Time period index.}
#' \item{"es":}{ Effect Size used for the simulation.}
#' \item{"treatment_start_time":}{ Treatment start time for the simulation}
#' \item{"investment":}{ Estimated Investment}
#' \item{"ScaledL2Imbalance":}{ Scaled L2 Imbalance metric}
#' }
#'
#' @export
pvalueCalc <- function(data,
sim,
max_time,
tp,
es,
locations,
cpic,
X,
type = "pValue",
normalize = FALSE,
fixed_effects = FALSE,
stat_func = stat_func,
model = "none",
conformal_type = conformal_type,
ns = ns) {
treatment_start_time <- max_time - tp - sim + 2
treatment_end_time <- treatment_start_time + tp - 1
pre_test_duration <- treatment_start_time - 1
pre_treatment_start_time <- 1
if (normalize == TRUE) {
factor <- sd(as.matrix(data$Y))
data$Y <- data$Y / factor
}
data_aux <- fn_treatment(data,
locations = locations,
treatment_start_time,
treatment_end_time
)
data_aux$Y_inc <- data_aux$Y
data_aux$Y_inc[data_aux$D == 1] <- data_aux$Y_inc[data_aux$D == 1] * (1 + es)
if (length(X) == 0) {
ascm_obj <- augsynth::augsynth(Y_inc ~ D,
unit = location,
time = time,
data = data_aux,
t_int = treatment_start_time,
progfunc = model,
scm = T,
fixedeff = fixed_effects
)
} else if (length(X) > 0) {
fmla <- as.formula(paste(
"Y_inc ~ D |",
sapply(list(X),
paste,
collapse = "+"
)
))
ascm_obj <- augsynth::augsynth(fmla,
unit = location,
time = time,
data = data_aux,
t_int = treatment_start_time,
progfunc = model,
scm = T,
fixedeff = fixed_effects
)
}
ave_treatment_convs <- sum(ascm_obj$data$y[which(ascm_obj$data$trt == 1), ]) / sum(ascm_obj$data$trt == 1)
ave_pred_control_convs <- predict(ascm_obj)[treatment_start_time:treatment_end_time]
ave_incremental_convs <- ave_treatment_convs - sum(ave_pred_control_convs)
att_estimator <- ave_incremental_convs / tp
lift_estimator <- ave_incremental_convs / sum(ave_pred_control_convs)
if (type == "pValue") {
wide_data <- ascm_obj$data
new_wide_data <- wide_data
new_wide_data$X <- cbind(wide_data$X, wide_data$y)
new_wide_data$y <- matrix(1, nrow = nrow(wide_data$X), ncol = 1)
pVal <- augsynth:::compute_permute_pval(
wide_data = new_wide_data,
ascm = ascm_obj,
h0 = 0,
post_length = ncol(wide_data$y),
type = conformal_type,
q = 1,
ns = ns,
stat_func = stat_func
)
ScaledL2Imbalance <- ascm_obj$scaled_l2_imbalance
} else if (type == "Imbalance") {
pVal <- NA
ScaledL2Imbalance <- ascm_obj$scaled_l2_imbalance
} else {
message(paste0("ERROR: Please input a valid type: pValue or Imbalance."))
pVal <- NA
ScaledL2Imbalance <- NA
}
investment <- cpic * sum(data_aux$Y[data_aux$D == 1]) * (es)
return(
list(
locations = c(paste(locations, collapse = ", ")),
pvalue = pVal,
treatment_periods = tp,
effect_size = es,
treatment_start_time = treatment_start_time,
investment = investment,
scaled_l2_imbalance = ScaledL2Imbalance,
att_estimator = att_estimator,
lift_estimator = lift_estimator
)
)
}
#' Run simulations for treatment markets.
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' `run_simulations` computes simulations for each treatment market.
#'
#' @param data A data.frame containing the historical conversions by
#' geographic unit. It requires a "locations" column with the geo name,
#' a "Y" column with the outcome data (units), a time column with the indicator
#' of the time period (starting at 1), and covariates.
#' @param treatment_combinations A matrix of treatment locations.
#' Each row symbolizes a combination, each column one element of the combination.
#' @param treatment_durations Expected durations of the experiment.
#' @param effect_sizes A vector of effect sizes to simulate.
#' @param side_of_test A string indicating whether confidence will be determined
#' using a one sided or a two sided test.
#' \itemize{
#' \item{"two_sided":}{ The test statistic is the sum of all treatment effects, i.e. sum(abs(x)). Defualt.}
#' \item{"one_sided":}{ One-sided test against positive or negaative effects i.e.
#' If the effect being applied is negative, then defaults to -sum(x). H0: ES >= 0; HA: ES < 0.
#' If the effect being applied is positive, then defaults to sum(x). H0: ES <= 0; HA: ES > 0.}
#' }
#' @param conformal_type Type of conformal inference used. Can be either "iid" for Independent and identically
#' distributed or "block" for moving block permutations. Set to "iid" by default.
#' @param ns Number of resamples for "iid" permutations if `conformal_type = "iid`. Set to 1000 by default.
#' @param lookback_window A number indicating how far back in time the simulations
#' for the power analysis should go. For instance, a value equal to 5 will simulate
#' power for the last five possible tests. By default lookback_window = 1 which
#' will only execute the most recent test based on the data.
#' @param cpic Number indicating the Cost Per Incremental Conversion.
#' @param parallel A logic flag indicating whether to use parallel computing to
#' speed up calculations. Set to TRUE by default.
#' @param ProgressBar A logic flag indicating whether to display a progress bar
#' to track progress. Set to FALSE by default.
#' @param X List of names of covariates.
#' @param normalize A logic flag indicating whether to scale the outcome which is
#' useful to accelerate computing speed when the magnitude of the data is large. The
#' default is FALSE.
#' @param fixed_effects A logic flag indicating whether to include unit fixed
#' effects in the model. Set to TRUE by default.
#' @param model A string indicating the outcome model used to augment the Augmented
#' Synthetic Control Method. Augmentation through a prognostic function can improve
#' fit and reduce L2 imbalance metrics.
#' \itemize{
#' \item{"None":}{ ASCM is not augmented by a prognostic function. Defualt.}
#' \item{"Ridge":}{ Augments with a Ridge regression. Recommended to improve fit
#' for smaller panels (less than 40 locations and 100 time-stamps.))}
#' \item{"GSYN":}{ Augments with a Generalized Synthetic Control Method. Recommended
#' to improve fit for larger panels (more than 40 locations and 100
#' time-stamps. }
#' }
#'
#' @return
#' DataFrame that contains:
#' \itemize{
#' \item{"location":}{ Test locations.}
#' \item{"pvalue":}{ P Value.}
#' \item{"tp":}{ Time period index.}
#' \item{"es":}{ Effect Size used for the simulation.}
#' \item{"treatment_start_time":}{ Treatment start time for the simulation}
#' \item{"investment":}{ Estimated Investment}
#' \item{"ScaledL2Imbalance":}{ Scaled L2 Imbalance metric}
#' \item{"att_estimator":}{ Detected Average Treatment on the Treated}
#' \item{"detected_lift":}{ Detected % Lift by GeoLift for an effect size}
#' }
#'
#' @export
run_simulations <- function(data,
treatment_combinations,
treatment_durations,
effect_sizes = 0,
side_of_test = "two_sided",
conformal_type = conformal_type,
ns = ns,
lookback_window = 1,
parallel = TRUE,
ProgressBar = FALSE,
cpic = 0,
X = c(),
normalize = FALSE,
fixed_effects = TRUE,
model = "none") {
`%parallel_connector%` <- ifelse(parallel, foreach::`%dopar%`, foreach::`%do%`)
results <- data.frame(matrix(ncol = 10, nrow = 0))
colnames(results) <- c(
"location",
"pvalue",
"duration",
"EffectSize",
"treatment_start",
"Investment",
"cpic",
"ScaledL2Imbalance",
"att_estimator",
"detected_lift"
)
param_combination <- expand.grid(
effect_sizes,
treatment_durations,
1:lookback_window,
1:nrow(as.matrix(treatment_combinations))
)
colnames(param_combination) <- c(
"effect_size",
"treatment_duration",
"lookback_window",
"treatment_combination_row"
)
combine_function <- function(iterator) {
pb <- txtProgressBar(min = 1, max = iterator - 1, style = 3)
count <- 0
function(...) {
count <<- count + length(list(...)) - 1
setTxtProgressBar(pb, count)
flush.console()
cbind(...) # this can feed into .combine option of foreach
}
}
simulation_results <- foreach(
effect_size = param_combination$effect_size,
treatment_duration = param_combination$treatment_duration,
sim = param_combination$lookback_window,
test = param_combination$treatment_combination_row,
.combine = ifelse(
ProgressBar,
combine_function(nrow(param_combination)),
cbind
),
.errorhandling = "stop",
.verbose = FALSE
) %parallel_connector% {
suppressMessages(pvalueCalc(
data = data,
sim = sim,
max_time = max(data$time),
tp = treatment_duration,
es = effect_size,
locations = as.list(as.matrix(treatment_combinations)[test, ]),
cpic = cpic,
X,
type = "pValue",
normalize = normalize,
fixed_effects = fixed_effects,
model = model,
stat_func = type_of_test(
side_of_test = side_of_test,
alternative_hypothesis = ifelse(
effect_size > 0, "positive", "negative"
)
),
conformal_type = conformal_type,
ns = ns
))
}
if (is.null(dim(simulation_results))) {
simulation_results <- matrix(
simulation_results,
nrow = length(names(simulation_results))
)
}
for (i in 1:ncol(simulation_results)) {
results <- rbind(
results,
data.frame(
location = simulation_results[[1, i]],
pvalue = as.numeric(simulation_results[[2, i]]),
duration = as.numeric(simulation_results[[3, i]]),
EffectSize = as.numeric(simulation_results[[4, i]]),
treatment_start = as.numeric(simulation_results[[5, i]]),
Investment = as.numeric(simulation_results[[6, i]]),
cpic = cpic,
ScaledL2Imbalance = as.numeric(simulation_results[[7, i]]),
att_estimator = as.numeric(simulation_results[[8, i]]),
detected_lift = as.numeric(simulation_results[[9, i]])
)
)
}
return(results)
}
#' Power calculations for unknown test market locations, number of
#' test markets, and test duration.
#'
#' @description
#' `r lifecycle::badge("superseded")`
#'
#' Development on `GeoLiftPowerFinder()` is complete.
#' We recommend switching to `GeoLiftMarketSelection()`
#' for new code, which is easier to use, more featureful,
#' and still under active development.
#'
#' `GeoLiftPowerFinder` provides power calculations for unknown
#' test markets, number of test locations, and test duration.
#'
#' @param data A data.frame containing the historical conversions by
#' geographic unit. It requires a "locations" column with the geo name,
#' a "Y" column with the outcome data (units), a time column with the indicator
#' of the time period (starting at 1), and covariates.
#' @param treatment_periods List of treatment periods to calculate power for.
#' @param N List of number of test markets to calculate power for.
#' @param X List of names of covariates.
#' @param Y_id Name of the outcome variable (String).
#' @param location_id Name of the location variable (String).
#' @param time_id Name of the time variable (String).
#' @param effect_size A vector of effect sizes to test by default a
#' sequence between 0 - 25 percent in 5 percent increments: seq(0,0.25,0.05).
#' Make sure that the sequence includes zero.
#' @param top_results Number of results to display.
#' @param alpha Significance Level. By default 0.1.
#' @param normalize A logic flag indicating whether to scale the outcome which is
#' useful to accelerate computing speed when the magnitude of the data is large. The
#' default is FALSE.
#' @param model A string indicating the outcome model used to augment the Augmented
#' Synthetic Control Method. Augmentation through a prognostic function can improve
#' fit and reduce L2 imbalance metrics.
#' \itemize{
#' \item{"None":}{ ASCM is not augmented by a prognostic function. Defualt.}
#' \item{"Ridge":}{ Augments with a Ridge regression. Recommended to improve fit
#' for smaller panels (less than 40 locations and 100 time-stamps.))}
#' \item{"GSYN":}{ Augments with a Generalized Synthetic Control Method. Recommended
#' to improve fit for larger panels (more than 40 locations and 100
#' time-stamps. }
#' }
#' @param fixed_effects A logic flag indicating whether to include unit fixed
#' effects in the model. Set to TRUE by default.
#' @param dtw Emphasis on Dynamic Time Warping (DTW), dtw = 1 focuses exclusively
#' on this metric while dtw = 0 (default) relies on correlations only.
#' @param ProgressBar A logic flag indicating whether to display a progress bar
#' to track progress. Set to FALSE by default.
#' @param plot_best A logic flag indicating whether to plot the best 4 tests for
#' each treatment length. Set to FALSE by default.
#' @param run_stochastic_process A logic flag indicating whether to select test
#' markets through random sampling of the the similarity matrix. Given that
#' interpolation biases may be relevant if the synthetic control matches
#' the characteristics of the test unit by averaging away large discrepancies
#' between the characteristics of the test and the units in the synthetic controls,
#' it is recommended to only use random sampling after making sure all units are
#' similar. This parameter is set by default to FALSE.
#' @param parallel A logic flag indicating whether to use parallel computing to
#' speed up calculations. Set to TRUE by default.
#' @param parallel_setup A string indicating parallel workers set-up.
#' Set to "sequential" by default.
#' @param side_of_test A string indicating whether confidence will be determined
#' using a one sided or a two sided test.
#' \itemize{
#' \item{"two_sided":}{ The test statistic is the sum of all treatment effects, i.e. sum(abs(x)). Defualt.}
#' \item{"one_sided":}{ One-sided test against positive or negaative effects i.e.
#' If the effect being applied is negative, then defaults to -sum(x). H0: ES >= 0; HA: ES < 0.
#' If the effect being applied is positive, then defaults to sum(x). H0: ES <= 0; HA: ES > 0.}
#' }
#' @param import_augsynth_from Points to where the augsynth package
#' should be imported from to send to the nodes.
#' @param import_tidyr_from Points to where the tidyr package
#' should be imported from to send to the nodes.
#'
#' @return
#' Data frame with the ordered list of best locations and their
#' average power.
#'
#' @export
GeoLiftPowerFinder <- function(data,
treatment_periods,
N = 1,
X = c(),
Y_id = "Y",
location_id = "location",
time_id = "time",
effect_size = seq(0, 0.25, 0.05),
top_results = 5,
alpha = 0.1,
normalize = FALSE,
model = "none",
fixed_effects = TRUE,
dtw = 0,
ProgressBar = FALSE,
plot_best = FALSE,
run_stochastic_process = FALSE,
parallel = TRUE,
parallel_setup = "sequential",
side_of_test = "two_sided",
import_augsynth_from = "library(augsynth)",
import_tidyr_from = "library(tidyr)") {
if (parallel == TRUE) {
cl <- build_cluster(
parallel_setup = parallel_setup,
import_augsynth_from = import_augsynth_from,
import_tidyr_from = import_tidyr_from
)
}
# Part 1: Treatment and pre-treatment periods
data <- data %>% dplyr::rename(Y = paste(Y_id), location = paste(location_id), time = paste(time_id))
max_time <- max(data$time)
data$location <- tolower(data$location)
# Small Pre-treatment Periods
if (max_time / max(treatment_periods) < 4) {
message(paste0("Caution: Small pre-treatment period!.
\nIt's recommended to have at least 4x pre-treatment periods for each treatment period.\n"))
}
results <- data.frame(matrix(ncol = 6, nrow = 0))
colnames(results) <- c(
"location",
"pvalue",
"duration",
"EffectSize",
"treatment_start",
"ScaledL2Imbalance"
)
BestMarkets <- MarketSelection(data,
location_id = "location",
time_id = "time",
Y_id = "Y",
dtw = dtw
)
N <- limit_test_markets(BestMarkets, N, run_stochastic_process)
# Aggregated Y Per Location
AggYperLoc <- data %>%
dplyr::group_by(location) %>%
dplyr::summarize(Total_Y = sum(Y))
num_sim <- length(N) * length(treatment_periods) * length(effect_size)
if (ProgressBar == TRUE) {
pb <- progress::progress_bar$new(
format = " Running Simulations [:bar] :percent",
total = num_sim,
clear = FALSE,
width = 60
)
} else {
pb <- NULL
}
message("Finding the best markets for your experiment.")
for (n in N) {
BestMarkets_aux <- stochastic_market_selector(
n,
BestMarkets,
run_stochastic_process = run_stochastic_process
)
partial_results <- run_simulations(
data = data,
treatment_combinations = BestMarkets_aux,
treatment_durations = treatment_periods,
effect_sizes = effect_size,
side_of_test = side_of_test,
lookback_window = 1,
parallel = parallel,
ProgressBar = ProgressBar,
cpic = 0,
X = X,
normalize = normalize,
fixed_effects = fixed_effects,
model = model
)
results <- rbind(results, partial_results)
}
if (parallel == TRUE) {
parallel::stopCluster(cl)
}
# Sort Locations alphabetically
results$location <- strsplit(stringr::str_replace_all(results$location, ", ", ","), split = ",")
results$location <- lapply(results$location, sort)
results$location <- lapply(results$location, function(x) paste(x, collapse = ", "))
results$location <- unlist(results$location)
results <- results %>%
dplyr::mutate(significant = ifelse(pvalue < alpha, 1, 0)) %>%
dplyr::filter(significant > 0) %>%
dplyr::distinct()
resultsM <- results %>%
dplyr::filter(EffectSize != 0) %>%
dplyr::group_by(location, duration) %>%
dplyr::slice(which.min(abs(EffectSize)))
# Add Percent of Y in test markets
resultsM$ProportionTotal_Y <- 1
resultsM$Locs <- strsplit(stringr::str_replace_all(resultsM$location, ", ", ","), split = ",")
for (row in 1:nrow(resultsM)) {
resultsM$ProportionTotal_Y[row] <- as.numeric(AggYperLoc %>%
dplyr::filter(location %in% resultsM$Locs[[row]]) %>%
dplyr::summarize(total = sum(Total_Y))) /
sum(AggYperLoc$Total_Y)
}
# Remove any duplicates
resultsM <- resultsM %>%
dplyr::group_by(location, duration) %>%
dplyr::slice_min(order_by = pvalue, n = 1)
resultsM$abs_lift_in_zero <- round(abs(resultsM$detected_lift - resultsM$EffectSize), 3)
resultsM <- as.data.frame(resultsM) %>%
dplyr::mutate(
rank_mde = dplyr::dense_rank(abs(EffectSize)),
rank_pvalue = dplyr::dense_rank(pvalue),
rank_abszero = dplyr::dense_rank(abs_lift_in_zero)
)
resultsM$rank <- rank(
rowMeans(resultsM[, c("rank_mde", "rank_pvalue", "rank_abszero")]),
ties.method = "min"
)
resultsM <- resultsM %>%
dplyr::mutate(
rank_mde = NULL,
rank_pvalue = NULL,
rank_abszero = NULL,
Locs = NULL,
treatment_start = NULL,
significant = NULL
) %>%
dplyr::arrange(rank)
class(results) <- c("GeoLiftPowerFinder", class(resultsM))
if (top_results > nrow(resultsM)) {
top_results <- nrow(resultsM)
}
if (plot_best == TRUE) {
message("Calculating GeoLifts to plot top results.")
for (tp in treatment_periods) {
BestResults <- resultsM %>%
dplyr::filter(duration == tp) %>%
dplyr::arrange(rank)
bestmodels <- list()
for (i in 1:4) {
locs_aux <- unlist(strsplit(stringr::str_replace_all(BestResults$location[i], ", ", ","), split = ","))
data_lifted <- data
data_lifted$Y[data_lifted$location %in% locs_aux &
data_lifted$time >= max_time - tp + 1] <-
data_lifted$Y[data_lifted$location %in% locs_aux &
data_lifted$time >= max_time - tp + 1] * (1 + BestResults$EffectSize[i])
bestmodels[[i]] <- suppressMessages(GeoLift::GeoLift(
Y_id = "Y",
time_id = "time",
location_id = "location",
data = data_lifted,
locations = locs_aux,
treatment_start_time = max_time - tp + 1,
treatment_end_time = max_time,
model = model,
fixed_effects = fixed_effects
))
}
suppressMessages(gridExtra::grid.arrange(
plot(bestmodels[[1]], notes = paste(
"locations:", BestResults$location[1],
"\n Treatment Periods:", tp, "\n Minimum Detectable Effect: ",
BestResults$EffectSize[1],
"\n Proportion Total Y: ", 100 * round(BestResults$ProportionTotal_Y[1], 3), "%"
)),
plot(bestmodels[[2]], notes = paste(
"locations:", BestResults$location[2],
"\n Treatment Periods:", tp, "\n Minimum Detectable Effect: ",
BestResults$EffectSize[2],
"\n Proportion Total Y: ", 100 * round(BestResults$ProportionTotal_Y[2], 3), "%"
)),
plot(bestmodels[[3]], notes = paste(
"locations:", BestResults$location[3],
"\n Treatment Periods:", tp, "\n Minimum Detectable Effect: ",
BestResults$EffectSize[3],
"\n Proportion Total Y: ", 100 * round(BestResults$ProportionTotal_Y[3], 3), "%"
)),
plot(bestmodels[[4]], notes = paste(
"locations:", BestResults$location[4],
"\n Treatment Periods:", tp, "\n Minimum Detectable Effect: ",
BestResults$EffectSize[4],
"\n Proportion Total Y: ", 100 * round(BestResults$ProportionTotal_Y[4], 3), "%"
)),
ncol = 2
))
}
}
resultsM <- resultsM %>% dplyr::rename(MinDetectableEffect = EffectSize)
return(resultsM)
}
#' Power calculations for unknown test market locations, number of
#' test markets, and test duration.
#'
#' @description
#' `r lifecycle::badge("superseded")`
#'
#' Development on `GeoLiftPower.search()` is complete.
#' We recommend switching to `GeoLiftMarketSelection()`
#' for new code, which is easier to use, more featureful,
#' and still under active development.
#'
#' `GeoLiftPower.search` provides power calculations for unknown
#' test markets, number of test locations, and test duration.
#'
#' @param data A data.frame containing the historical conversions by
#' geographic unit. It requires a "locations" column with the geo name,
#' a "Y" column with the outcome data (units), a time column with the indicator
#' of the time period (starting at 1), and covariates.
#' @param treatment_periods List of treatment periods to calculate power for.
#' @param N List of number of test markets to calculate power for.
#' @param lookback_window A number indicating how far back in time the simulations
#' for the power analysis should go. For instance, a value equal to 5 will simulate
#' power for the last five possible tests. By default lookback_window = 1 which
#' will only execute the most recent test based on the data.
#' @param X List of names of covariates.
#' @param Y_id Name of the outcome variable (String).
#' @param location_id Name of the location variable (String).
#' @param time_id Name of the time variable (String).
#' @param top_results Number of results to display.
#' @param alpha Significance Level. By default 0.1.
#' @param type Method of inference used in the analysis.
#' pValue=Provides conformal inference to provide the aggregate
#' p-value for the null hypothesis of no effect from the intervention.
#' The Default type is pValue.
#' Imbalance=Uses the model's Scaled L2 Imbalance metric.
#' @param normalize A logic flag indicating whether to scale the outcome which is
#' useful to accelerate computing speed when the magnitude of the data is large. The
#' default is FALSE.
#' @param model A string indicating the outcome model used to augment the Augmented
#' Synthetic Control Method. Augmentation through a prognostic function can improve
#' fit and reduce L2 imbalance metrics.
#' \itemize{
#' \item{"None":}{ ASCM is not augmented by a prognostic function. Defualt.}
#' \item{"Ridge":}{ Augments with a Ridge regression. Recommended to improve fit
#' for smaller panels (less than 40 locations and 100 time-stamps.))}
#' \item{"GSYN":}{ Augments with a Generalized Synthetic Control Method. Recommended
#' to improve fit for larger panels (more than 40 locations and 100
#' time-stamps. }
#' }
#' @param fixed_effects A logic flag indicating whether to include unit fixed
#' effects in the model. Set to TRUE by default.
#' @param stat_func Function to compute test statistic. NULL by default.
#' @param dtw Emphasis on Dynamic Time Warping (DTW), dtw = 1 focuses exclusively
#' on this metric while dtw = 0 (default) relies on correlations only.
#' @param ProgressBar A logic flag indicating whether to display a progress bar
#' to track progress. Set to FALSE by default.
#' @param run_stochastic_process A logic flag indicating whether to select test
#' markets through random sampling of the the similarity matrix. Given that
#' interpolation biases may be relevant if the synthetic control matches
#' the characteristics of the test unit by averaging away large discrepancies
#' between the characteristics of the test and the units in the synthetic controls,
#' it is recommended to only use random sampling after making sure all units are
#' similar. This parameter is set by default to FALSE.
#' @param parallel A logic flag indicating whether to use parallel computing to
#' speed up calculations. Set to TRUE by default.
#' @param parallel_setup A string indicating parallel workers set-up.
#' Set to "sequential" by default.
#' @param import_augsynth_from Points to where the augsynth package
#' should be imported from to send to the nodes.
#' @param import_tidyr_from Points to where the tidyr package
#' should be imported from to send to the nodes.
#'
#' @return
#' Data frame with the ordered list of best locations and their
#' average power.
#'
#' @export
GeoLiftPower.search <- function(data,
treatment_periods,
N = 1,
lookback_window = 1,
X = c(),
Y_id = "Y",
location_id = "location",
time_id = "time",
top_results = 5,
alpha = 0.1,
type = "pValue",
normalize = FALSE,
model = "none",
fixed_effects = TRUE,
stat_func = NULL,
dtw = 0,
ProgressBar = FALSE,
run_stochastic_process = FALSE,
parallel = TRUE,
parallel_setup = "sequential",
import_augsynth_from = "library(augsynth)",
import_tidyr_from = "library(tidyr)") {
if (parallel == TRUE) {
cl <- build_cluster(
parallel_setup = parallel_setup,
import_augsynth_from = import_augsynth_from,
import_tidyr_from = import_tidyr_from
)
}
# Part 1: Treatment and pre-treatment periods
data <- data %>% dplyr::rename(Y = paste(Y_id), location = paste(location_id), time = paste(time_id))
max_time <- max(data$time)
data$location <- tolower(data$location)
# Small Pre-treatment Periods
if (max_time / max(treatment_periods) < 4) {
message(paste0("Caution: Small pre-treatment period!.
\nIt's recommended to have at least 4x pre-treatment periods for each treatment period.\n"))
}
results <- data.frame(matrix(ncol = 5, nrow = 0))
colnames(results) <- c(
"location",
"pvalue",
"duration",
"treatment_start",
"ScaledL2Imbalance"
)
BestMarkets <- MarketSelection(data,
location_id = "location",
time_id = "time",
Y_id = "Y",
dtw = dtw
)