## Overview
<!--START_EXPLANATION-->
This document contains exploratory plots for continuous PD data as well as the R code that generates these graphs. The plots presented here are based on simulated data ([see: PKPD Datasets](PKPD_Datasets.html)). Data specifications can be accessed on [Datasets](Datasets.html) and Rmarkdown template to generate this page can be found on [Rmarkdown-Template](Rmarkdown/Multiple_Ascending_Dose_PKPD_continuous.Rmd). You may also download the Multiple Ascending Dose PK/PD dataset for your reference ([download dataset](Data/Multiple_Ascending_Dose_Dataset2.csv)).
<!--END_EXPLANATION-->

## Setup

```{r, error = TRUE, warning=FALSE, message=FALSE}
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)
library(xgxr)

#flag for labeling figures as draft
status = "DRAFT"

## ggplot settings
xgx_theme_set()

#directories for saving individual graphs
dirs = list(
  parent_dir= tempdir(),
  rscript_dir  = "./",
  rscript_name = "Example.R",
  results_dir  = "./",
  filename_prefix   = "",
  filename     = "Example.png")
```

## Load Dataset

```{r, error = TRUE, warning=FALSE, message=FALSE}
#load dataset
pkpd_data <- read.csv("../Data/Multiple_Ascending_Dose_Dataset2.csv")

DOSE_CMT = 1
PK_CMT = 2
PD_CMT = 3
SS_PROFDAY = 6 # steady state prof day
PD_PROFDAYS <- c(0, 2, 4, 6)
TAU = 24 # time between doses, units should match units of TIME, e.g. 24 for QD, 12 for BID, 7*24 for Q1W (when units of TIME are h)

#ensure dataset has all the necessary columns
pkpd_data = pkpd_data %>%
  mutate(ID      = ID,     #ID   column
         TIME    = TIME,   #TIME column name 
         NOMTIME = NOMTIME,#NOMINAL TIME column name
         PROFDAY = 1 + floor(NOMTIME / 24), #PROFILE DAY day associated with profile, e.g. day of dose administration
         LIDV    = LIDV,   #DEPENDENT VARIABLE column name
         CENS    = CENS,   #CENSORING column name
         CMT     = CMT,    #COMPARTMENT column
         DOSE    = DOSE,   #DOSE column here (numeric value)
         TRTACT  = TRTACT, #DOSE REGIMEN column here (character, with units),
         LIDV_NORM = LIDV/DOSE,
         LIDV_UNIT    = EVENTU,
         DAY_label = ifelse(PROFDAY > 0, paste("Day", PROFDAY), "Baseline")
  )

#create a factor for the treatment variable for plotting
pkpd_data = pkpd_data %>%
  arrange(DOSE) %>%
  mutate(TRTACT_low2high = factor(TRTACT, levels = unique(TRTACT)),
         TRTACT_high2low = factor(TRTACT, levels = rev(unique(TRTACT))))

#create pk and pd datasets
pk_data <- pkpd_data %>%
  filter(CMT==PK_CMT)

pd_data <- pkpd_data %>%
  filter(CMT==PD_CMT)

#create wide pkpd dataset for plotting PK vs PD
pkpd_data_wide <- pd_data %>%
  select(ID, NOMTIME, PD = LIDV) %>%
  right_join(pk_data) %>%
  rename(CONC = LIDV)%>%
  filter(!is.na(PD))%>%
  filter(!is.na(CONC))

#perform NCA, for additional plots
NCA = pk_data %>%
  group_by(ID, DOSE) %>%
  filter(!is.na(LIDV)) %>%
  summarize(AUC_0 = ifelse(length(LIDV[NOMTIME > 0 & NOMTIME <= TAU]) > 1,
                              caTools::trapz(TIME[NOMTIME > 0 & NOMTIME <= TAU], 
                                      LIDV[NOMTIME > 0 & NOMTIME <= TAU]),
                              NA), 
            Cmax_0     = ifelse(length(LIDV[NOMTIME > 0 & NOMTIME <= TAU]) > 1,
                              max(LIDV[NOMTIME > 0 & NOMTIME <= TAU]),
                              NA), 
            AUC_tau = ifelse(length(LIDV[NOMTIME > (SS_PROFDAY-1)*24 & 
                                           NOMTIME <= ((SS_PROFDAY-1)*24 + TAU)]) > 1,
                             caTools::trapz(TIME[NOMTIME > (SS_PROFDAY-1)*24 & 
                                                   NOMTIME <= ((SS_PROFDAY-1)*24 + TAU)],
                                     LIDV[NOMTIME > (SS_PROFDAY-1)*24 & 
                                            NOMTIME <= ((SS_PROFDAY-1)*24 + TAU)]),
                             NA),
            Cmax_tau     = ifelse(length(LIDV[NOMTIME > (SS_PROFDAY-1)*24 & 
                                                NOMTIME <= ((SS_PROFDAY-1)*24 + TAU)]) > 1,
                             max(LIDV[NOMTIME > (SS_PROFDAY-1)*24 & 
                                        NOMTIME <= ((SS_PROFDAY-1)*24 + TAU)]),
                             NA), 
            SEX      = SEX[1], #this part just keeps the SEX and WEIGHTB covariates
            WEIGHTB  = WEIGHTB[1]) %>%
  gather(PARAM, VALUE,-c(ID, DOSE, SEX, WEIGHTB)) %>%
  ungroup() %>%
  mutate(VALUE_NORM = VALUE/DOSE,
         PROFDAY = ifelse(PARAM %in% c("AUC_0", "Cmax_0"), 1, SS_PROFDAY))

#add response data at day 1 and steady state to NCA for additional plots
NCA <- pd_data %>% subset(PROFDAY %in% c(1, SS_PROFDAY),) %>%
  select(ID, PROFDAY, DAY_label, PD = LIDV, TRTACT_low2high, TRTACT_high2low) %>%
  merge(NCA, by = c("ID","PROFDAY"))

#units and labels
time_units_dataset = "hours"
time_units_plot    = "days"
trtact_label       = "Dose"
dose_units         = unique((pkpd_data %>% filter(CMT == DOSE_CMT) )$LIDV_UNIT) %>% as.character()
dose_label         = paste0("Dose (", dose_units, ")")
conc_units         = unique(pk_data$LIDV_UNIT) %>% as.character()
conc_label         = paste0("Concentration (", conc_units, ")")
concnorm_label     = paste0("Normalized Concentration (", conc_units, ")/", dose_units)
AUC_units          = paste0("h.", conc_units)
pd_units           = unique(pd_data$LIDV_UNIT) %>% as.character()
pd_label           = paste0("Continuous PD Marker (", pd_units, ")")  

```


