---
title: "Introduction to PPMiss"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to PPMiss}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6.5,
  fig.height = 4
)
```

## Overview

**PPMiss** implements the copula-based estimator for univariate long-range
dependent processes introduced in Pumi, Prass, and Lopes (2024). The
methodology exploits the asymptotic relationship between a stationary
process's autocovariance decay and the parameter $\theta_h$ of a parametric
bivariate copula $C_{\theta_h}$ associated with lagged pairs
$(X_t, X_{t+h})$.

A key practical advantage of this estimator is that it handles missing values
(`NA`) and irregular gaps directly—by forming only complete lagged pairs
$(X_t, X_{t+h})$—without requiring prior imputation. As shown in Pumi, Choque
Ulloa, and Prass (2023), the estimator remains competitive even when up to
70% of the observations are missing.

### Estimator formulation

Let $C_\theta$ be a one-parameter bivariate copula such that
$\lim_{\theta \to a} C_\theta(u, v) = uv$ (the independence copula), and
define the constant

$$
K_1 = \int_0^1 \int_0^1 \frac{1}{l(u)\, l(v)}
  \lim_{\theta \to a} \frac{\partial C_\theta(u, v)}{\partial \theta}
  \,du\,dv,
$$

where $l(x) := F'(F^{(-1)}(x))$ and $F$ is the marginal distribution function
of the process. Given estimates $\hat\theta_h$ over a set of positive integer
lags $\mathcal{H}$ (by default $\mathcal{H} = \{s, s + 1, \dots, m\}$), the
long-memory parameter $d \in (-0.5, 0.5)$ is estimated by

$$
\hat d = \operatorname*{argmin}_{|d| < 0.5}
  \sum_{h \in \mathcal{H}}
  \left|
    \frac{\hat K_1}{\hat\sigma^2}(\hat\theta_h - a)
    - \frac{\Gamma(1 - d)}{\Gamma(d)} h^{2d - 1}
  \right|^r,
  \quad r > 0,
$$

where $\hat\sigma^2$ is the sample variance of the observed values and
$\hat K_1$ is estimated via `k1fun()`.

### Built-in copulas

**PPMiss** exports four copula objects (from the **copula** package) together
with their analytical derivative limits at $a = 0$:

| Copula object | Derivative limit (`dCdtheta`) | Independence ($a$) | Bounds for `"Brent"` |
| :--- | :--- | :---: | :---: |
| `gauss` | `dCtheta_gauss` | `0` | `[-1, 1]` |
| `frank` | `dCtheta_frank` | `0` | e.g., `[-100, 100]` |
| `amh` | `dCtheta_amh` | `0` | `[-1, 1]` |
| `fgm` | `dCtheta_fgm` | `0` | `[-1, 1]` |

## Simulating an ARFIMA process

The package includes `arfima.coefs()`, a Fortran-backed routine that computes
the infinite-order moving-average coefficients $c_k$ ($k = 0, \dots, \text{trunc}$)
of an $\mathrm{ARFIMA}(p, d, q)$ model:

```{r simulate}
library(PPMiss)

# First 6 MA coefficients of an ARFIMA(1, 0.3, 1) process
arfima.coefs(ar = -0.2, ma = 0.4, d = 0.3, trunc = 5)

# Simulate an ARFIMA(0, 0.25, 0) series of length n = 400
set.seed(123)
trunc <- 1000
n <- 400
cks <- arfima.coefs(d = 0.25, trunc = trunc)
eps <- rnorm(trunc + n)
x <- sapply(seq_len(n), function(t) sum(cks * rev(eps[t:(t + trunc)])))

# Create a version with 30% missing observations
xt <- x
xt[sample(seq_len(n), size = round(0.30 * n))] <- NA
```

```{r plot-series}
op <- par(mfrow = c(2, 1), mar = c(3, 4, 2, 1))
plot.ts(x, main = "Complete ARFIMA(0, 0.25, 0) series", ylab = expression(X[t]))
plot.ts(xt, main = "Same series with 30% missing values", ylab = expression(X[t]))
par(op)
```

## Estimating $d$ on complete and missing data

We can fit all four built-in copulas to both the complete series `x` and the
incomplete series `xt` using `d.fit()`. Note that the Frank copula parameter
has unbounded support $(-\infty, \infty)$, so finite bounds (such as
`theta.lower = -100, theta.upper = 100`) are supplied for the `"Brent"`
optimizer:

```{r fit-copulas}
fit_all <- function(series, s = 1, m = 15, empirical = TRUE) {
  c(
    GAUSS = d.fit(
      series, copula = gauss, dCdtheta = dCtheta_gauss,
      s = s, m = m, empirical = empirical
    ),
    FRANK = d.fit(
      series, copula = frank, dCdtheta = dCtheta_frank,
      theta.lower = -100, theta.upper = 100,
      s = s, m = m, empirical = empirical
    ),
    AMH = d.fit(
      series, copula = amh, dCdtheta = dCtheta_amh,
      s = s, m = m, empirical = empirical
    ),
    FGM = d.fit(
      series, copula = fgm, dCdtheta = dCtheta_fgm,
      s = s, m = m, empirical = empirical
    )
  )
}

res_complete <- fit_all(x)
res_missing  <- fit_all(xt)

