---
title: "Introduction to simFastBOIN"
author: "Gosuke Homma"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to simFastBOIN}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  message = FALSE,  # Suppress messages
  warning = FALSE   # Suppress warnings
)
```

## Overview

**simFastBOIN** provides fast and efficient simulation tools for Bayesian Optimal Interval (BOIN) designs in Phase I clinical trials. The package enables researchers to evaluate operating characteristics and design performance across different dose-toxicity scenarios.

### Key Features

- **High Performance**: Vectorized implementation (2-5x faster than traditional approaches)
- **BOIN Compatible**: Results match BOIN package within <0.5% across all scenarios
- **User-Friendly**: Simplified API with automatic decision table generation
- **Flexible**: Multiple safety stopping rules and customizable design parameters
- **Multi-Scenario Support**: Evaluate multiple dose-toxicity scenarios simultaneously
- **Publication-Ready Output**: Professional table formatting options

## Installation

```{r eval=FALSE}
# Install from GitHub
devtools::install_github("gosukehommaEX/simFastBOIN")
```

## Basic Usage

```{r setup}
library(simFastBOIN)
```

### Running a Basic BOIN Simulation

The most basic simulation requires only a few parameters:

```{r basic-simulation, message=FALSE}
# Define design parameters
target <- 0.30  # Target DLT rate (30%)
p_true <- c(0.10, 0.25, 0.40, 0.55, 0.70)  # True toxicity probabilities

# Run simulation (progress messages suppressed)
result <- sim_boin(
  n_trials = 1000,
  target = target,
  p_true = p_true,
  n_cohort = 10,
  cohort_size = 3,
  seed = 123
)

# Display results
print(result$summary)
```

### Understanding the Output

The summary table contains four key sections:

1. **True Toxicity (%)**: The actual DLT rate at each dose
2. **MTD Selected (%)**: Percentage of trials selecting each dose as MTD
3. **Participants Treated (mean)**: Average patient enrollment at each dose
4. **Participants w/ DLTs (mean)**: Average DLT counts at each dose

## BOIN Standard Implementation

For BOIN standard compliance, use the following recommended settings:

```{r boin-standard}
result_standard <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = c(0.10, 0.25, 0.40, 0.55, 0.70),
  n_cohort = 10,
  cohort_size = 3,
  boundMTD = TRUE,              # Conservative MTD selection
  n_earlystop_rule = "with_stay",  # Stop when converged
  seed = 123
)

print(result_standard$summary, scenario_name = "BOIN Standard")
```

### Key Parameters

- **`boundMTD = TRUE`**: Ensures selected MTD's isotonic estimate is below the de-escalation boundary
- **`n_earlystop_rule = "with_stay"`**: Stops trial when dose stays at n_earlystop threshold

## Safety Features

### Extra Safety Stopping

For scenarios with high toxicity uncertainty:

```{r extrasafe}
result_safe <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = c(0.05, 0.10, 0.20, 0.30, 0.45),
  n_cohort = 10,
  cohort_size = 3,
  extrasafe = TRUE,  # Safety monitoring at lowest dose
  offset = 0.05,     # Safety cutoff adjustment
  seed = 123
)

print(result_safe$summary, scenario_name = "With Extra Safety")
```

### Maximum Conservatism

Combining all safety features:

```{r conservative}
result_conservative <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = seq(0.05, 0.45, by = 0.05),
  n_cohort = 20,
  cohort_size = 3,
  extrasafe = TRUE,
  boundMTD = TRUE,
  n_earlystop_rule = "with_stay",
  seed = 123
)

print(result_conservative$summary, scenario_name = "Maximum Conservatism")
```

## Multi-Scenario Simulations

Evaluate multiple dose-toxicity scenarios simultaneously:

```{r multi-scenario, results='hide'}
# Define multiple scenarios
scenarios <- list(
  list(name = "Scenario 1: MTD at DL3", 
       p_true = c(0.05, 0.10, 0.20, 0.30, 0.45)),
  list(name = "Scenario 2: MTD at DL4", 
       p_true = c(0.10, 0.15, 0.25, 0.30, 0.45)),
  list(name = "Scenario 3: All doses safe", 
       p_true = c(0.05, 0.10, 0.15, 0.20, 0.25))
)