## Provide an overview of the data
<!--START_EXPLANATION-->
Summarize the data in a way that is easy to visualize the general trend of PD over time and between doses. Using summary statistics can be helpful, e.g. Mean +/- SE, or median, 5th & 95th percentiles. Consider either coloring by dose or faceting by dose. Depending on the amount of data one graph may be better than the other.
<!--END_EXPLANATION-->

### PK and PD marker over time, colored by Dose, mean (95% CI) percentiles by nominal time
<!--START_EXPLANATION-->
Observe the overall shape of the average profiles. Does the effect appear to increase and decrease quickly on a short time scale, or does is occur over a longer time scale? Do the PK and PD profiles appear to be on the same time scale, or does the PD seem delayed compared to the PK? Is there clear separation between the profiles for different doses? Does the effect appear to increase with increasing dose? Do you detect a saturation of the effect? 
<!--END_EXPLANATION-->

```{r, error = TRUE, cache = TRUE, fig.width = 10, fig.height = 3, warning = FALSE, message= FALSE}

#PK data
gg <- ggplot(data = pk_data, 
             aes(x = NOMTIME,y = LIDV, color = TRTACT_high2low, fill = TRTACT_high2low)) 
gg <- gg + xgx_stat_ci(conf_level = .95)
gg <- gg + xgx_annotate_status(status)
gg <- gg + xgx_scale_x_time_units(units_dataset = time_units_dataset, 
                                  units_plot    = time_units_plot)
gg <- gg + guides(color = guide_legend(""), fill = guide_legend(""))
gg <- gg + xgx_scale_y_log10()
gg <- gg + labs(y = conc_label)
print(gg)


#PD data
gg %+% (data = pd_data) + scale_y_continuous() + labs(y = pd_label)
```

