---
title: "Introduction to casebase sampling"
author: "Maxime Turgeon"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    fig_height: 8
    fig_width: 11
    toc: yes
    toc_depth: 4
vignette: >
  %\VignetteIndexEntry{Introduction to casebase sampling}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
bibliography: reference.bib
editor_options: 
  chunk_output_type: console
---

## Methodological details

```{r}
evaluate_vignette <- requireNamespace("eha", quietly = TRUE) && 
    requireNamespace("visreg", quietly = TRUE) && 
    requireNamespace("splines", quietly = TRUE)
knitr::opts_chunk$set(eval = evaluate_vignette)
```


Case-base sampling was proposed by [Hanley and Miettinen, 2009](https://github.com/sahirbhatnagar/casebase/blob/master/references/Hanley_Miettinen-2009-Inter_J_of_Biostats.pdf) as a way to fit smooth-in-time parametric hazard functions via logistic regression. The main idea, which was first proposed by Mantel, 1973 and then later developed by Efron, 1977, is to sample person-moments, i.e. discrete time points along an subject's follow-up time, in order to construct a base series against which the case series can be compared. 

This approach allows the explicit inclusion of the time variable into the model, which enables the user to fit a wide class of parametric hazard functions. For example, including time linearly recovers the Gompertz hazard, whereas including time *logarithmically* recovers the Weibull hazard; not including time at all corresponds to the exponential hazard.

The theoretical properties of this approach have been studied in [Saarela and Arjas, 2015](https://github.com/sahirbhatnagar/casebase/blob/master/references/Saarela_et_al-2015-Scandinavian_Journal_of_Statistics.pdf) and [Saarela, 2015](https://github.com/sahirbhatnagar/casebase/blob/master/references/Saarela-2015-Lifetime_Data_Analysis.pdf).

## Analysis of the `veteran` dataset

The first example we discuss uses the well-known ```veteran``` dataset, which is part of the ```survival``` package. As we can see below, there is almost no censoring, and therefore we can get a good visual representation of the survival function:

```{r}
set.seed(12345)
library(casebase)
library(survival)
data(veteran)
table(veteran$status)

evtimes <- veteran$time[veteran$status == 1]
hist(evtimes, nclass = 30, main = '', xlab = 'Survival time (days)', 
     col = 'gray90', probability = TRUE)
tgrid <- seq(0, 1000, by = 10)
lines(tgrid, dexp(tgrid, rate = 1.0/mean(evtimes)), 
      lwd = 2, lty = 2, col = 'red')
```

As we can see, the empirical survival function resembles an exponential distribution.

We will first try to estimate the hazard function parametrically using some well-known regression routines. But first, we will reformat the data slightly.

```{r}
veteran$prior <- factor(veteran$prior, levels = c(0, 10), labels = c("no","yes"))
veteran$celltype <- factor(veteran$celltype, 
                           levels = c('large', 'squamous', 'smallcell', 'adeno'))
veteran$trt <- factor(veteran$trt, levels = c(1, 2), labels = c("standard", "test"))
```

Using the ```eha``` package, we can fit a Weibull form, with different values of the shape parameter. For `shape = 1`, we get an exponential distribution:

```{r}
library(eha)
y <- with(veteran, Surv(time, status))

model1 <- weibreg(y ~ karno + diagtime + age + prior + celltype + trt, 
                  data = veteran, shape = 1)
summary(model1)
```

If we take `shape = 0`, the shape parameter is estimated along with the regression coefficients:

```{r}
model2 <- weibreg(y ~ karno + diagtime + age + prior + celltype + trt, 
                  data = veteran, shape = 0)
summary(model2)
```

Finally, we can also fit a Cox proportional hazard:

```{r}
model3 <- coxph(y ~ karno + diagtime + age + prior + celltype + trt, 
                data = veteran)
summary(model3)
```

As we can see, all three models are significant, and they give similar information: ```karno``` and ```celltype``` are significant predictors, both treatment is not.

The method available in this package makes use of *case-base sampling*. That is, person-moments are randomly sampled across the entire follow-up time, with some moments corresponding to cases and others to controls. By sampling person-moments instead of individuals, we can then use logistic regression to fit smooth-in-time parametric hazard functions. See the previous section for more details.

First, we will look at the follow-up time by using population-time plots:

```{r}
# create popTime object
pt_veteran <- popTime(data = veteran)

class(pt_veteran)

# plot method for objects of class 'popTime'
plot(pt_veteran)
```

Population-time plots are a useful way of visualizing the total follow-up experience, where individuals appear on the y-axis, and follow-up time on the x-axis; each individual's follow-up time is represented by a gray line segment. For convenience, we have ordered the patients according to their time-to-event, and each event is represented by a red dot. The censored observations (of which there is only a few) correspond to the grey lines which do not end with a red dot.

Next, we use case-base sampling to fit a parametric hazard function via logistic regression. First, we will include time as a linear term; as noted above, this corresponds to an Gompertz hazard.

```{r}
model4 <- fitSmoothHazard(status ~ time + karno + diagtime + age + prior +
             celltype + trt, data = veteran, ratio = 100)
summary(model4)
```

Since the output object from ```fitSmoothHazard``` inherits from the ```glm``` class, we see a familiar result when using the function ```summary```. We can quickly visualize the conditional association between each predictor and the hazard function using the `plot` method for objects that are fit with `fitSmoothHazard`. Specifically, if $x$ is the predictor of interest, $h$ is the hazard function, and $\mathbf{x_{-j}}$ the other predictors in the model, the conditional association plot represents the relationship $f(x) = \mathbb{E}(h|x, \mathbf{x_{-j}})$. By default, the other terms in the model ($\mathbf{x_{-j}}$) are set to their median if the term is numeric or the most common category if the term is a factor. Further details of customizing these plots are given in the `Plot Hazards and Hazard Ratios` vignette.

```{r, results='show', R.options=list(max.print=1)}
library(visreg)
plot(model4, 
     hazard.params = list(alpha = 0.05))
```


The main purpose of fitting smooth hazard functions is that it is then relatively easy to compute absolute risks. For example, we can use the function ```absoluteRisk``` to compute the mean absolute risk at 90 days, which can then be compared to the empirical measure.

```{r}
absRisk4 <- absoluteRisk(object = model4, time = 90)
mean(absRisk4)

ftime <- veteran$time
mean(ftime <= 90)
```

We can also fit a Weibull hazard by using a logarithmic term for time:

```{r}
model5 <- fitSmoothHazard(status ~ log(time) + karno + diagtime + age + prior +
             celltype + trt, data = veteran, ratio = 100)
summary(model5)
```

With case-base sampling, it is straightforward to fit a semi-parametric hazard function using splines, which can then be used to estimate the mean absolute risk.

```{r}
# Fit a spline for time
library(splines)
model6 <- fitSmoothHazard(status ~ bs(time) + karno + diagtime + age + prior +
             celltype + trt, data = veteran, ratio = 100)
summary(model6)

str(absoluteRisk(object = model6, time = 90))
```

As we can see from the summary, there is little evidence that splines actually improve the fit. Moreover, we can see that estimated individual absolute risks are essentially the same when using either a linear term or splines:

```{r}
linearRisk <- absoluteRisk(object = model4, time = 90, newdata = veteran)
splineRisk <- absoluteRisk(object = model6, time = 90, newdata = veteran)

plot.default(linearRisk, splineRisk,
     xlab = "Linear", ylab = "Splines", pch = 19)
abline(a = 0, b = 1, lty = 2, lwd = 2, col = 'red')
```

These last three models give similar information as the first three, i.e. the main predictors for the hazard are ```karno``` and ```celltype```, with treatment being non-significant. Moreover, by explicitly including the time variable in the formula, we see that it is not significant; this is evidence that the true hazard is exponential. 

Finally, we can look at the estimates of the coefficients for the Cox model, as well as the last three models (CB stands for "case-base"):

```{r, echo = FALSE}
table_coef <- cbind(coefficients(model3), 
                    coefficients(model4)[-(1:2)], 
                    coefficients(model5)[-(1:2)], 
                    coefficients(model6)[-(1:4)])
knitr::kable(table_coef, format = "html", digits = 4,
             col.names = c("Cox model", 
                           "CB linear",
                           "CB log-linear",
                           "CB splines"))
```



## Cumulative Incidence Curves

Here we show how to calculate the cumulative incidence curves for a specific risk profile using the following equation:

$$ CI(x, t) = 1 - exp\left[ - \int_0^t h(x, u) \textrm{d}u \right] $$ 
where \\( h(x, t) \\) is the hazard function, \\( t \\) denotes the numerical value (number of units) of a point in prognostic/prospective time and \\( x \\) is the realization of the vector \\( X \\) of variates based on the patient's profile and intervention (if any).

We compare the cumulative incidence functions from the fully-parametric fit using case base sampling, with those from the Cox model:

```{r}
# define a specific covariate profile
new_data <- data.frame(trt = "test", 
                       celltype = "adeno", 
                       karno = median(veteran$karno), 
                       diagtime = median(veteran$diagtime),
                       age = median(veteran$age),
                       prior = "no")

# calculate cumulative incidence using casebase model
smooth_risk <- absoluteRisk(object = model4, 
                            time = seq(0,300, 1), 
                            newdata = new_data)

cols <- c("#8E063B","#023FA5")

# cumulative incidence function for the Cox model
plot(survfit(model3, newdata = new_data),
     xlab = "Days", ylab = "Cumulative Incidence (%)", fun = "event",
     xlim = c(0,300), conf.int = F, col = cols[1], 
     main = sprintf("Estimated Cumulative Incidence (risk) of Lung Cancer\ntrt = test, celltype = adeno, karno = %g,\ndiagtime = %g, age = %g, prior = no", median(veteran$karno), median(veteran$diagtime), 
                    median(veteran$age)))

# add casebase curve with legend
plot(smooth_risk, add = TRUE, col = cols[2], gg = FALSE)
legend("bottomright", 
       legend = c("semi-parametric (Cox)", "parametric (casebase)"), 
       col = cols,
       lty = c(1, 1), 
       bg = "gray90")
```

Note that by default, `absoulteRisk` calculated the cumulative incidence. Alternatively, you can calculate the survival curve by specifying `type = 'survival'` in the call to `absoulteRisk`:

```{r}
smooth_risk <- absoluteRisk(object = model4, 
                            time = seq(0,300, 1), 
                            newdata = new_data, 
                            type = "survival")

plot(survfit(model3, newdata = new_data),
     xlab = "Days", ylab = "Survival Probability (%)", 
     xlim = c(0,300), conf.int = F, col = cols[1], 
     main = sprintf("Estimated Survival Probability of Lung Cancer\ntrt = test, celltype = adeno, karno = %g,\ndiagtime = %g, age = %g, prior = no", median(veteran$karno), median(veteran$diagtime), 
                    median(veteran$age)))

# add casebase curve with legend
plot(smooth_risk, add = TRUE, col = cols[2], gg = FALSE)
legend("topright", 
       legend = c("semi-parametric (Cox)", "parametric (casebase)"), 
       col = cols,
       lty = c(1, 1), 
       bg = "gray90")
```


## Session information

```{r echo=FALSE, eval=TRUE}
print(sessionInfo(), locale = F)
```

## References

<ol>
<li>
<p>Efron, Bradley. 1977. "The Efficiency of Cox's Likelihood Function for Censored Data." <em>Journal of the American Statistical Association</em> 72 (359). Taylor &amp; Francis Group: 557–65.</p>
</li>
<li>
<p>Hanley, James A, and Olli S Miettinen. 2009. "Fitting Smooth-in-Time Prognostic Risk Functions via Logistic Regression." <em>The International Journal of Biostatistics</em> 5 (1).</p>
</li>
<li>
<p>Mantel, Nathan. 1973. "Synthetic Retrospective Studies and Related Topics." <em>Biometrics</em>. JSTOR, 479–86.</p>
</li>
<li>
<p>Saarela, Olli. 2015. "A Case-Base Sampling Method for Estimating Recurrent Event Intensities." <em>Lifetime Data Analysis</em>. Springer, 1–17.</p>
</li>
<li>
<p>Saarela, Olli, and Elja Arjas. 2015. "Non-Parametric Bayesian Hazard Regression for Chronic Disease Risk Assessment." <em>Scandinavian Journal of Statistics</em> 42 (2). Wiley Online Library: 609–26.</p>
</li>
<li>
<p>Scrucca, L, A Santucci, and F Aversa. 2010. "Regression Modeling of Competing Risk Using R: An in Depth Guide for Clinicians." <em>Bone Marrow Transplantation</em> 45 (9). Nature Publishing Group: 1388–95.</p>
</li>
<li>
<p>Kalbfleisch, John D., and Ross L. Prentice. The statistical analysis of failure time data. Vol. 360. John Wiley & Sons, 2011.</p>
</li>
<li>
<p>Cox, D. R. "Regression models and life tables." <em>Journal of the Royal Statistical Society</em> 34 (1972): 187-220.</p>
</li>
</ol>
