# Settings -------------------------------------------------------------------------------------------------------------


library(MASS)

library(investr)
library(nonmem2R)
library(patchwork)
library(readxl)
library(tidyverse)


drug_palette <- c("Canagliflozin" = "#7030a0",
                  "Dapagliflozin" = "#0070c0",
                  "Empagliflozin" = "#7f7f7f",
                  "Ipragliflozin" = "#ffc000",
                  "Luseogliflozin" = "#ff6600",
                  "Tofogliflozin" = "#339933")


# Fitting with Linear-Log Model for each drug --------------------------------------------------------------------------


df_uge <- read_csv("../data/data_uge.csv")

models <- df_uge %>%
  group_by(DRUG) %>%
  nest() %>%
  mutate(model = map(data, ~lm(UGE~log10(DOSE), data = .))) %>%
  pull(model) %>%
  set_names(unique(df_uge$DRUG))

# Parameter check
# lapply(models, coef) %>%
#   as_tibble() %>%
#   mutate(coef = c("Intercept", "log10(DOSE)")) %>%
#   select(coef, everything())


# Missing values of clinical doses are complemented by the model -------------------------------------------------------


uge_prediction <- function(drug_name, dose) {
  tmp_model <- models[[drug_name]]
  
  return(predict(tmp_model, newdata = data.frame(DOSE = dose)))
}

df_uge <- df_uge %>%
  rowwise() %>%
  mutate(UGE_imputed = ifelse(is.na(UGE), uge_prediction(DRUG, DOSE), UGE)) %>%
  ungroup()


# Calculation of UGE at clinical doses ---------------------------------------------------------------------------------


df_clinical_uge <- df_uge %>%
  filter(isClinicalDose == 1) %>%
  group_by(DRUG) %>%
  summarise(clinical_uge = exp(mean(log(UGE_imputed))))

reference_uge <- exp(mean(log(df_clinical_uge$clinical_uge)))


# Calculation of normalized clinical dose for each drug ----------------------------------------------------------------


reference_dose <- sapply(models, function(x){10**((reference_uge - coef(x)[1]) / coef(x)[2])})
names(reference_dose) <-  unique(df_uge$DRUG)


# Plotting（Figure 1） -------------------------------------------------------------------------------------------------


gg_fig1_list <- list()
for (i in unique(df_uge$DRUG)) {
  tmp_df <- df_uge %>%
    filter(DRUG == i)
  
  tmp_drug_palette <- ifelse(tmp_df$isClinicalDose == 1, drug_palette[i], "black")
  
  gg_fig1_list[[i]] <-
    ggplot(tmp_df, aes(x = DOSE, y = UGE_imputed)) +
    geom_vline(xintercept = reference_dose[[i]], color = "red", lty = "dashed") +
    annotate("text", x = max(tmp_df$DOSE), y = 5, hjust = 1, label = "--- reference dose", color = "red") +
    stat_function(fun = function (x, i) coef(models[[i]])[1] + log10(x) * coef(models[[i]])[2], args = list(i = i)) +
    geom_point(size = 3, shape = ifelse(is.na(tmp_df$UGE), 1, 21), fill = tmp_drug_palette, color = tmp_drug_palette) +
    ylim(0, 85) +
    labs(title = i,x = "Dose (mg)", y = "UGE (g / day)") +
    guides(shape = "none") +
    theme_test() +
    theme(plot.title = element_text(hjust = 0.5))
}

gg_fig1 <- wrap_plots(gg_fig1_list)
gg_fig1

# ggsave("../output/Figure1.png", gg_fig1, width = 9, height = 6)


# Dose normalization ---------------------------------------------------------------------------------------------------


df_uge <- df_uge %>%
  mutate(nDOSE = DOSE / reference_dose[DRUG])


# Validation of normalized doses (Figure 2） ---------------------------------------------------------------------------


norm_emax <- lm(UGE ~ log10(nDOSE) - 1, data = df_uge, offset = rep(reference_uge, nrow(df_uge)))

seq_dose <- 10**(seq(-2, 2, by = 0.01))
df_ci <- predFit(norm_emax, newdata = data.frame(nDOSE = seq_dose), interval = "confidence", level = 0.95) %>%
  as_tibble() %>%
  mutate(nDOSE = seq_dose)

