---
title: "Gaussian AR(1): Hermite eigenfunctions and mixing"
output:
  html_document:
    toc: true
    code_folding: show
---

# Gaussian AR(1) chain

Consider

\[
\theta_{t+1}
=
a\theta_t+\sqrt{1-a^2}\,Z_{t+1},
\qquad
Z_{t+1}\overset{\mathrm{iid}}{\sim}N(0,1),
\qquad |a|<1.
\]

The stationary distribution is

\[
\pi=N(0,1).
\]

Starting from \(\theta_0=\theta^{(0)}\),

\[
\theta_t\mid\theta_0=\theta^{(0)}
\sim
N\left(a^t\theta^{(0)},1-a^{2t}\right).
\]

The normalized probabilists' Hermite polynomials are eigenfunctions of the transition operator:

\[
\phi_k(\theta)=\frac{H_k(\theta)}{\sqrt{k!}},
\qquad
P\phi_k=a^k\phi_k.
\]
 The first four polynomials look like:
\[ \begin{aligned} \phi_1(\theta) &= \theta, \\[0.3em] \phi_2(\theta) &= \frac{\theta^2-1}{\sqrt{2}}, \\[0.3em] \phi_3(\theta) &= \frac{\theta^3-3\theta}{\sqrt{6}}, \\[0.3em] \phi_4(\theta) &= \frac{\theta^4-6\theta^2+3}{\sqrt{24}}. \end{aligned} \]



Hence, in stationarity,

\[
\operatorname{Corr}\{\phi_k(\theta_t),\phi_k(\theta_{t+\ell})\}
=
a^{k\ell}.
\]

This notebook examines orders \(k=1,2,4,8\). Change `a` in the setup chunk to compare rapid, slow, or alternating convergence.

```{r setup}
set.seed(4021)

# Main controls
a <- 0.90                 # Must satisfy abs(a) < 1
B <- 10000                # Number of retained stationary draws
burn <- 2000              # Initial draws discarded before the displayed chain
lag_max <- 50             # Maximum lag in ACF plots
theta0 <- 8               # Dispersed initial value
orders <- c(1, 2, 4, 8)

stopifnot(abs(a) < 1, B > 1, burn >= 0)
```

# Simulation

```{r functions}
simulate_ar1 <- function(n, a, theta0 = 0) {
  theta <- numeric(n)
  theta[1] <- theta0

  if (n >= 2) {
    for (t in 2:n) {
      theta[t] <- a * theta[t - 1] + sqrt(1 - a^2) * rnorm(1)
    }
  }

  theta
}

# Probabilists' Hermite polynomial H_k(theta), computed recursively:
# H_0(theta) = 1, H_1(theta) = theta,
# H_{k+1}(theta) = theta H_k(theta) - k H_{k-1}(theta).
hermite_prob <- function(theta, k) {
  stopifnot(k >= 0, k == as.integer(k))

  if (k == 0) return(rep(1, length(theta)))
  if (k == 1) return(theta)

  H_previous <- rep(1, length(theta))
  H_current <- theta

  for (j in 1:(k - 1)) {
    H_next <- theta * H_current - j * H_previous
    H_previous <- H_current
    H_current <- H_next
  }

  H_current
}

normalized_hermite <- function(theta, k) {
  hermite_prob(theta, k) / sqrt(factorial(k))
}
```

The chain is first run from the dispersed value `theta0`. We discard `burn` iterations and analyze the remaining draws.

```{r simulate}
theta_full <- simulate_ar1(B + burn, a = a, theta0 = theta0)
theta <- theta_full[(burn + 1):(burn + B)]

phi <- sapply(orders, function(k) normalized_hermite(theta, k))
colnames(phi) <- paste0("phi_", orders)

c(a = a, initial_value = theta0, retained_draws = B,
  retained_mean = mean(theta), retained_sd = sd(theta))
```

# Convergence from the initial value

The conditional mean satisfies

\[
\operatorname{E}(\theta_t\mid\theta_0)=a^t\theta_0.
\]

For the Hermite mode of order \(k\),

\[
\operatorname{E}\{\phi_k(\theta_t)\mid\theta_0\}
=
a^{kt}\phi_k(\theta_0).
\]

Thus higher-order modes decay faster when \(0<|a|<1\), although their realized traces may contain occasional large values.

```{r initial-convergence, fig.width=10, fig.height=4.5}
show_n <- min(250, length(theta_full))
time <- 0:(show_n - 1)

par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
plot(time, theta_full[seq_len(show_n)], type = "l",
     xlab = "Iteration", ylab = expression(theta[t]),
     main = paste0("AR(1) path, a = ", a))
lines(time, a^time * theta0, col = "red", lwd = 2)
abline(h = 0, lty = 2)
legend("topright", c("Simulated path", "Conditional mean"),
       col = c("black", "red"), lty = c(1, 1), lwd = c(1, 2), bty = "n")

matplot(time,
        sapply(orders, function(k) {
          a^(k * time) * normalized_hermite(theta0, k)
        }),
        type = "l", lty = 1, col = seq_along(orders),
        xlab = "Iteration", ylab = "Conditional mode mean",
        main = "Decay of Hermite modes")
abline(h = 0, lty = 2)
legend("topright", paste("Order", orders),
       col = seq_along(orders), lty = 1, bty = "n")
```