### PK and PD marker over time, faceted by Dose, mean (95% CI) by nominal time

```{r, error = TRUE, cache = TRUE, fig.width = 10, fig.height = 3, warning = FALSE, message= FALSE}
#PK data
gg <- ggplot(data = pk_data, 
             aes(x = NOMTIME,y = LIDV))
gg <- gg + xgx_stat_ci(conf_level = .95)
gg <- gg + xgx_scale_x_time_units(units_dataset = time_units_dataset, 
                                  units_plot    = time_units_plot)
gg <- gg + guides(color = guide_legend(""),fill = guide_legend(""))
gg <- gg + facet_grid(~TRTACT_low2high)
gg <- gg + xgx_scale_y_log10()
gg <- gg + labs(y = conc_label)
print(gg)

#PD data
gg %+% (data = pd_data %>% subset(DOSE>0)) + scale_y_continuous() + labs(y = pd_label)
```

## Explore variability
<!--START_EXPLANATION-->
Use spaghetti plots to visualize the extent of variability between individuals. The wider the spread of the profiles, the higher the between subject variability. Distinguish different doses by color, or separate into different panels. If coloring by dose, do the individuals in the different dose groups overlap across doses? Dose there seem to be more variability at higher or lower concentrations?
<!--END_EXPLANATION-->

### PK and PD marker over time, colored by Dose, dots & lines grouped by individuals

```{r, error = TRUE, cache = TRUE, fig.width = 10, fig.height = 3, warning = FALSE, message= FALSE}
#PK data
gg <- ggplot(data = pk_data, 
             aes(x = TIME, y = LIDV,group = ID, color = factor(TRTACT_high2low))) 
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_line(alpha = 0.5)
gg <- gg + geom_point(alpha = 0.5)
gg <- gg + guides(color = guide_legend(""), fill = guide_legend(""))
gg <- gg + xgx_scale_x_time_units(units_dataset = time_units_dataset, 
                                  units_plot    = time_units_plot)    
gg <- gg + geom_point(data = pk_data %>% subset(CENS == 1,), color = "red", shape = 8,alpha = 0.5)
gg <- gg + xgx_scale_y_log10() 
gg <- gg + labs(y = conc_label)
print(gg)

#PD data
gg %+% (data = pd_data %>% subset(DOSE>0)) + scale_y_continuous() + labs(y = pd_label)
```

### PK and PD marker over time, faceted by Dose, dots & lines grouped by individuals

```{r, error = TRUE, cache = TRUE, fig.width = 10, fig.height = 3, warning = FALSE, message= FALSE}
#PK data
gg <- ggplot(data = pk_data, aes(x = TIME, y = LIDV, group = ID))
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_line(alpha = 0.5)
gg <- gg + geom_point(alpha = 0.5)
gg <- gg + guides(color = guide_legend(""), fill = guide_legend(""))
gg <- gg + xgx_scale_x_time_units(units_dataset = time_units_dataset, 
                                  units_plot    = time_units_plot)
gg <- gg + facet_grid(~TRTACT_low2high)
gg <- gg + xgx_scale_y_log10() 
gg <- gg + labs(y = conc_label)

gg1 <- gg + geom_point(data = pk_data %>% subset(CENS==1,), color="red", shape=8, alpha = 0.5)
print(gg1)

#PD data
gg %+% (data = pd_data %>% subset(DOSE>0)) + scale_y_continuous() + labs(y = pd_label)
```

## Explore Exposure-Response Relationship

### PD marker by Concentration, for endpoint of interest, mean (95% CI) by concentration bins
<!--START_EXPLANATION-->
Plot PD marker against concentration. Do you see any relationship? Does response increase (decrease) with increasing dose? Are you able to detect a plateau or emax (emin) on the effect? 

