---
title: "Univariate goodness-of-fit tests with the multiplier bootstrap"
author:
  - Ivan Kojadinovic
  - Jun Yan
bibliography: references.bib
engine: knitr
format:
  html:
    html-math-method: mathml
vignette: >
  %\VignetteIndexEntry{Univariate goodness-of-fit tests with the multiplier bootstrap}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
---

The `fgof` package provides goodness-of-fit tests for continuous distributions
with parameters estimated from the data. Its `gof.test()` function compares
the empirical cumulative distribution function (CDF) with the fitted CDF.
It uses the multiplier bootstrap by default (`simulation = "mult"`) and also
supports the parametric bootstrap (`simulation = "pb"`)
[@kojadinovic2012goodness].

The usual one-sample p-value from `stats::ks.test()` assumes a fully
specified null distribution. Estimating its parameters from the same data
changes the null distribution of the statistic and invalidates that p-value
[@zeimbekakis2024misuses].

In this vignette, we test whether independent, positive observations follow a
lognormal distribution with unknown log-scale mean and standard deviation.
We use the multiplier bootstrap first, then compare it with the parametric
bootstrap.

## Simulate a lognormal sample

We generate 100 independent observations with `meanlog = 1` and
`sdlog = 0.5`. These values determine the simulation. For the test, we
estimate both parameters from the sample. The sample mean and standard
deviation of `log(x)` provide starting values for maximum likelihood.

```{r}
library(fgof)

set.seed(123)
x <- rlnorm(100, meanlog = 1, sdlog = 0.5)
start <- list(meanlog = mean(log(x)), sdlog = sd(log(x)))
```

## Run the default multiplier test

Use `distr = "lnorm"` to select the lognormal model. The names in `start`
match the parameters of `dlnorm()`. Set `nsim = 199` to generate 199
bootstrap replicates for this example. The multiplier bootstrap uses
derivatives of the fitted CDF and log-density to account for parameter
estimation. This call uses numerical differentiation because we omit
the derivative callbacks.

```{r}
set.seed(456)
fit_mult <- gof.test(x, "lnorm", nsim = 199, start = start)
fit_mult$estimate
rbind(statistic = fit_mult$statistic, p.value = fit_mult$p.value)
```

`estimate` contains the fitted log-scale mean and standard deviation.
The table shows the observed statistics and their bootstrap p-values.
Each statistic compares the empirical and fitted CDFs at a set of points.

| Discrepancy | Quantile grid | Observed values |
|:--|:--:|:--:|
| Largest absolute difference (Kolmogorov–Smirnov) | `ks` | `ksa` |
| Squared differences (Cramér–von Mises) | `cvm` | `cvma` |

For example, the observation-based Kolmogorov–Smirnov p-value is about
`r round(fit_mult$p.value[["ksa"]], 2)`. At the 5% level, this test gives
insufficient evidence against the lognormal model.
Use `gridStat = FALSE` to compute only the observation-based statistics.

## Generate analytical derivatives with `stats::deriv()`

For a positive observation $x$, write $z = (\log x - \mu)/\sigma$, where
$\mu$ and $\sigma$ are `meanlog` and `sdlog`. The CDF is $\Phi(z)$, where
$\Phi$ is the standard normal CDF. The log-density is
$-z^2/2 - \log(\sigma) - \log(x) - \log(2\pi)/2$.

R's `stats::deriv()` generates code that evaluates each expression and
its analytical gradient by applying derivative rules to the expression.
The callbacks extract the gradient matrix, with one row per evaluation
point and columns in parameter order.
[Documentation for `stats::deriv()`](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/deriv.html)

```{r}
parameters <- c("meanlog", "sdlog")
cdf_with_gradient <- stats::deriv(
  ~ pnorm((log(x) - meanlog) / sdlog),
  parameters, function.arg = c("x", parameters)
)
log_density_with_gradient <- stats::deriv(
  ~ -((log(x) - meanlog) / sdlog)^2 / 2 - log(sdlog) - log(x) -
    log(2 * pi) / 2,
  parameters, function.arg = c("x", parameters)
)

cdf_gradient <- function(theta, x) {
  attr(cdf_with_gradient(as.numeric(x), theta[1], theta[2]), "gradient")
}

score <- function(theta, x) {
  attr(log_density_with_gradient(as.numeric(x), theta[1], theta[2]), "gradient")
}

set.seed(456)
fit_analytic <- gof.test(
  x, "lnorm", nsim = 199, start = start,
  derCdfWrtPar = cdf_gradient, derLogPdfWrtPar = score
)

rbind(numerical = fit_mult$p.value, analytical = fit_analytic$p.value)
max(abs(fit_mult$stat.sim - fit_analytic$stat.sim))
```

Resetting the seed uses the same multiplier draws in both fits. Comparing
the simulated statistics directly shows how closely the two derivative
methods agree, even when the discrete bootstrap p-values coincide.

## Run the multiplier bootstrap with RTMB derivatives

With RTMB installed, `RTMB::MakeTape()` records the operations that compute
the CDF or log-density at fixed evaluation points. Its `jacobian()` method
then differentiates those outputs with respect to the fitted parameters.
Use `RTMB::pnorm()` inside the tape so that RTMB can differentiate the
standard normal CDF. [RTMB on CRAN](https://CRAN.R-project.org/package=RTMB)

```{r, eval=requireNamespace("RTMB", quietly = TRUE)}
cdf_gradient_rtmb <- function(theta, points) {
  log_points <- log(as.numeric(points))
  tape <- RTMB::MakeTape(function(par) {
    RTMB::pnorm((log_points - par[1]) / par[2])
  }, theta)
  tape$jacobian(theta)
}

score_rtmb <- function(theta, points) {
  log_points <- log(as.numeric(points))
  tape <- RTMB::MakeTape(function(par) {
    z <- (log_points - par[1]) / par[2]
    -z^2 / 2 - log(par[2]) - log_points - log(2 * pi) / 2
  }, theta)
  tape$jacobian(theta)
}

set.seed(456)
fit_rtmb <- gof.test(
  x, "lnorm", nsim = 199, start = start,
  derCdfWrtPar = cdf_gradient_rtmb, derLogPdfWrtPar = score_rtmb
)

rbind(deriv = fit_analytic$p.value, RTMB = fit_rtmb$p.value)
max(abs(fit_analytic$stat.sim - fit_rtmb$stat.sim))
```

Each callback builds a tape for the evaluation points supplied by
`gof.test()`. This lets the CDF callback evaluate derivatives at both
the observations and the quantile grid. The results compare the RTMB
and `stats::deriv()` runs using the same multiplier draws.

## Run the parametric bootstrap

To compare the two resampling methods, set `simulation = "pb"`. The
parametric bootstrap simulates samples from the fitted lognormal model and
refits the model to each sample.

```{r}
set.seed(789)
fit_pb <- gof.test(x, "lnorm", nsim = 199, start = start,
                   simulation = "pb")
fit_pb$p.value
```

For either bootstrap method, a small p-value indicates that the observed
discrepancy is large relative to the simulated discrepancies. The two
methods use different resampling schemes, so their p-values can differ.
Choose the test statistic before inspecting the p-values. Increase `nsim`
when Monte Carlo variability matters for the decision.

## Test a model with a fixed parameter

To test a lognormal model with known `sdlog = 0.5`, pass
`distr.args = list(sdlog = 0.5)` and include only `meanlog` in `start`.
The fitted model and bootstrap samples then use the same fixed `sdlog`.

See `help("gof.test", package = "fgof")` for the available statistics,
quantile grids, and optimizer controls.

## References

::: {#refs}
:::