gg_fig2 <- ggplot(aes(x = nDOSE, y = UGE), data = df_uge) +
  geom_vline(xintercept = 1, linewidth = 0.5, color = "gray20", linetype = "dashed") +
  geom_errorbar(aes(ymin = UGE - SE, ymax = UGE + SE), width = 0.03) +
  geom_point(aes(color = DRUG), size = 3) +
  geom_line(data = df_ci, aes(x = nDOSE, y = lwr), linewidth = 1, color = "gray")+
  geom_line(data = df_ci, aes(x = nDOSE, y = upr), linewidth = 1, color = "gray")+
  geom_line(data = df_ci, aes(x = nDOSE, y = fit), linewidth = 1)+
  scale_x_log10(labels = scales::label_number()) +
  scale_color_manual(values = drug_palette) +
  ylim(0, 85) +
  labs(x = "Normalized dose (Dose / Reference dose)", y = "UGE (g/day)") +
  theme_test()+
  theme(legend.position = c(0.98, 0.02), legend.justification = c(1, 0)) +
  guides(color = guide_legend(title = element_blank()))
gg_fig2

ggsave("../output/Figure2.png", gg_fig2, width = 6, height = 4.5)


# Normalize the doses in the dataset for MBMA --------------------------------------------------------------------------


df_hba1c <- read_xlsx("../data/TableS1-S2_Study information_240221.xlsx", sheet = "Table S2", na = c("", "-")) %>%
  select(ID,
         DOSE = `Dose (mg)`,
         HBA1C = `HbA1c change (%)`,
         SD = `SD of HbA1c change (%)`,
         NSUB = `Patients (n)`,
         JAPAN = `Study in Japan`,
         BW = `Body weight (kg)`,
         BMI = `BMI (kg/㎡)`,
         MALE = `Male (%)`,
         AGE = `Age (years)`,
         FPG = `FPG (mg/dL)`,
         BASE_HBA1C = `Baseline HbA1c (%)`,
         NAIVE = `Drug naïve`,
         ADD = `Concomitant drug`,
         DURATION = `Study duration (weeks)`,
         DIABETIC = `Diabetic duration (years)`,
         SBP = `SBP (mmHg)`,
         DBP = `DBP (mmHg)`,
         GFR = `eGFR (mL/min/1.73㎡)`) %>%
  mutate(ADD = ifelse(is.na(ADD), 0, 1),
         CANA = ifelse(floor(ID / 100) == 1, 1, 0),
         DAPA = ifelse(floor(ID / 100) == 2, 1, 0),
         EMPA = ifelse(floor(ID / 100) == 3, 1, 0),
         IPRA = ifelse(floor(ID / 100) == 4, 1, 0),
         LUSEO = ifelse(floor(ID / 100) == 5, 1, 0),
         TOFO = ifelse(floor(ID / 100) == 6, 1, 0),
         nDOSE = DOSE,
         nDOSE = ifelse(CANA == 1, nDOSE / reference_dose["Canagliflozin"], nDOSE),
         nDOSE = ifelse(DAPA == 1, nDOSE / reference_dose["Dapagliflozin"], nDOSE),
         nDOSE = ifelse(EMPA == 1, nDOSE / reference_dose["Empagliflozin"], nDOSE),
         nDOSE = ifelse(IPRA == 1, nDOSE / reference_dose["Ipragliflozin"], nDOSE),
         nDOSE = ifelse(LUSEO == 1, nDOSE / reference_dose["Luseogliflozin"], nDOSE),
         nDOSE = ifelse(TOFO == 1, nDOSE / reference_dose["Tofogliflozin"], nDOSE))

# write_csv(df_hba1c, "../data/data_hba1c.csv", na = "-99")


# Execution of scm -----------------------------------------------------------------------------------------------------


# system("scm config.scm -seed=42 -directory="../output/scm_dir"")


# Copy scm_dir>final_models>final_backword.mod to cwd
# Rename it as CONTROL_bootstrap
# Change path in $DATA


# Execution of bootstrap -----------------------------------------------------------------------------------------------


# system("bootstrap CONTROL_bootstrap -seed=42 -samples=500 -directory="../output/bootstrap_dir"")


