---
title: "Superposition of Pharmacokinetic Data"
author: "Bill Denney"
output:
  rmarkdown::html_vignette:
    toc: yes
    toc_depth: 6
vignette: >
  %\VignetteIndexEntry{Superposition of Pharmacokinetic Data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, echo=FALSE, include=FALSE}
library(PKNCA)
library(knitr)
library(ggplot2)
scale_colour_discrete <- scale_colour_hue
scale_fill_discrete <- scale_fill_hue
scale_colour_ordinal <- scale_colour_hue
scale_fill_ordinal <- scale_fill_hue
```

Examples simplify understanding.  Below is an example of how to use
the theophylline dataset to estimate the concentration for each
subject after multiple doses.

```{r check-ggplot, include=!requireNamespace("ggplot2"), results="asis"}
cat("ggplot2 is required for this vignette to work correctly.  Please install the ggplot2 library and retry building the vignette.")
```

# Load the data

```{r showtheoph}
## It is always a good idea to look at the data
knitr::kable(head(datasets::Theoph))
```

The columns that we will be interested in for our analysis are conc,
Time, and Subject in the concentration data.

```{r setupconc}
## By default it is groupedData; convert it to a data frame for use
conc_obj <- PKNCAconc(as.data.frame(datasets::Theoph), conc~Time|Subject)
```

# Compute the Superposition from Single-Dose Data to Steady-State

With a simple call, we can have the estimated steady-state
concentration for each subject.  At minimum, the time between dosing
(`tau`) must be provided.

```{r superposition, error=TRUE}
steady_state <- superposition(conc_obj, tau=24)
```

The error noting that the first concentration must be zero is due to
the fact that superposition usually occurs with single-dose data.  If
the first concentration is nonzero, the data are not likely to be
single-dose (or a data error should be fixed).  Let's find the offending data.

```{r findnonzero}
knitr::kable(subset(datasets::Theoph, Time == 0 & conc > 0),
             caption="Nonzero predose measurements",
             row.names=FALSE)
```

For this example, we will assume that these were errors, correct them to zero, and recalculate.

```{r allownonzero}
## Correct nonzero concentrations at time 0 to be BLQ.
theoph_corrected <- as.data.frame(datasets::Theoph)
theoph_corrected$conc[theoph_corrected$Time == 0] <- 0
conc_obj_corrected <- PKNCAconc(theoph_corrected, conc~Time|Subject)

## Calculate the new steady-state concentrations with 24 hour dosing
steady_state <- superposition(conc_obj_corrected, tau=24)
knitr::kable(head(steady_state, n=14),
             caption="Superposition at steady-state")
```

The output is a `r class(steady_state)` including all the grouping factors as columns, a column for `conc`entration, and a column for `time`.  Time point selection ensures that the beginning and end of the interval are included and that every measured time that contributes to the interval is included.  The points at the beginning and end of the interval are very similar; they are within a tolerance of `r formals(PKNCA:::superposition.numeric)$steady.state.tol` as defined by the `steady.state.tol` argument to superposition.

# Nonstandard Superposition Computations

## Compute the Superposition from Single-Dose Data to a Specific Dose

If simulation to a specific dose is needed, the number of dosing intervals (`n.tau`) can be specified.

```{r UnsteadyState}
## Calculate the unsteady-state concentrations with 24 hour dosing
unsteady_state <- superposition(conc_obj_corrected, tau=24, n.tau=2)
knitr::kable(head(unsteady_state, n=14),
             caption="Superposition before steady-state")
```

## Compute the Superposition from Single-Dose Data with >1 Dose Per Interval

Some dosing intervals are more complex than once per X hours (or days or weeks or...).  To predict more complex dosing with superposition, give the dose times within the interval.  The `dose.times` must all be less than `tau` (otherwise they are not in the interval).

```{r ComplexInterval}
## Calculate the new steady-state concentrations with 24 hour dosing
complex_interval_steady_state <- superposition(conc_obj_corrected, tau=24, dose.times=c(0, 2, 4))
knitr::kable(head(complex_interval_steady_state, n=10),
             caption="Superposition at steady-state with complex dosing")
```
```{r ComplexInterval-visualization, eval=requireNamespace("ggplot2")}
ggplot(complex_interval_steady_state,
       aes(y=conc, x=time, colour=Subject)) +
  geom_line()
```

With this more complex dosing interval, the number of time points estimated increases.  The next section describes the selection of time points.

### Show the Curve to Steady-State

To determine the concentration curve to get to steady-state, you can give all the dose times considered required to get to steady-state.  To do this, specify tau as the total time to steady-state, specify `n.tau` as `1` to indicate that only one round of dosing should be administered.

This command does not technically go to steady-state; if the `dose.times` are not sufficiently long to reach steady-state, it only goes for as many doses as requested.

```{r to_steady_state}
up_to_steady_state <- superposition(conc_obj_corrected,
                                    tau=4*24,
                                    n.tau=1,
                                    dose.times=seq(0, 3*24, by=12))
```
```{r to_steady_state-visualization, eval=requireNamespace("ggplot2")}
ggplot(up_to_steady_state, aes(x=time, y=conc, colour=Subject)) +
  geom_line()
```

# Time Point Selection and Addition

Superposition is often used to estimate NCA parameters with nonparametric methods.  To ensure that estimated parameters are as accurate as possible (especially $C_{max}$), each dose has every post-dose time point included.  Specifically, each dose will have the following times:

* 0 (zero) and `tau`,
* The time of each dose (the `dose.times` argument)
* Every value from the time column of the data modulo `tau` (shifting the time for each measurement to be within the dosing interval) repeated for each dose, and
* each time from the `additional.times` argument.

How the number of time points increases can be seen by comparing the time points for subject 1 in the steady-state single dosing and the complex dosing examples above.

```{r time-point-selection}
steady_state$time[steady_state$Subject == 1]
sum(steady_state$Subject == 1)
complex_interval_steady_state$time[complex_interval_steady_state$Subject == 1]
sum(complex_interval_steady_state$Subject == 1)
```

# Interpolation and Extrapolation Methods

The interpolation and extrapolation methods align with those used for calculating the AUC.  By default, interpolation uses the `PKNCA.options` selection for `"auc.method"` and extrapolation follows the curve of $AUC_{inf}$.  These can be modified with the `interp.method` and `extrap.method` arguments.