**Warning:** Even if you don't see an Emax, that doesn't mean there isn't one. Be very careful about using linear models for Dose-Response or Exposure-Response relationships. Extrapolation outside of the observed dose range could indicate a higher dose is always better (even if it isn't).
<!--END_EXPLANATION-->

```{r, error = TRUE, cache = TRUE, fig.width = 8, fig.height = 4, warning = FALSE, message= FALSE}
gg <- ggplot(data = pkpd_data_wide %>% subset(PROFDAY == SS_PROFDAY,), aes(x = CONC,y = PD))
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_point(aes(color = TRTACT_high2low))
gg <- gg + geom_point(data = pkpd_data_wide %>% subset(CENS==1,), color="red", shape = 8)
gg <- gg + labs(x = conc_label , y = pd_label)
gg <- gg + guides(color = guide_legend(""))

gg <- gg + xgx_geom_smooth_emax(color = "black") 
## Note: if the above line doesn't work, try modifying the formula, 
##       initial estimates, or lower bounds in the following code
# gg <- gg + xgx_geom_smooth(color = "black", method = "nlsLM", 
#                            formula = y ~ E0 + Emax*x/(ED50 + x),
#                            method.args = list(
#                              start = list(Emax = 1, ED50 = 1, E0 = 1),
#                              lower = c(-Inf, 0, -Inf)))

gg <- gg + xgx_stat_ci(bins = 4, geom = "point", shape = 0, size = 4)
gg <- gg + xgx_stat_ci(bins = 4, geom = "errorbar")

gg1 <- gg + ggtitle("Concentration on Linear Scale")
gg2 <- gg + xgx_scale_x_log10() + ggtitle("Concentration on Log Scale")

grid.arrange(gg1,gg2,nrow = 1)
```

### PD marker by Concentration, faceted by visit, mean (95% CI) by concentration bins

```{r, error = TRUE, cache = TRUE, fig.width = 8, fig.height = 6, warning = FALSE, message= FALSE}
data_to_plot <- pkpd_data_wide %>% subset(PROFDAY %in% PD_PROFDAYS,)

gg <- ggplot(data = data_to_plot,
             aes(x = CONC, y = PD))
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_point(aes(color = TRTACT_high2low))
gg <- gg + geom_point(data = data_to_plot %>% subset(CENS==1,), color="red", shape = 8)
gg <- gg + guides(color = guide_legend(""), fill = guide_legend(""))
gg <- gg + labs(x = conc_label , y = pd_label)
gg <- gg + xgx_stat_ci(bins = 4, geom = "point", shape = 0, size = 4)
gg <- gg + xgx_stat_ci(bins = 4, geom = "errorbar")
gg <- gg + facet_grid(~DAY_label)

gg1 <- gg + xgx_geom_smooth_emax(color = "black") + ggtitle("Concentration on Linear Scale")
gg2 <- gg + xgx_geom_smooth(color = "black", method = "nlsLM", formula = y ~ E0 + Emax*x/(ED50 + x),
                     method.args = list(
                         start = list(Emax = 1, ED50 = 5, E0 = 1),
                         lower = c(-Inf, 0, -Inf))) + 
  xgx_scale_x_log10() + ggtitle("Concentration on Log Scale")

grid.arrange(gg1,gg2,nrow = 2)

```

<!--START_EXPLANATION-->
Plotting AUC vs response instead of concentration vs response may make more sense in some situations. For example, when there is a large delay between PK and PD it would be diffcult to relate the time-varying concentration with the response. If rich sampling is only done at a particular point in the study, e.g. at steady state, then the AUC calculated on the rich profile could be used as the exposure variable for a number of PD visits. If PK samples are scarce, average Cmin could also be used as the exposure metric.
<!--END_EXPLANATION-->

```{r, error = TRUE, cache = TRUE, fig.width = 8, fig.height = 6, warning = FALSE, message= FALSE}
gg <- ggplot(data = NCA, aes(x = VALUE, y = PD))
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_point(aes(color = TRTACT_high2low)) 

gg <- gg + xgx_geom_smooth_emax(color = "black")
## Note: if the above line doesn't work, try modifying the formula, 
##       initial estimates, or lower bounds in the following code
# gg <- gg + xgx_geom_smooth(color = "black", method = "nlsLM", 
#                            formula = y ~ E0 + Emax*x/(ED50 + x),
#                            method.args = list(
#                              start = list(Emax = 1, ED50 = 1, E0 = 1),
#                              lower = c(-Inf, 0, -Inf)))

gg <- gg + xgx_stat_ci(bins = 4, geom = "errorbar")
gg <- gg + xgx_stat_ci(bins = 4, geom = "point", shape = 0, size = 4)
gg <- gg + guides(color = guide_legend(""), fill = guide_legend(""))
gg <- gg + labs(color = trtact_label, x = "NCA parameter", y = pd_label)
gg <- gg + facet_wrap(~DAY_label + PARAM, scales = "free_x")
print(gg)
```

### Explore covariate effects on Exposure-Response Relationship
<!--START_EXPLANATION-->
Stratify exposure-response plots by covariates of interest to explore whether any key covariates impact response independent of exposure. 
<!--END_EXPLANATION-->

```{r, error = TRUE, cache = TRUE, fig.width = 8, fig.height = 4, warning = FALSE, message= FALSE}
gg <- ggplot(data = NCA, aes(x = VALUE, y = PD)) 
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_point(aes(color = SEX)) 

gg <- gg + xgx_geom_smooth_emax(aes(color = SEX))
## Note: if the above line doesn't work, try modifying the formula, 
##       initial estimates, or lower bounds in the following code
# gg <- gg + xgx_geom_smooth(aes(color = SEX), method = "nlsLM", 
#                            formula = y ~ E0 + Emax*x/(ED50 + x),
#                            method.args = list(
#                              start = list(Emax = 1, ED50 = 1, E0 = 1),
#                              lower = c(-Inf, 0, -Inf)))

gg <- gg + guides(color = guide_legend(""), fill = guide_legend(""))
gg <- gg + labs(x = AUC_units , y = pd_label)
gg + facet_grid(.~DAY_label) 
```

### Individual response vs exposure hysteresis plots
<!--START_EXPLANATION-->
Using geom_path you can create hysteresis plots of response vs exposure. Including details like arrows or colors can be helpful to indicate the direction of time.

If most of the arrows point up and to the right or down and to the left, this indicates a positive relationship between exposure and response (i.e. increasing exposure -> increasing response). Arrows pointing down and to the right or up and to the left indicate a negative relationship. 

In a hysteresis plot, you want to determine whether the path is curving, and if so in what direction. If you detect a curve in the hysteresis plot, this indicates there is a delay between the exposure and the response. Normally, a clockwise turn indicates that increasing exposure is associated with (a delayed) increasing response, while a counter clockwise turn indicates increasing concentration gives (a delayed) decreasing response. 

In the plots below, most of the hysteresis paths follow a counter clockwise turn, with most arrows pointing up and to the right or down and to the left, indicating the effect increases in a delayed manner with increasing concentration.
<!--END_EXPLANATION-->

```{r, error = TRUE, cache = TRUE, fig.width = 8, fig.height = 15, warning = FALSE, message= FALSE}
pkpd_data_wide <- pkpd_data_wide %>% arrange(ID, TIME)

gg <- ggplot(data = pkpd_data_wide, aes(x = CONC, y = PD, color = TIME))
gg <- gg + xgx_annotate_status(status)
gg <- gg + geom_path(arrow = arrow(length = unit(0.15,"cm")))
gg <- gg + labs(x = conc_label , y = pd_label)
gg <- gg + xgx_scale_x_log10() 
gg <- gg + xgx_scale_y_log10() 
gg <- gg + theme(panel.grid.minor.x = ggplot2::element_line(color = rgb(0.9,0.9,0.9)),
                 panel.grid.minor.y = ggplot2::element_line(color = rgb(0.9,0.9,0.9)))

gg + facet_wrap(~ID + TRTACT_low2high, ncol = 5)
```

## R Session Info
```{r}
sessionInfo()
```