# Trace plots of the Hermite eigenfunctions

Each panel transforms the same retained AR(1) chain using one normalized Hermite polynomial. The horizontal dashed line marks the stationary expectation,

\[
\operatorname{E}_\pi\{\phi_k(\theta)\}=0,
\qquad k\geq1.
\]

```{r hermite-traces, fig.width=10, fig.height=8}
par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))

for (j in seq_along(orders)) {
  k <- orders[j]
  plot(phi[, j], type = "l",
       xlab = "Retained iteration",
       ylab = substitute(phi[k](theta), list(k = k)),
       main = paste("Hermite order", k))
  abline(h = 0, col = "red", lty = 2, lwd = 2)
}
```

The higher-order transformations can be visually dominated by occasional extreme values. A short local view can make the movement easier to inspect.

```{r hermite-traces-zoom, fig.width=10, fig.height=8}
show <- seq_len(min(1000, B))
par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))

for (j in seq_along(orders)) {
  k <- orders[j]
  plot(show, phi[show, j], type = "l",
       xlab = "Retained iteration",
       ylab = substitute(phi[k](theta), list(k = k)),
       main = paste("First", length(show), "draws: order", k))
  abline(h = 0, col = "red", lty = 2, lwd = 2)
}
```

# Autocorrelation

For a stationary Gaussian AR(1) chain, the theoretical autocorrelation of Hermite mode \(k\) is

\[
\rho_k(\ell)=a^{k\ell}.
\]

The plots compare the empirical ACF with this exact result.

```{r hermite-acf, fig.width=10, fig.height=8}
par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))

for (j in seq_along(orders)) {
  k <- orders[j]
  empirical <- as.numeric(acf(phi[, j], lag.max = lag_max,
                              plot = FALSE)$acf)
  lag <- 0:lag_max
  theoretical <- a^(k * lag)

  plot(lag, empirical, type = "h", lwd = 2,
       ylim = range(c(empirical, theoretical, 0)),
       xlab = "Lag", ylab = "Autocorrelation",
       main = paste("Hermite order", k))
  points(lag, empirical, pch = 16, cex = 0.5)
  lines(lag, theoretical, col = "red", lwd = 2)
  abline(h = 0, lty = 2)

  if (j == 1) {
    legend("topright", c("Empirical", "Theoretical"),
           col = c("black", "red"), lty = c(1, 1),
           lwd = 2, bty = "n")
  }
}
```

# Integrated autocorrelation time and ESS

For \(0\leq a<1\), the exact integrated autocorrelation time for mode \(k\) is

\[
\tau_k
=
1+2\sum_{\ell=1}^{\infty}a^{k\ell}
=
\frac{1+a^k}{1-a^k}.
\]

Therefore,

\[
\operatorname{ESS}_k
\approx
B\frac{1-a^k}{1+a^k}.
\]

The same algebra is valid for \(-1<a<0\), although odd-order modes then have alternating autocorrelation and may have \(\tau_k<1\).

```{r hermite-ess}
ess_from_acf <- function(z, lag_max = 1000) {
  rho <- as.numeric(acf(z, lag.max = min(lag_max, length(z) - 1),
                        plot = FALSE)$acf)[-1]

  # Simple truncation at the first negative autocorrelation.
  # This is a teaching estimate, not a modern bulk/tail ESS algorithm.
  first_negative <- which(rho < 0)[1]
  if (!is.na(first_negative)) {
    rho <- rho[seq_len(first_negative - 1)]
  }

  length(z) / (1 + 2 * sum(rho))
}

results <- data.frame(
  order = orders,
  eigenvalue = a^orders,
  theoretical_tau = (1 + a^orders) / (1 - a^orders),
  theoretical_ESS = B * (1 - a^orders) / (1 + a^orders),
  empirical_ESS = vapply(seq_along(orders), function(j) {
    ess_from_acf(phi[, j])
  }, numeric(1))
)

results
```

# Interpretation

All four functions are evaluated on the same AR(1) draws, but they have different eigenvalues:

\[
\lambda_k=a^k.
\]

For positive \(a\), higher-order Hermite modes usually lose autocorrelation faster:

\[
a^{8\ell}<a^{4\ell}<a^{2\ell}<a^\ell,
\qquad \ell>0.
\]

Therefore, convergence, autocorrelation, ESS, and MCSE depend on the quantity \(h(\theta)\) being estimated. Good mixing for \(\theta\) does not automatically imply identical efficiency for nonlinear functions of \(\theta\), although this Gaussian example gives an exact spectral comparison.

# Optional comparison of several values of a

Set `a_values` below to compare theoretical ACF decay without rerunning the main notebook.

```{r compare-a, fig.width=10, fig.height=8}
a_values <- c(0.5, 0.9, 0.99)
lag <- 0:lag_max

par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))
for (k in orders) {
  matplot(lag,
          sapply(a_values, function(a_value) a_value^(k * lag)),
          type = "l", lty = 1, col = seq_along(a_values),
          xlab = "Lag", ylab = "Theoretical autocorrelation",
          main = paste("Hermite order", k))
  abline(h = 0, lty = 2)
  legend("topright", paste("a =", a_values),
         col = seq_along(a_values), lty = 1, bty = "n")
}
```
