---
title: "Quick Start Guide"
author: "Wenchuan Guo and Bob Zhong"
date: '`r Sys.Date()`'
output:
  html_document:
    fig_height: 6
    fig_width: 7
    highlight: tango
    theme: united
  pdf_document: null
vignette: >
  %\VignetteIndexEntry{Quick Start Guide}
  %\VignetteEngine{knitr::rmarkdown}
---

This guide introduces the basic workflow of `tsdf`. For additional details, see the documentation for individual functions.

## Installation
Install the package from R with:

```{r, eval=FALSE}
install.packages("tsdf")
```

Then load the package:

```{r}
library(tsdf)
```

The remaining sections give short examples of the main functions.

## Zhong's 2-/3-stage Phase II designs
To calculate Zhong's two- or three-stage design, specify the left-side type I error (`alpha1`), right-side type I error (`alpha2`), type II error (`beta`), minimal response rate (`pc`), and postulated response rate (`pe`). The `stage` argument should be set to `2` or `3`.

The following example computes a two-stage design:

```{r}
# type I errors
alpha1 <- 0.15
alpha2 <- 0.10

# type II error
beta <- 0.15

# response rates
pc <- 0.25
pe <- pc + 0.20

# two-stage design
out <- opt.design(alpha1, alpha2, beta, pc, pe, stage = 2)
```

`out` is an object of class `opt.design`. The `print` method shows the recommended design and its operating characteristics:

```{r}
print(out)
```

Alpha-spending methods are available for both two- and three-stage designs. `opt.design()` uses the Hwang-Shih-DeCani spending function, with `sf.param` controlling the shape of the spending rule. For two-stage designs, the default is `NULL`, which means no alpha-spending is used. For three-stage designs, the default is `4`. For example, to use a Pocock-like spending function, set `sf.param = 1`:

```{r, eval=FALSE}
opt.design(alpha1, alpha2, beta, pc, pe, stage = 2, sf.param = 1)
```

## Decision table for Phase I dose-finding
`dec.table()` generates a decision table for a three-stage dose-finding design. `alpha.l` (left side), `alpha.r` (right side), and `alpha.u` (right-side type I error for `"DU"`, usually smaller than `alpha.r`) control the decision boundaries. `pt` is the target toxicity level and may be given as either a single value or an interval.

This procedure also supports alpha-spending through the `sf.param` argument, which has the same interpretation as in `opt.design()`. The default is `4`.

```{r}
# cohort sizes at each stage
n <- rep(3, 3)

# type I errors
alpha.l <- 0.6
alpha.r <- 0.4
alpha.u <- 0.2

# target toxicity
pt <- 0.3

# generate the decision table
out <- dec.table(alpha.l, alpha.r, alpha.u, pt, n)
```

`out` is an object of class `dec.table` that contains the decision table, realized error rates, and input settings. In most cases, it is better to use the provided S3 methods than to extract components manually.

View the decision table with:

```{r}
print(out)
```

Plot the decision boundaries with:

```{r}
plot(out)
```

## Dose-finding simulations
`dec.sim()` and `sl.sim()` run dose-finding simulations from a user-supplied decision table. To run a simulation, provide a decision table, the true toxicity probabilities for each dose level, the starting dose level (default: the lowest dose), and the number of simulated trials (default: `1000`).

`dec.sim()` runs a single scenario. `sl.sim()` runs a list of scenarios stored in a `.csv` or `.txt` file.

The simulation functions expect the decision table to be a matrix- or data-frame-like object with sample sizes as column names. If you start from `dec.table()`, convert `out$table` before passing it to the simulation functions:

```{r}
# true toxicity probabilities
truep <- c(0.3, 0.45, 0.5, 0.6)

# generate a decision table
dt <- dec.table(0.6, 0.4, 0.2, 0.3, c(3, 3, 3))

# convert the table object to a plain matrix for simulation
sim_table <- matrix(
  as.character(dt$table),
  nrow = nrow(dt$table),
  dimnames = dimnames(dt$table)
)

# run one simulation scenario
out1 <- dec.sim(truep, sim_table, start.level = 2, nsim = 1000)
```

The package also includes a sample scenario list:

```{r}
test.file <- system.file("extdata", "testS.csv", package = "tsdf")
```

Run simulations across all scenarios with:

```{r}
out2 <- sl.sim(sim_table, test.file)
```

`out1` is an object of class `dec.sim`. When the scenario file contains more than one scenario, `out2` has class `c("sl.sim", "dec.sim")`. Summary and plot methods are available for these objects. For example, the following command reports commonly used summary statistics:

```{r}
# target toxicity for each scenario
pt <- c(0.3, 0.4)
summary(out2, pt)
```

There are four plot types for a `dec.sim` object. The `s` argument selects the scenario to display, and `pt` gives the target toxicity for each scenario. See `?plot.dec.sim` for details:

```{r}
# scenario information (true toxicity)
plot(out2, s = 2, pt = c(0.3, 0.4), type = "s")

# probability of selecting each dose as the MTD
plot(out2, s = 2, pt = c(0.3, 0.4), type = "prob")

# average number of patients treated at each dose
plot(out2, s = 2, pt = c(0.3, 0.4), type = "np")

# average number of DLTs at each dose
plot(out2, s = 2, pt = c(0.3, 0.4), type = "dlt")
```

To display all plot types in a single figure, run:

```{r fig.height = 8}
plot(out2, pt = c(0.3, 0.4), type = "all", cex = 0.7)
```

## Scenario list and customized table format
The `.csv` or `.txt` files used by `sl.sim()` look like this:

```{r echo=FALSE, results='asis'}
sl <- system.file("extdata", "testS.csv", package = "tsdf")
knitr::kable(read.table(sl, header = TRUE, sep = ","))
```

This example is stored in `inst/extdata/testS.csv` and can be located with `system.file()`. The file should include:

- `Start Dose`: the starting dose level.
- `N Trials`: the number of simulated trials.
- `Dose*`: the true toxicity probability at each dose level.

If scenarios contain different numbers of dose levels, the raw file does not need explicit `NA` values; blank cells are sufficient.

Both `dec.sim()` and `sl.sim()` also support user-supplied decision tables. The table can be a `matrix`, `data.frame`, or similar rectangular object in R. The user is responsible for ensuring that the table is a valid dose-finding decision table. In particular, the column names should be the actual cumulative sample sizes rather than the default names created by `read.table()`, such as `X.*` or `V.*`.

For example, the following code reads the sample decision table included in the package:

```{r, warning=FALSE}
table.file <- system.file("extdata", "decTable.csv", package = "tsdf")
dec <- read.csv(table.file, row.names = 1, check.names = FALSE)
colnames(dec)
```

After importing the table, it should have the following format:

```{r, echo=FALSE}
knitr::kable(dec)
```