knitr::kable(
  rbind(Complete = res_complete, `Missing (30%)` = res_missing),
  digits = 3,
  caption = "Estimated long-memory parameter (true d = 0.25)."
)
```

### Empirical vs. Gaussian marginals

By default (`empirical = TRUE`), `d.fit()` computes pseudo-observations via
`copula::pobs()`, estimates the marginal density $F'$ with `kdens()`, and uses
sample quantiles for $F^{(-1)}$. Setting `empirical = FALSE` uses Gaussian
marginals instead:

```{r empirical-vs-gaussian}
d_emp <- d.fit(xt, s = 1, m = 15, empirical = TRUE)
d_gau <- d.fit(xt, s = 1, m = 15, empirical = FALSE)
c(Empirical = d_emp, Gaussian = d_gau)
```

You can also inspect the kernel density estimate `kdens()` and the constant
$K_1$ via `k1fun()` directly:

```{r kdens-k1}
x_obs <- xt[!is.na(xt)]
dfun <- kdens(x_obs)

hist(
  x_obs, probability = TRUE, breaks = 20, col = "grey90", border = "white",
  main = "Kernel density spline estimate (kdens)", xlab = "x"
)
curve(dfun, add = TRUE, col = "steelblue", lwd = 2)

c(
  K1_empirical = k1fun(dCtheta_gauss, fun = dfun, data = x_obs, empirical = TRUE),
  K1_gaussian  = k1fun(
    dCtheta_gauss, fun = NULL, data = NULL,
    empirical = FALSE, mean = mean(x_obs), sd = sd(x_obs)
  )
)
```

## Arbitrary lags and `theta.fit()`

By default, `d.fit()` and `theta.fit()` evaluate all consecutive lags
`s:m`. When you want to target specific (possibly non-contiguous) lags, pass
an integer vector via `lags`:

```{r arbitrary-lags}
my_lags <- c(1, 2, 4, 8, 12, 16)

# Estimate copula parameters theta_h alone
th <- theta.fit(xt, lags = my_lags)
th
```

```{r plot-thetas}
plot(
  my_lags, th, type = "b", pch = 19, col = "steelblue",
  xlab = "Lag (h)", ylab = expression(hat(theta)[h]),
  main = "Estimated Gaussian copula parameter across arbitrary lags"
)
abline(h = 0, lty = 2, col = "grey50")
```

### Reusing precomputed `thetas` and `full.output = TRUE`

If you already computed `th <- theta.fit(...)`, pass `thetas = th` to `d.fit()`
to skip the copula optimization step—for example, to compare different
Minkowski exponents `r` instantaneously. When `s`, `m`, and `lags` are omitted,
`d.fit()` infers the lags automatically from `names(th)`:

```{r reuse-thetas}
c(
  r1 = d.fit(xt, thetas = th, r = 1),
  r2 = d.fit(xt, thetas = th, r = 2)
)
```

Conversely, if you want both $\hat d$ and $\hat\theta_h$ in a single call, set
`full.output = TRUE`:

```{r full-output}
fit_full <- d.fit(xt, lags = my_lags, full.output = TRUE)
str(fit_full)
```

### Handling lags with no complete pairs (`na.action`)

When missingness occurs in blocks or periodic patterns, some lags may have
zero complete pairs $(X_t, X_{t+h})$. Instead of aborting, `theta.fit()` and
`d.fit()` emit a warning and handle those lags according to `na.action`:

- `na.action = "omit"` *(default)*: returns `NA` in `theta.fit()` and omits
  missing lags from the objective sum in `d.fit()`.
- `na.action = "approx"`: linearly interpolates missing $\hat\theta_h$ over
  the actual lag positions via `zoo::na.approx(..., x = lags, rule = 2)`.

```{r na-action}
# Keep only even time indices: odd lags have no complete pairs
x_even <- rep(NA_real_, n)
x_even[seq(2, n, by = 2)] <- x[seq(2, n, by = 2)]

th_omit <- suppressWarnings(
  theta.fit(x_even, lags = 1:6, na.action = "omit")
)
th_approx <- suppressWarnings(
  theta.fit(x_even, lags = 1:6, na.action = "approx")
)

rbind(omit = th_omit, approx = th_approx)

c(
  d_omit   = suppressWarnings(d.fit(x_even, lags = 1:6, na.action = "omit")),
  d_approx = suppressWarnings(d.fit(x_even, lags = 1:6, na.action = "approx"))
)
```

## Using a custom copula

Any one-parameter bivariate copula from the **copula** package can be used
with `d.fit()` by supplying `copula`, its derivative limit `dCdtheta`, and the
independence value `a`. For example, the Plackett copula attains independence
at $a = 1$ with derivative limit
$\lim_{\theta \to 1} \frac{\partial C_\theta(u, v)}{\partial \theta} = uv(1 - u)(1 - v)$:

```{r custom-copula}
plackett <- copula::plackettCopula()
dCtheta_plackett <- function(u, v) u * v * (1 - u) * (1 - v)

d.fit(
  xt = xt,
  copula = plackett,
  dCdtheta = dCtheta_plackett,
  theta.lower = 0.01,
  theta.upper = 50,
  theta.start = 1.5,
  a = 1,
  lags = my_lags
)
```

## References

- Pumi, G., Prass, T. S., & Lopes, S. R. C. (2024). A novel copula-based
  approach for parametric estimation of univariate time series through its
  covariance decay. *Statistical Papers*, 65(2), 1041–1063.
  <https://doi.org/10.1007/s00362-023-01418-z>
- Pumi, G., Choque Ulloa, G., & Prass, T. S. (2023). Estimation of long-range
  dependent models with missing data: to impute or not to impute?
  *arXiv preprint*. <https://doi.org/10.48550/arXiv.2303.04754>