# Move files generated directly under root to bootstrap_dir


# Loading the Final model ----------------------------------------------------------------------------------------------

position_CANA <- 8

df_table <- read_csv("../output/bootstrap_dir/CONTROL_bootstrap_table.csv") %>%
  mutate(DRUG = "NA",
         DRUG = ifelse(CANA == 1, "Canagliflozin", DRUG),
         DRUG = ifelse(DAPA == 1, "Dapagliflozin", DRUG),
         DRUG = ifelse(EMPA == 1, "Empagliflozin", DRUG),
         DRUG = ifelse(IPRA == 1, "Ipragliflozin", DRUG),
         DRUG = ifelse(LUSEO == 1, "Luseogliflozin", DRUG),
         DRUG = ifelse(TOFO == 1, "Tofogliflozin", DRUG))

params <- read_csv("../output/bootstrap_dir/raw_results_CONTROL_bootstrap.csv") %>%
  slice(1) %>%
  select(THETA1, THETA2, THETA3, THETA4, EMAXCANA1) %>%
  as.numeric()

covs <- covload("../output/bootstrap_dir/CONTROL_bootstrap.cov")


# Calculation of confidence intervals ----------------------------------------------------------------------------------


prb <- c(0.025, 0.500, 0.975)
ndose_seq <- seq(0, max(df_table$NDOSE), length = 300)

smp <- mvrnorm(10000, params, covs[c(1:4, position_CANA), c(1:4, position_CANA)]) %>%
  as.data.frame() %>%
  rename(BASE = THETA1, EMAX = THETA2, ED50 = THETA3, HILL = THETA4, CANA = paste0("THETA", position_CANA))

sig_emax_model <- function(x, par) {
  return(par["BASE"] + par["EMAX"] * x**par["HILL"] / (par["ED50"]**par["HILL"] + x**par["HILL"]))
}

sim <- apply(smp, 1, sig_emax_model, x = ndose_seq) %>%
  apply(1, quantile, probs = prb, na.rm = TRUE) %>%
  t() %>%
  as_tibble() %>%
  mutate(NDOSE = ndose_seq)


sig_emax_model_CANA <- function(x, par) {
  EMAX <- par["EMAX"] * (1 + par["CANA"])
  return(par["BASE"] + EMAX * x**par["HILL"] / (par["ED50"]**par["HILL"] + x**par["HILL"]))
}

sim_cana <- apply(smp, 1, sig_emax_model_CANA, x = ndose_seq) %>%
  apply(1, quantile, probs = prb, na.rm = TRUE) %>%
  t() %>%
  as_tibble() %>%
  mutate(NDOSE = ndose_seq)


# Plotting (Figure 3) --------------------------------------------------------------------------------------------------


gg_fig3 <- ggplot() +
  geom_hline(yintercept = 0, linewidth = 0.5, color = "gray20", linetype = "dashed") +
  geom_point(aes(x = NDOSE, y = HBA1C, color = DRUG), data = df_table) +
  geom_ribbon(aes(x = NDOSE, ymin = `2.5%`, ymax = `97.5%`), data = sim, alpha = 0.3, fill = "gray") +
  geom_line(aes(x = NDOSE, y = `50%`), data = sim, linewidth = 1) +
  scale_color_manual(values = drug_palette) +
  labs(x = "Normalized dose (Dose / Reference dose)", y = "HbA1c change from baseline") +
  theme_test() +
  theme(legend.position = c(0.98, 0.99), legend.justification = c(1, 1)) +
  guides(color = guide_legend(title = element_blank(), ncol = 2))
gg_fig3

# ggsave("../output/Figure3.png", gg_fig3, width = 6, height = 4.5)


# Plotting (Figure 4) --------------------------------------------------------------------------------------------------


gg_fig4 <- ggplot() +
  geom_hline(yintercept = 0, linewidth = 0.5, color = "gray20", linetype = "dashed") +
  geom_point(aes(x = NDOSE, y = HBA1C, color = factor(CANA)), data = df_table) +
  geom_ribbon(aes(x = NDOSE, ymin = `2.5%`, ymax = `97.5%`), data = sim, alpha = 0.3, fill = "#6b6b6b") +
  geom_line(aes(x = NDOSE, y = `50%`), data = sim, color = "#6b6b6b", linewidth = 1) +
  geom_ribbon(aes(x = NDOSE, ymin = `2.5%`, ymax = `97.5%`), data = sim_cana, alpha = 0.3, fill = "#5a198d") +
  geom_line(aes(x = NDOSE, y = `50%`), data = sim_cana, color = "#5a198d", linewidth = 1) +
  scale_color_manual(values = c("1" = "#5a198d", "0" = "#6b6b6b"), labels = c("1" = "Canagliflozin", "0" = "Others")) +
  labs(x = "Normalized dose (Dose / Reference dose)", y = "HbA1c change from baseline") +
  theme_test() +
  theme(legend.position = c(0.98, 0.98), legend.justification = c(1, 1)) +
  guides(color = guide_legend(title = element_blank()))
gg_fig4

# ggsave("../output/Figure4.png", gg_fig4, width = 6, height = 4.5)


# Goodness of fit plot (Figure 5) --------------------------------------------------------------------------------------

control <- GOF.control()

gg_fig5_1 <- df_table %>%
  rename(DV = HBA1C) %>%
  ggplot(aes(x = PRED, y = DV)) +
  geom_point() +
  geom_abline(slope = 1, intercept = 0, color = "red", linetype = "dashed", linewidth = 1) +
  stat_smooth(method = "loess",
              span = control$span.smooth,
              method.args = list(degree = control$degree.smooth,
                                 family = control$family.smooth)) +
  labs(x = "Population predictions", y = "Observations")

gg_fig5_2 <- df_table %>%
  rename(DV = HBA1C) %>%
  ggplot(aes(x = IPRED, y = DV)) +
  geom_point() +
  geom_abline(slope = 1, intercept = 0, color = "red", linetype = "dashed", linewidth = 1) +
  stat_smooth(method = "loess",
              span = control$span.smooth,
              method.args = list(degree = control$degree.smooth,
                                 family = control$family.smooth)) +
  labs(x = "Individual predictions", y = "Observations")

gg_fig5_3 <- df_table %>%
  rename(DV = HBA1C) %>%
  ggplot(aes(x = CWRES)) +
  geom_histogram(aes(y = ..density..), bins = ceiling(1 + log2(nrow(df_table)))) +
  geom_density(alpha = 0, color = "#3366ff", linewidth = 1) +
  stat_function(fun = dnorm, color = "red", linetype = "dashed", linewidth = 1) +
  labs(x = "CWRES", y = "Density")

fig_4_intercept <- df_table$CWRES %>% abs() %>% sqrt() %>% mean()
gg_fig5_4 <- df_table %>%
  rename(DV = HBA1C) %>%
  ggplot(aes(x = IPRED, y = sqrt(abs(CWRES)))) +
  geom_point() +
  geom_abline(slope = 0, intercept = fig_4_intercept, color = "red", linetype = "dashed", linewidth = 1) +
  stat_smooth(method = "loess",
              span = control$span.smooth,
              method.args = list(degree = control$degree.smooth,
                                 family = control$family.smooth)) +
  labs(x = "Individual predictions", y = expression(sqrt("|CWRES|")))

gg_fig5_5 <- df_table %>%
  ggplot(aes(x = NDOSE, y = CWRES)) +
  geom_point() +
  geom_abline(slope = 0, intercept = 0, color = "red", linetype = "dashed", linewidth = 1) +
  stat_smooth(method = "loess",
              span = control$span.smooth,
              method.args = list(degree = control$degree.smooth,
                                 family = control$family.smooth)) +
  labs(x = "Normalized dose", y = "Individual predictions")

gg_fig5_6 <- df_table %>%
  ggplot(aes(sample = CWRES)) +
  stat_qq() +
  stat_qq_line(color = "red", linetype = "dashed", linewidth = 1) +
  labs(x = "Theoretical Quantiles", y = "CWRES")

gg_fig5 <- gg_fig5_1 + gg_fig5_2 + gg_fig5_3 + gg_fig5_4 + gg_fig5_5 + gg_fig5_6 +
  plot_annotation(tag_levels = "A") & theme_test()

ggsave("../output/Figure5.png", gg_fig5, width = 9, height = 6)