# Run multi-scenario simulation
result_multi <- sim_boin_multi(
  scenarios = scenarios,
  target = 0.30,
  n_trials = 1000,
  n_cohort = 10,
  cohort_size = 3,
  seed = 123
)
```

```{r multi-scenario-display}
# Display aggregated results
print(result_multi)
```

## Output Formatting Options

### Percentage Format

Display values as percentages instead of absolute numbers:

```{r percent-format}
print(result$summary, percent = TRUE)
```

### Markdown Table Format

For R Markdown documents:

```{r markdown-format}
print(result$summary, kable = TRUE, kable_format = "pipe")
```

### HTML Format

For web-based reports:

```{r html-format, eval=FALSE}
print(result$summary, kable = TRUE, kable_format = "html")
```

## Accessing Detailed Results

When `return_details = TRUE`, you can access trial-level information:

```{r detailed-results}
result_detailed <- sim_boin(
  n_trials = 100,
  target = 0.30,
  p_true = c(0.10, 0.25, 0.40, 0.55, 0.70),
  n_cohort = 10,
  cohort_size = 3,
  return_details = TRUE,
  seed = 123
)

# Check first trial
trial_1 <- result_detailed$detailed_results[[1]]
cat("Trial 1 MTD:", trial_1$mtd, "\n")
cat("Trial 1 stopping reason:", trial_1$reason, "\n")

# Summary of stopping reasons
stopping_reasons <- table(sapply(result_detailed$detailed_results, 
                                function(x) x$reason))
print(stopping_reasons)
```

## Design Comparison

Compare different safety configurations:

```{r design-comparison}
# Baseline
result_baseline <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = c(0.05, 0.10, 0.20, 0.30, 0.45, 0.60),
  n_cohort = 20,
  cohort_size = 3,
  seed = 123
)

# With boundMTD
result_boundMTD <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = c(0.05, 0.10, 0.20, 0.30, 0.45, 0.60),
  n_cohort = 20,
  cohort_size = 3,
  boundMTD = TRUE,
  seed = 123
)

# Create comparison
comparison <- data.frame(
  Setting = c("Baseline", "boundMTD"),
  Avg_Patients = c(
    result_baseline$summary$avg_total_n_pts,
    result_boundMTD$summary$avg_total_n_pts
  ),
  MTD_Selection_at_DL4 = c(
    result_baseline$summary$mtd_selection_percent[4],
    result_boundMTD$summary$mtd_selection_percent[4]
  )
)

print(comparison)
```

## Performance Benchmarking

simFastBOIN is optimized for speed:

```{r benchmark, eval=FALSE}
# Benchmark with 10,000 trials
system.time({
  result_large <- sim_boin(
    n_trials = 10000,
    target = 0.30,
    p_true = seq(0.05, 0.45, by = 0.05),
    n_cohort = 48,
    cohort_size = 3,
    seed = 123
  )
})
```

Typical performance:
- 1,000 trials: ~0.02 seconds
- 10,000 trials: ~0.25 seconds
- 100,000 trials: ~2.7 seconds

## Advanced Features

### Custom Cohort Sizes

Use variable cohort sizes:

```{r variable-cohort}
result_variable <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = c(0.10, 0.25, 0.40, 0.55, 0.70),
  n_cohort = 10,
  cohort_size = c(1, 3, 3, 3, 3, 3, 3, 3, 3, 3),  # First cohort: 1 patient
  seed = 123
)
```

### Titration Phase

Enable accelerated dose escalation:

```{r titration}
result_titration <- sim_boin(
  n_trials = 1000,
  target = 0.30,
  p_true = c(0.05, 0.10, 0.20, 0.30, 0.45),
  n_cohort = 20,
  cohort_size = 3,
  titration = TRUE,  # Enable titration phase
  seed = 123
)
```

## Stopping Reasons

The package tracks why each trial terminated:

- `"max_cohorts_reached"`: Normal completion
- `"n_earlystop_with_stay"`: Converged at sample size limit
- `"n_earlystop_simple"`: Reached sample size limit (simple rule)
- `"lowest_dose_too_toxic"`: Safety stopping at lowest dose
- `"lowest_dose_eliminated"`: Lowest dose eliminated during trial
- `"max_sample_size_reached"`: Maximum total patients reached

## References

Liu, S. and Yuan, Y. (2015). Bayesian Optimal Interval Designs for Phase I Clinical Trials. *Journal of the Royal Statistical Society: Series C*, 64, 507–523.

## See Also

- `?sim_boin` - Main simulation function
- `?sim_boin_multi` - Multi-scenario simulation
- `?get_boin_boundary` - BOIN boundary calculation
- `?get_boin_decision` - Decision table generation
