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: add clusters information to one-pagers, fix metric notes, reduce texts sizes, no ng check to recreate + fix: RNG warning #928

Merged
merged 15 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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.5.9015
Version: 3.10.5.9016
Authors@R: c(
person("Gufeng", "Zhou", , "gufeng@meta.com", c("cre","aut")),
person("Leonel", "Sentana", , "leonelsentana@meta.com", c("aut")),
Expand Down
1 change: 1 addition & 0 deletions R/R/clusters.R
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ robyn_clusters <- function(input, dep_var_type,
dim_red = dim_red, quiet = TRUE, seed = seed
)
)
cls$df <- group_by(cls$df, .data$cluster) %>% mutate(n = n()) %>% ungroup()

# Select top models by minimum (weighted) distance to zero
all_paid <- setdiff(names(cls$df), c(ignore, "cluster"))
Expand Down
10 changes: 9 additions & 1 deletion R/R/json.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ robyn_write <- function(InputCollect,
OutputCollect$OutputModels$trials
collect$conv_msg <- gsub("\\:.*", "", OutputCollect$OutputModels$convergence$conv_msg)
if ("clusters" %in% names(OutputCollect)) {
collect$clusters <- OutputCollect$clusters$n_clusters
collect$n_clusters <- OutputCollect$clusters$n_clusters
}

skip <- which(unlist(lapply(OutputCollect, function(x) is.list(x) | is.null(x))))
Expand Down Expand Up @@ -106,6 +106,14 @@ robyn_write <- function(InputCollect,
select(order(colnames(.))) %>%
as.list()
outputs$hyper_updated <- OutputCollect$hyper_updated
if ("clusters" %in% names(OutputCollect)) {
outputs$clusters <- list(
data = OutputCollect$clusters$data %>%
group_by(.data$cluster) %>% mutate(n = n()) %>%
filter(.data$solID == select_model) %>%
select(any_of(c("solID", "cluster", "n")))
)
}
ret[["ExportedModel"]] <- outputs
} else {
select_model <- "models"
Expand Down
29 changes: 18 additions & 11 deletions R/R/model.R
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,11 @@ robyn_run <- function(InputCollect = NULL,
output <- robyn_outputs(InputCollect, OutputModels, clusters = FALSE, ...)
}

# Created with assign from JSON file
if (exists("clusters"))
if (!is.integer(get("clusters")))
output$clusters <- get("clusters")

# Check convergence when more than 1 iteration
if (!hyper_collect$all_fixed) {
output[["convergence"]] <- robyn_converge(OutputModels, ...)
Expand Down Expand Up @@ -300,7 +305,7 @@ Pareto-front ({x$pareto_fronts}) All solutions ({nSols}): {paste(x$allSolutions,
{clusters_info}
",
nSols = length(x$allSolutions),
clusters_info = if ("clusters" %in% names(x)) {
clusters_info = if ("models" %in% names(x[["clusters"]])) {
glued(
"Clusters (k = {x$clusters$n_clusters}): {paste(x$clusters$models$solID, collapse = ', ')}"
)
Expand Down Expand Up @@ -451,17 +456,19 @@ robyn_mmm <- function(InputCollect,
trial = 1L,
seed = 123L,
quiet = FALSE, ...) {
if (reticulate::py_module_available("nevergrad")) {
ng <- reticulate::import("nevergrad", delay_load = TRUE)
if (is.integer(seed)) {
np <- reticulate::import("numpy", delay_load = FALSE)
np$random$seed(seed)
if (iterations > 1) {
if (reticulate::py_module_available("nevergrad")) {
ng <- reticulate::import("nevergrad", delay_load = TRUE)
if (is.integer(seed)) {
np <- reticulate::import("numpy", delay_load = FALSE)
np$random$seed(seed)
}
} else {
stop(
"You must have nevergrad python library installed.\nPlease check our install demo: ",
"https://github.com/facebookexperimental/Robyn/blob/main/demo/install_nevergrad.R"
)
}
} else {
stop(
"You must have nevergrad python library installed.\nPlease check our install demo: ",
"https://github.com/facebookexperimental/Robyn/blob/main/demo/install_nevergrad.R"
)
}

################################################
Expand Down
32 changes: 22 additions & 10 deletions R/R/plots.R
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ robyn_onepagers <- function(
baseline_level = 0, ...) {
check_class("robyn_outputs", OutputCollect)
if (TRUE) {
window <- c(InputCollect$window_start, InputCollect$window_end)
pareto_fronts <- OutputCollect$pareto_fronts
hyper_fixed <- OutputCollect$hyper_fixed
resultHypParam <- as_tibble(OutputCollect$resultHypParam)
Expand Down Expand Up @@ -315,7 +316,7 @@ robyn_onepagers <- function(
uniqueSol <- unique(plotMediaShare$solID)

# parallelResult <- for (sid in uniqueSol) { # sid = uniqueSol[1]
parallelResult <- foreach(sid = uniqueSol) %dorng% { # sid = uniqueSol[1]
parallelResult <- foreach(sid = uniqueSol, .options.RNG = OutputCollect$seed) %dorng% { # sid = uniqueSol[1]

if (TRUE) {
plotMediaShareLoop <- plotMediaShare[plotMediaShare$solID == sid, ]
Expand Down Expand Up @@ -354,7 +355,7 @@ robyn_onepagers <- function(
plotMediaShareLoopLine <- temp[[sid]]$plot1data$plotMediaShareLoopLine
ySecScale <- temp[[sid]]$plot1data$ySecScale
plotMediaShareLoopBar$variable <- stringr::str_to_title(gsub("_", " ", plotMediaShareLoopBar$variable))
type <- ifelse(InputCollect$dep_var_type == "conversion", "CPA", "ROI")
type <- ifelse(InputCollect$dep_var_type == "conversion", "CPA", "ROAS")
plotMediaShareLoopLine$type_colour <- type_colour <- "#03396C"
names(type_colour) <- "type_colour"
p1 <- ggplot(plotMediaShareLoopBar, aes(x = .data$rn, y = .data$value, fill = .data$variable)) +
Expand Down Expand Up @@ -386,7 +387,7 @@ robyn_onepagers <- function(
scale_fill_brewer(palette = 3) +
scale_color_identity(guide = "legend", labels = type) +
labs(
title = paste0("Share of Sum of Spend, Sum of Effect & Total ", type, " in Modeling Window*"),
title = paste0("Share of Total Spend, Effect & ", type, " in Modeling Window*"),
x = NULL, fill = NULL, color = NULL
)

Expand Down Expand Up @@ -589,7 +590,14 @@ robyn_onepagers <- function(

## 8. Bootstrapped ROI/CPA with CIs
if ("ci_low" %in% colnames(xDecompAgg)) {
metric <- ifelse(InputCollect$dep_var_type == "conversion", "CPA", "ROI")
cluster_txt <- ""
if ("clusters" %in% names(OutputCollect)) {
temp <- OutputCollect$clusters$data
if (!"n" %in% colnames(temp)) temp <- group_by(temp, .data$cluster) %>% mutate(n = n())
temp <- filter(temp, .data$solID == sid)
cluster_txt <- sprintf(" %s (%s IDs)", temp$cluster, temp$n)
}
title <- sprintf("In-cluster%s bootstrapped %s [95%% CI & mean]", cluster_txt, type)
p8 <- xDecompAgg %>%
filter(!is.na(.data$ci_low), .data$solID == sid) %>%
select(.data$rn, .data$solID, .data$boot_mean, .data$ci_low, .data$ci_up) %>%
Expand All @@ -599,10 +607,10 @@ robyn_onepagers <- function(
geom_text(aes(y = .data$ci_low, label = signif(.data$ci_low, 2)), hjust = 1.1, size = 2.8) +
geom_text(aes(y = .data$ci_up, label = signif(.data$ci_up, 2)), hjust = -0.1, size = 2.8) +
geom_errorbar(aes(ymin = .data$ci_low, ymax = .data$ci_up), width = 0.25) +
labs(title = paste("In-cluster bootstrapped", metric, "with 95% CI & mean"), x = NULL, y = NULL) +
labs(title = title, x = NULL, y = NULL) +
coord_flip() +
theme_lares(background = "white", )
if (metric == "ROI") {
if (type == "ROAS") {
p8 <- p8 + geom_hline(yintercept = 1, alpha = 0.5, colour = "grey50", linetype = "dashed")
}
} else {
Expand All @@ -614,8 +622,12 @@ robyn_onepagers <- function(
rver <- utils::sessionInfo()$R.version
onepagerTitle <- sprintf("One-pager for Model ID: %s", sid)
onepagerCaption <- sprintf("Robyn v%s [R-%s.%s]", ver, rver$major, rver$minor)
onepagerCaption <- paste0(onepagerCaption,
"\n*Total ROI = sum of response / sum of spend in the modeling window")
calc <- ifelse(type == "ROAS",
"Total ROAS = sum of response / sum of spend",
"Total CPA = sum of spend / sum of response")
onepagerCaption <- paste0(
"*", calc, " in modeling window ", paste0(window, collapse = ":"),
"\n", onepagerCaption)
get_height <- length(unique(plotMediaShareLoopLine$rn)) / 5
pg <- (p2 + p5) / (p1 + p8) / (p3 + p7) / (p4 + p6) +
patchwork::plot_layout(heights = c(get_height, get_height, get_height, 1)) +
Expand Down Expand Up @@ -676,8 +688,8 @@ allocation_plots <- function(
"* Mean CPA = raw spend / mean response | mCPA = marginal spend / marginal response"
)
formulax1 <- paste0(
"The allocator 'mean response' = curve response of adstocked mean spend in date range, ",
"while the model onepager 'sum of effect' = sum of curve responses of all adstocked spends in modeling window\n",
"Allocator's mean response = curve response of adstocked mean spend in date range, ",
"while\n Model's sum of effect = sum of curve responses of all adstocked spends in modeling window\n",
formulax1)
formulax2 <- sprintf("When reallocating budget, m%s converges across media within respective bounds", metric)

Expand Down