Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allocator's new scenario for ROAS target #648

Merged
merged 22 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
3eac6af
feat: added scenario hit target roas
gufengzhou Mar 10, 2023
beb15bc
feat: adapted onepager for target roas
gufengzhou Mar 10, 2023
550c66d
feat: no need to define select_model when there's only one
laresbernardo Mar 10, 2023
4b8d6a3
docs update + simpler scenarios: max_response and target_roas
laresbernardo Mar 10, 2023
7b0df9b
feat: target cpa added into scenario
gufengzhou Mar 13, 2023
ffa7415
fix: update scenario for backwards compatibility
gufengzhou Mar 13, 2023
fd63dcb
docs: updates demo and params - 3.10.1 [dev]
laresbernardo Mar 13, 2023
9ce0321
fix: error when both CPA scenarios are same
gufengzhou Mar 14, 2023
00d781a
doc: update demo.R
gufengzhou Mar 14, 2023
d3a570b
fix: channel constraint NULL error
gufengzhou Mar 15, 2023
34d8b7d
recode: finetune plot labels
gufengzhou Mar 16, 2023
9a600c2
fix: pass export parameter correctly on allocator
laresbernardo Mar 17, 2023
49113a4
recode: finetune onepager & default target_value_ext
gufengzhou Mar 20, 2023
90f24cb
fix: NaN values set as 0
laresbernardo Mar 21, 2023
b748204
site: yarn upgrade
laresbernardo Mar 21, 2023
8288d26
docs: get rid of metric_ds => date_range
laresbernardo Mar 21, 2023
67cf946
recode: styler applied
laresbernardo Mar 21, 2023
8b76ee8
docs: export str_to_title and case_when
laresbernardo Mar 22, 2023
60780cc
recode: update demo.R
gufengzhou Mar 22, 2023
fd8d7ad
doc: remove old and redundant guide
gufengzhou Mar 22, 2023
b9eb87e
docs: fixed % escape + decomp_plot()
laresbernardo Mar 22, 2023
c8d87c1
Merge branch 'hit_roas_target' of https://github.com/facebookexperime…
laresbernardo Mar 22, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion R/DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: Robyn
Type: Package
Title: Semi-Automated Marketing Mix Modeling (MMM) from Meta Marketing Science
Version: 3.10.0.9000
Version: 3.10.1.9000
Authors@R: c(
person("Gufeng", "Zhou", , "[email protected]", c("aut")),
person("Leonel", "Sentana", , "[email protected]", c("aut")),
Expand Down
297 changes: 226 additions & 71 deletions R/R/allocator.R

Large diffs are not rendered by default.

39 changes: 16 additions & 23 deletions R/R/checks.R
Original file line number Diff line number Diff line change
Expand Up @@ -780,8 +780,6 @@ check_class <- function(x, object) {

check_allocator_constrains <- function(low, upr) {
max_length <- max(c(length(low), length(upr)))
if (length(low) == 1) low <- rep(low, max_length)
if (length(upr) == 1) upr <- rep(upr, max_length)
if (any(low < 0)) {
stop("Inputs 'channel_constr_low' must be >= 0")
}
Expand All @@ -802,35 +800,30 @@ check_allocator <- function(OutputCollect, select_model, paid_media_spends, scen
paste(OutputCollect$allSolutions, collapse = ", ")
)
}
if (any(channel_constr_up > 5)) {
warning("Inputs 'channel_constr_up' > 5 might cause unrealistic allocation")
}
if ("max_response_expected_spend" %in% scenario) {
stop(paste(
"Scenario 'max_response_expected_spend' has been deprecated.",
"Use scenario = 'max_historical_response' and new 'total_budget' parameter instead."
))
}
opts <- "max_historical_response" # Deprecated: max_response_expected_spend
if ("max_historical_response" %in% scenario) scenario <- "max_response"
opts <- c("max_response", "target_efficiency") # Deprecated: max_response_expected_spend
if (!(scenario %in% opts)) {
stop("Input 'scenario' must be one of: ", paste(opts, collapse = ", "))
}
if (length(channel_constr_low) != 1 && length(channel_constr_low) != length(paid_media_spends)) {
stop(paste(
"Input 'channel_constr_low' have to contain either only 1",
"value or have same length as 'InputCollect$paid_media_spends':", length(paid_media_spends)
))
}
if (length(channel_constr_up) != 1 && length(channel_constr_up) != length(paid_media_spends)) {
stop(paste(
"Input 'channel_constr_up' have to contain either only 1",
"value or have same length as 'InputCollect$paid_media_spends':", length(paid_media_spends)
))
if (!(scenario == "target_efficiency" & is.null(channel_constr_low) & is.null(channel_constr_up))) {
if (length(channel_constr_low) != 1 && length(channel_constr_low) != length(paid_media_spends)) {
stop(paste(
"Input 'channel_constr_low' have to contain either only 1",
"value or have same length as 'InputCollect$paid_media_spends':", length(paid_media_spends)
))
}
if (length(channel_constr_up) != 1 && length(channel_constr_up) != length(paid_media_spends)) {
stop(paste(
"Input 'channel_constr_up' have to contain either only 1",
"value or have same length as 'InputCollect$paid_media_spends':", length(paid_media_spends)
))
}
}
opts <- c("eq", "ineq")
if (!(constr_mode %in% opts)) {
stop("Input 'constr_mode' must be one of: ", paste(opts, collapse = ", "))
}
return(scenario)
}

check_metric_type <- function(metric_name, paid_media_spends, paid_media_vars, exposure_vars, organic_vars) {
Expand Down
13 changes: 12 additions & 1 deletion R/R/json.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#' @param select_model Character. Which model ID do you want to export
#' into the JSON file?
#' @param dir Character. Existing directory to export JSON file to.
#' @param all_sol_json Dataframe. Add all pareto solutions to json.
#' @param ... Additional parameters.
#' @examples
#' \dontrun{
Expand All @@ -32,7 +33,9 @@ robyn_write <- function(InputCollect,
select_model = NULL,
dir = OutputCollect$plot_folder,
export = TRUE,
quiet = FALSE, ...) {
quiet = FALSE,
all_sol_json = NULL,
...) {
# Checks
stopifnot(inherits(InputCollect, "robyn_inputs"))
if (!is.null(OutputCollect)) {
Expand Down Expand Up @@ -91,6 +94,14 @@ robyn_write <- function(InputCollect,
attr(ret, "json_file") <- filename
if (export) {
if (!quiet) message(sprintf(">> Exported model %s as %s", select_model, filename))
if (!is.null(all_sol_json)) {
all_c <- unique(all_sol_json$cluster)
all_sol_json <- lapply(all_c, function(x) {
(all_sol_json %>% filter(.data$cluster == x))$solID
})
names(all_sol_json) <- paste0("cluster", all_c)
ret[["all_sols"]] <- all_sol_json
}
write_json(ret, filename, pretty = TRUE)
}
return(invisible(ret))
Expand Down
12 changes: 11 additions & 1 deletion R/R/outputs.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#' to "all" will output all iterations as csv. Set NULL to skip exports into CSVs.
#' @param ui Boolean. Save additional outputs for UI usage. List outcome.
#' @param export Boolean. Export outcomes into local files?
#' @param all_sol_json Logical. Add all solutions to json export.
#' @param quiet Boolean. Keep messages off?
#' @param refresh Boolean. Refresh mode
#' @param ... Additional parameters passed to \code{robyn_clusters()}
Expand All @@ -47,6 +48,7 @@ robyn_outputs <- function(InputCollect, OutputModels,
clusters = TRUE,
select_model = "clusters",
ui = FALSE, export = TRUE,
all_sol_json = FALSE,
quiet = FALSE,
refresh = FALSE, ...) {
if (is.null(plot_folder)) plot_folder <- getwd()
Expand Down Expand Up @@ -229,7 +231,15 @@ robyn_outputs <- function(InputCollect, OutputModels,
)
}

robyn_write(InputCollect, dir = OutputCollect$plot_folder, quiet = quiet)
if (all_sol_json) {
all_sol_json <- OutputCollect$resultHypParam %>%
filter(!is.na(.data$cluster)) %>%
select(c("solID", "cluster", "top_sol")) %>%
arrange(.data$cluster, -.data$top_sol, .data$solID)
} else {
all_sol_json <- NULL
}
robyn_write(InputCollect, dir = OutputCollect$plot_folder, quiet = quiet, all_sol_json = all_sol_json)

# For internal use -> UI Code
if (ui && plot_pareto) OutputCollect$UI$pareto_onepagers <- pareto_onepagers
Expand Down
2 changes: 1 addition & 1 deletion R/R/pareto.R
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ robyn_pareto <- function(InputCollect, OutputModels,

if (!quiet) {
message(sprintf(
">>> Calculating response curves for all models' variables (%s)...",
">>> Calculating response curves for all models' media variables (%s)...",
nrow(decompSpendDistPar)
))
}
Expand Down
69 changes: 50 additions & 19 deletions R/R/plots.R
Original file line number Diff line number Diff line change
Expand Up @@ -700,12 +700,16 @@ allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_mo
message("NOTE: Given the upper/lower constrains, the total budget can't be fully allocated (^)")
}
}
levs1 <- c("Initial", "Bounded", paste0("Bounded x", bound_mult))
levs2 <- c(
"Initial",
paste0("Bounded", ifelse(optm_topped_bounded, "^", "")),
paste0("Bounded", ifelse(optm_topped_unbounded, "^", ""), " x", bound_mult)
)
levs1 <- eval_list$levs1
if (scenario == "max_response") {
levs2 <- c(
"Initial",
paste0("Bounded", ifelse(optm_topped_bounded, "^", "")),
paste0("Bounded", ifelse(optm_topped_unbounded, "^", ""), " x", bound_mult)
)
} else if (scenario == "target_efficiency") {
levs2 <- levs1
}

resp_metric <- data.frame(
type = factor(levs1, levels = levs1),
Expand All @@ -726,7 +730,7 @@ allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_mo
pivot_longer(cols = !"type") %>%
left_join(resp_metric, "type") %>%
mutate(
name = factor(.data$name, levels = c("spend", "response")),
name = factor(paste("total", .data$name), levels = c("total spend", "total response")),
name_label = factor(
paste(.data$type, .data$name, sep = "\n"),
levels = paste(.data$type, .data$name, sep = "\n")
Expand All @@ -746,7 +750,7 @@ allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_mo
df_roi$labs <- factor(rep(labs, each = 2), levels = labs)

outputs[["p1"]] <- p1 <- df_roi %>%
ggplot(aes(x = .data$name_label, y = .data$value, fill = .data$type)) +
ggplot(aes(x = .data$name, y = .data$value, fill = .data$type)) +
facet_grid(. ~ .data$labs, scales = "free") +
scale_fill_manual(values = c("grey", "steelblue", "darkgoldenrod4")) +
geom_bar(stat = "identity", width = 0.6, alpha = 0.7) +
Expand Down Expand Up @@ -780,8 +784,19 @@ allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_mo
left_join(
dt_optimOut %>%
mutate(
channel = as.factor(.data$channels), Initial = .data$initRoiUnit,
Bounded = .data$optmRoiUnit, Unbounded = .data$optmRoiUnitUnbound
channel = as.factor(.data$channels),
Initial = dplyr::case_when(
metric == "ROAS" ~ .data$initRoiUnit,
TRUE ~ .data$initCpaUnit
),
Bounded = dplyr::case_when(
metric == "ROAS" ~ .data$optmRoiUnit,
TRUE ~ .data$optmCpaUnit
),
Unbounded = dplyr::case_when(
metric == "ROAS" ~ .data$optmRoiUnitUnbound,
TRUE ~ .data$optmCpaUnitUnbound
)
) %>%
select(.data$channel, .data$Initial, .data$Bounded, .data$Unbounded) %>%
`colnames<-`(c("channel", levs1)) %>%
Expand Down Expand Up @@ -846,25 +861,34 @@ allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_mo
),
values = round(.data$values, 4),
# Deal with extreme cases divided by almost 0
values = ifelse((.data$values > 1e15 & .data$metric == "ROAS"), 0, .data$values),
values_label = dplyr::case_when(
values = ifelse((.data$values > 1e15 & .data$metric %in% c("ROAS", "mROAS")), 0, .data$values),
values_label = suppressWarnings(dplyr::case_when(
laresbernardo marked this conversation as resolved.
Show resolved Hide resolved
.data$metric %in% c("ROAS", "mROAS") ~ paste0("x", round(.data$values, 2)),
.data$metric %in% c("CPA", "mCPA") ~ formatNum(100 * .data$values, 2, abbr = TRUE, pre = "$"),
.data$metric %in% c("CPA", "mCPA") ~ formatNum(.data$values, 2, abbr = TRUE, pre = "$"),
TRUE ~ paste0(round(100 * .data$values, 1), "%")
),
)),
# Better fill scale colours
values_label = ifelse(grepl("NA|NaN", .data$values_label), "-", .data$values_label),
values = ifelse((is.nan(.data$values) | is.na(.data$values)), 0, .data$values)
values = ifelse((is.nan(.data$values) | is.na(.data$values)), 0, .data$values),
) %>%
mutate(
channel = factor(.data$channel, levels = rev(unique(.data$channel))),
metric = factor(
dplyr::case_when(
.data$metric %in% c("spend", "response") ~ paste0(.data$metric, "%"),
TRUE ~ .data$metric
),
levels = paste0(unique(.data$metric), c("%", "%", "", ""))
)
) %>%
mutate(channel = factor(.data$channel, levels = rev(unique(.data$channel)))) %>%
group_by(.data$name_label) %>%
mutate(
values_norm = lares::normalize(.data$values),
values_norm = ifelse(is.nan(.data$values_norm), 0, .data$values_norm)
)

outputs[["p2"]] <- p2 <- df_plot_share %>%
ggplot(aes(x = .data$name_label, y = .data$channel, fill = .data$type)) +
ggplot(aes(x = .data$metric, y = .data$channel, fill = .data$type)) +
geom_tile(aes(alpha = .data$values_norm), color = "white") +
scale_fill_manual(values = c("grey50", "steelblue", "darkgoldenrod4")) +
scale_alpha_continuous(range = c(0.6, 1)) +
Expand Down Expand Up @@ -992,8 +1016,15 @@ allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_mo

# Gather all plots
if (export) {
scenario <- ifelse(scenario == "max_historical_response", "hist", "respo")
filename <- paste0(OutputCollect$plot_folder, select_model, "_reallocated_", scenario, ".png")
suffix <- dplyr::case_when(
scenario == "max_response" & metric == "ROAS" ~ "best_roas",
scenario == "max_response" & metric == "CPA" ~ "best_cpa",
scenario == "target_efficiency" & metric == "ROAS" ~ "target_roas",
scenario == "target_efficiency" & metric == "CPA" ~ "target_cpa",
TRUE ~ "none"
)
# suffix <- ifelse(scenario == "max_response", "resp", "effi")
filename <- paste0(OutputCollect$plot_folder, select_model, "_reallocated_", suffix, ".png")
if (!quiet) message("Exporting charts into file: ", filename)
ggsave(
filename = filename,
Expand Down
43 changes: 25 additions & 18 deletions R/man/robyn_allocator.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions R/man/robyn_outputs.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion R/man/robyn_response.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions R/man/robyn_write.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading