---
title: "How rough is too rough for Fourier-based confidence and prediction bands?"
author: "Daniel Koska"
date: 2026-11-24
categories: [functional data, bootstrap, simulation, R]
description: "A small experiment on curve roughness, Fourier reconstruction, and simultaneous coverage using funbootband."
format:
html:
toc: true
toc-depth: 2
code-fold: true
page-layout: article
execute:
warning: false
message: false
---
Yesterday I had one of those "rabbit hole days". Funny thing is, I thought I was already near the bottom of that hole, but turns out that wasn't the case at all. Should have known better.
The latest journey started when I came across the paper by [Liebl and Reimherr (2023)](https://doi.org/10.1093/jrsssb/qkad026) on fast and fair simultaneous confidence bands. As far as I understand it, the article presents a new method for generating simultaneous statistical bands that is both fast (as it avoids resampling) and - maybe more interesting to me - accounts for different degrees of roughness in different regions of a curve domain. This is highly relevant in biomechanical setting, where this occurs all the time. For instance, running trajectories can fluctuate differently during stance (when the foot is on the ground) and flight.
That got me thinking about my own R package [`funbootband`](https://CRAN.R-project.org/package=funbootband). `band()` constructs simultaneous confidence bands for a mean function and prediction bands for a future curve, but it first reconstructs the observed curves using finite Fourier series. How well does that work if the curves become rougher? And, more importantly, does an imperfect reconstruction affect the coverage of the resulting bands?
This post is a small, reproducible experiment rather than a comprehensive simulation study. It is also groundwork for a more systematic evaluation in a forthcoming software/statistics paper. At least I hope so.
```{r echo=FALSE}
#| label: setup
#| include: false
library(funbootband)
library(ggplot2)
library(reshape2)
library(knitr)
# Use these settings for the published post. Reduce M and B for previews.
M <- 400L
B <- 500L
n <- 60L
alpha <- 0.05
T_grid <- 161L
t_grid <- seq(0, 1, length.out = T_grid)
k_values <- c(4L, 10L, 20L, 40L, 65L)
k_coverage <- c(4L, 40L)
stopifnot(max(k_values) <= floor((T_grid - 2) / 2))
set.seed(20261124)
```
### An experiment with controlled roughness
#### Curve simulation
For this experiment I simulate curves as realizations of Gaussian processes with a [Matérn covariance function](https://en.wikipedia.org/wiki/Mat%C3%A9rn_covariance_function) rather than as sums of a few sinusoidal components. This seems like a more interesting test of Fourier reconstruction because the random curves are not generated from the same finite basis that is then used to approximate them.
The Matérn covariance has two parameters that are particularly interesting here: the smoothness parameter $\nu$ and the length scale $\ell$. The former controls the mean-square differentiability of the process, while the latter controls the characteristic distance over which observations remain correlated. Smaller values of $\ell$ generally produce more rapid fluctuations. I use the closed-form Matérn correlations for $\nu=5/2$ and $\nu=3/2$.
Since I am thinking of time-normalized movement cycles, I use a periodic version of the Matérn covariance. More specifically, I embed the normalized domain on a circle and evaluate the covariance using the chord distance
$$d(s,t)=\frac{|\sin(\pi(s-t))|}{\pi}.$$
This gives a valid covariance on the circle and ensures that the random curves have matching endpoints. Otherwise, an ordinary Matérn process on an interval would introduce an endpoint mismatch even in the smooth scenario, making it difficult to separate roughness from the periodicity assumption of the Fourier basis.
I use two independent unit-variance processes, $Z_s$ and $Z_r$. The smooth component has $\nu=5/2$ and $\ell=0.16$, while the rougher component has $\nu=3/2$ and $\ell=0.045$ (length scales expressed as fractions of a movement cycle). Both are smoother than a Matérn process with $\nu=1/2$, which would generate nondifferentiable, rather jagged trajectories. The simulated curve is
$$Y(t)=\mu(t)+0.6\{\sqrt{1-w(t)^2}Z_s(t)+w(t)Z_r(t)\}.$$
The weight $w(t)$ determines the relative contribution of the rougher component. Since the two processes are independent, the theoretical pointwise SD is 0.6 everywhere. The mean is a smooth periodic waveform with a dominant excursion and a smaller secondary feature, meant to resemble the broad shape of a movement trajectory rather than a specific joint angle or force signal.
#### Investigated scenarios
Three scenarios vary stochastic roughness. A fourth tests what happens when the mean is not periodic:
(1) smooth curves ($w=0$)
(2) globally rough curves ($w=1$)
(3) locally rough curves ($w=1$ between 0.55 and 0.80 of the cycle, with smooth transitions on either side).
(4) smooth curves with a nonperiodic mean trend added to isolate the endpoint constraint.
```{r}
#| label: data-generator
#| code-fold: true
#| code-summary: "Code for the data-generating functions"
roughness_weight <- function(t, scenario) {
if (scenario == "rough_global") return(rep(1, length(t)))
if (scenario == "rough_local") {
# Smooth transitions into and out of the rough part of the cycle
up <- pmax(0, pmin(1, (t - 0.40) / 0.15))
down <- pmax(0, pmin(1, (0.95 - t) / 0.15))
return(sin(pi / 2 * sin(pi * up / 2)^2 * sin(pi * down / 2)^2))
}
if (scenario %in% c("smooth", "nonperiodic")) return(rep(0, length(t)))
stop("Unknown scenario: ", scenario)
}
population_mean <- function(t, scenario) {
mean_curve <- sin(2 * pi * t) + 0.35 * sin(4 * pi * t - 0.7) +
0.15 * cos(6 * pi * t)
if (scenario == "nonperiodic") mean_curve <- mean_curve + 0.8 * (t - 0.5)
mean_curve
}
# Matérn correlation on a circle (only the two nu values used here)
matern_cor <- function(t, nu, ell) {
d <- abs(sin(pi * outer(t, t, "-"))) / pi
z <- sqrt(2 * nu) * d / ell
if (nu == 1.5) return((1 + z) * exp(-z))
if (nu == 2.5) return((1 + z + z^2 / 3) * exp(-z))
stop("Unknown nu")
}
# Exclude the duplicated endpoint before taking the Cholesky factor.
# The factors only need to be computed once for the simulation grid.
make_factors <- function(t) {
u <- head(t, -1)
list(smooth = chol(matern_cor(u, nu = 2.5, ell = 0.16)),
rough = chol(matern_cor(u, nu = 1.5, ell = 0.045)))
}
L <- make_factors(t_grid)
draw_gp <- function(R, n) {
Z <- t(R) %*% matrix(rnorm(nrow(R) * n), ncol = n)
rbind(Z, Z[1, , drop = FALSE])
}
random_component <- function(t, w, n) {
R <- if (identical(t, t_grid)) L else make_factors(t)
# Mix independent processes, keeping the marginal variance constant
a <- sqrt(pmax(0, 1 - w^2))
if (all(w == 0)) return(draw_gp(R$smooth, n))
if (all(w == 1)) return(draw_gp(R$rough, n))
a * draw_gp(R$smooth, n) + w * draw_gp(R$rough, n)
}
simulate_sample <- function(scenario, t, n = 60L) {
w <- roughness_weight(t, scenario)
mu <- population_mean(t, scenario)
sigma <- 0.60
Y <- sweep(sigma * random_component(t, w, n), 1, mu, "+")
future <- mu + as.vector(sigma * random_component(t, w, 1L))
list(Y = Y, mu = mu, future = future)
}
fourier_Q <- function(T, k) {
stopifnot(k >= 0, k <= floor((T - 2) / 2))
u <- (seq_len(T) - 1) / (T - 1) # same phase convention as funbootband
D <- matrix(1, nrow = T, ncol = 2L * k + 1L)
if (k > 0) {
for (j in seq_len(k)) {
D[, 2L * j] <- cos(2 * pi * j * u)
D[, 2L * j + 1L] <- sin(2 * pi * j * u)
}
}
qr.Q(qr(D))
}
project_on_Q <- function(X, Q) {
X <- as.matrix(X)
Q %*% crossprod(Q, X) # least-squares fitted curves
}
```
```{r}
#| label: scenario-data
#| code-fold: true
#| code-summary: "Code to create curves in each of the four scenarios"
scenarios <- c("smooth", "rough_global", "rough_local", "nonperiodic")
scenario_labels <- c(smooth = "Smooth",
rough_global = "Globally rough",
rough_local = "Locally rough",
nonperiodic = "Nonperiodic mean")
idx_smooth <- which(t_grid >= 0.05 & t_grid <= 0.30)
idx_rough <- which(t_grid >= 0.55 & t_grid <= 0.80)
Q_by_k <- setNames(lapply(k_values, function(k) fourier_Q(T_grid, k)),
as.character(k_values))
set.seed(101)
recon_data <- lapply(scenarios, function(scenario) {
simulate_sample(scenario, t_grid, n = 80L)
})
names(recon_data) <- scenarios
```
```{r}
#| label: fig-original-curves
#| code-summary: "Code to draw the curves in each scenario"
#| fig-cap: "Examples of simulated functional observations under four scenarios."
#| fig-width: 10
#| fig-height: 6
n_show <- 10L
plot_data <- do.call(rbind, lapply(scenarios, function(scenario) {
X <- recon_data[[scenario]]$Y[, 1:n_show, drop = FALSE]
tmp <- melt(X, varnames = c("time", "curve"), value.name = "value")
tmp$t <- t_grid[tmp$time]
tmp$scenario <- scenario_labels[[scenario]]
tmp
}))
plot_data$scenario <- factor(plot_data$scenario, levels = scenario_labels)
p_original <- ggplot(plot_data, aes(x = t, y = value, group = curve)) +
geom_line(alpha = 0.6, linewidth = 0.45) +
facet_wrap(~ scenario, ncol = 2) +
labs(
x = "Normalized domain",
y = "Y(t)",
title = "Simulated functional observations"
) +
theme_minimal(base_size = 12)
p_original
```
@fig-original-curves displays example curves in each of the four simulated scenarios. The applied parameters are illustrative, i.e., they were primarily chosen to create realistic looking curves. Parameters were not estimated from any actual data. Roughness here means faster local fluctuations, not simply a larger pointwise standard deviation. Unlike the finite sinusoidal generator, the Matérn processes are not restricted to a fixed number of Fourier frequencies.
Both Matérn parameters vary together, so this is a comparison of roughness scenarios rather than an isolated test of either parameter.
#### Sanity check
As a quick sanity check, the pointwise SD should stay roughly constant, while the RMS of standardized increments divided by the grid spacing should increase where fluctuations become faster. This is a grid-dependent roughness proxy, not the fairness criterion of Liebl and Reimherr.
```{r}
#| label: fig-roughness-check
#| fig-cap: "A controlled change in roughness for different scenarios."
#| fig-width: 8
#| fig-height: 5.3
set.seed(102)
scenario_names <- c("smooth", "rough_global", "rough_local")
roughness_samples <- setNames(
lapply(scenario_names, function(scenario) {
simulate_sample(scenario, t_grid, n = 120L)$Y
}),
scenario_names
)
roughness_diagnostic <- do.call(rbind, lapply(
c("smooth", "rough_global", "rough_local"), function(scenario) {
X <- roughness_samples[[scenario]]
centered <- sweep(X, 1, rowMeans(X), "-")
sd_t <- apply(centered, 1, sd)
standardized <- sweep(centered, 1, sd_t, "/")
differences <- sweep(
standardized[-1, , drop = FALSE] -
standardized[-nrow(standardized), , drop = FALSE],
1, diff(t_grid), "/"
)
data.frame(
t = (head(t_grid, -1) + tail(t_grid, -1)) / 2,
scenario = scenario,
sd = (head(sd_t, -1) + tail(sd_t, -1)) / 2,
roughness = sqrt(rowMeans(differences^2))
)
}
))
roughness_diagnostic <- melt(roughness_diagnostic,
id.vars = c("t", "scenario"),
variable.name = "measure")
roughness_diagnostic$scenario <- scenario_labels[roughness_diagnostic$scenario]
roughness_diagnostic$measure <- factor(roughness_diagnostic$measure,
levels = c("sd", "roughness"),
labels = c("Pointwise SD (estimated)", "Standardized increment RMS / dt"))
p_diagnostic <- ggplot(roughness_diagnostic,
aes(t, value, color = scenario)) +
geom_line(linewidth = 0.65) +
facet_wrap(~ measure, ncol = 1, scales = "free_y") +
labs(x = "Normalized domain", y = NULL, color = "Scenario") +
theme_minimal(base_size = 11)
print(p_diagnostic)
```
### How much is lost in the Fourier reconstruction?
`funbootband` uses `k.coef` to select the number of Fourier harmonics. I reconstruct the same simulated curves at several values of this parameter and calculate their root mean squared reconstruction error (RMSE). Because these simulated curves have no added measurement noise, the original observations themselves are the relevant reference for this particular experiment.
I also calculate the RMSE separately in a smooth region and in the region designed to be locally rough. These are approximation diagnostics, not measures of statistical coverage.
```{r}
#| label: reconstruction-analysis
#| code-fold: true
#| code-summary: "Code for the Fourier reconstruction and error calculations"
rmse <- function(A, B, idx) {
sqrt(mean((A[idx, , drop = FALSE] - B[idx, , drop = FALSE])^2))
}
recon_results <- do.call(rbind, lapply(scenarios, function(scenario) {
X <- recon_data[[scenario]]$Y
do.call(rbind, lapply(k_values, function(k) {
fitted <- project_on_Q(X, Q_by_k[[as.character(k)]])
data.frame(
scenario = scenario, k = k,
Whole_domain = rmse(X, fitted, seq_len(T_grid)),
Smooth_region = rmse(X, fitted, idx_smooth),
Rough_region = rmse(X, fitted, idx_rough)
)
}))
}))
recon_long <- melt(recon_results, id.vars = c("scenario", "k"),
measure.vars = c("Whole_domain", "Smooth_region", "Rough_region"),
variable.name = "region", value.name = "RMSE")
recon_long$scenario <- factor(recon_long$scenario, levels = scenarios,
labels = scenario_labels)
```
```{r}
#| label: fig-reconstruction-plot
#| fig-cap: "Fourier reconstruction error as a function of the number of harmonics. Separate regional errors can reveal problems hidden by a single global RMSE."
#| fig-width: 9
#| fig-height: 6
p_recon <- ggplot(recon_long, aes(k, RMSE, linetype = region, group = region)) +
geom_line(linewidth = 0.7) +
geom_point(size = 1.7) +
facet_wrap(~ scenario, ncol = 2) +
scale_x_continuous(breaks = k_values) +
labs(x = "Fourier harmonics (k.coef)", y = "Reconstruction RMSE",
linetype = "Area", title = "How much does the Fourier approximation miss?") +
theme_minimal(base_size = 12)
print(p_recon)
```
But how large are these errors actually? Since the theoretical pointwise SD of the simulated curves is 0.6 in all four scenarios, I use this as a reference. Dividing the RMSE by 0.6 gives an error relative to the magnitude of the between-curve variability. An RMSE of 0.06, for instance, corresponds to 10% of the pointwise SD. This is not the percentage of variance lost, nor is there a universal threshold for an acceptable reconstruction error.
```{r}
#| label: tbl-relative-reconstruction-error
#| echo: false
#| tbl-cap: "Whole-domain reconstruction RMSE as a percentage of the theoretical pointwise SD."
rel_error <- recon_results[, c("scenario", "k", "Whole_domain")]
rel_error$relative_rmse <- 100 * rel_error$Whole_domain / 0.6
rel_tab <- dcast(rel_error, scenario ~ k, value.var = "relative_rmse")
rel_tab <- rel_tab[match(scenarios, rel_tab$scenario), ]
rel_tab$scenario <- unname(scenario_labels[rel_tab$scenario])
names(rel_tab) <- c("Scenario", paste0("k = ", sort(unique(rel_error$k))))
kable(rel_tab, digits = 2)
```
With four harmonics, the whole-domain reconstruction error is `r round(rel_error$relative_rmse[rel_error$scenario == "smooth" & rel_error$k == 4], 1)`% of the pointwise SD for the smooth curves, compared with `r round(rel_error$relative_rmse[rel_error$scenario == "rough_global" & rel_error$k == 4], 1)`% for the globally rough curves. With 40 harmonics, the corresponding values are `r round(rel_error$relative_rmse[rel_error$scenario == "smooth" & rel_error$k == 40], 2)`% and `r round(rel_error$relative_rmse[rel_error$scenario == "rough_global" & rel_error$k == 40], 2)`%. In the locally rough scenario, the regional RMSE at $k=40$ is `r round(100 * recon_results$Rough_region[recon_results$scenario == "rough_local" & recon_results$k == 40] / 0.6, 2)`% of the pointwise SD in the rough region.
Unlike data generated from a finite Fourier series, there is no particular value of $k$ at which the underlying Matérn process becomes exactly representable. Even a very small error at the observed grid points does not guarantee that the continuous curve has been recovered between those points.
To get a better feel for what these numbers mean, I plotted one of the original curves from each scenario alongside its Fourier reconstruction. The same curve is used for all three values of `k.coef` within each scenario (the first simulated curve, rather than one selected based on its reconstruction error).
```{r}
#| label: fig-reconstruction-examples
#| fig-cap: "Original and Fourier-reconstructed curves for three numbers of harmonics. All panels use the same axis scales. The first simulated curve in each scenario is shown."
#| fig-width: 10
#| fig-height: 8
k_show <- c(4, 10, 40)
example_data <- list()
i <- 1
for (scenario in scenarios) {
X <- recon_data[[scenario]]$Y[, 1, drop = FALSE]
for (k in k_show) {
fitted <- project_on_Q(X, Q_by_k[[as.character(k)]])
tmp <- data.frame(t = t_grid, Original = X[, 1],
Reconstructed = fitted[, 1])
tmp <- melt(tmp, id.vars = "t", variable.name = "curve",
value.name = "Y")
tmp$scenario <- scenario_labels[scenario]
tmp$k <- paste("k =", k)
example_data[[i]] <- tmp
i <- i + 1
}
}
example_data <- do.call(rbind, example_data)
example_data$scenario <- factor(example_data$scenario, levels = scenario_labels)
example_data$k <- factor(example_data$k, levels = paste("k =", k_show))
p_recon_examples <- ggplot(example_data, aes(t, Y, color = curve,
linetype = curve)) +
geom_line(linewidth = 0.65) +
facet_grid(scenario ~ k) +
scale_color_manual(values = c("Original" = "grey35", "Reconstructed" = "#0072B2")) +
scale_linetype_manual(values = c("Original" = "solid", "Reconstructed" = "dashed")) +
labs(x = "Normalized domain", y = "Y(t)", color = NULL, linetype = NULL) +
theme_minimal(base_size = 11) +
theme(legend.position = "bottom")
p_recon_examples
```
Overall, I find the reconstruction quality quite encouraging for the periodic curves. With 40 harmonics, even the rougher curves are approximated very well relative to the between-curve variability. A small global RMSE can, however, hide errors in a short region of the domain.
The nonperiodic mean is a different problem: the Fourier basis forces the first and last fitted values to agree. No number of harmonics can remove that constraint. Both local errors and endpoint errors matter for simultaneous bands, where missing the target at just one grid point counts as noncoverage.
### A good reconstruction is not the same as good coverage
Alright, we have established that the Fourier reconstruction works reasonably well. But does the reconstruction error actually matter for inference? When answering this, I look at two targets: (1) the original mean or future curve, and (2) its Fourier projection.
This distinction is important because (somewhat counterintuitively, at least to me) a band may fully cover a reconstructed curve but fail to cover the original curve, for instance, if a local peak is lost during Fourier reconstruction. Comparing the coverage of both targets using the same band helps us assess the impact of the approximation error. Coverage of the projected target also tells us how well the band is calibrated for that target.
I simulate `r M` independent samples of `r n` curves in each of the four scenarios, construct nominal 95% confidence and prediction bands with `r B` bootstrap resamples, and compare `k.coef = 4` and `40`. Coverage means that the entire target lies inside the band at all `r T_grid` grid points. Near 95% coverage, Monte Carlo standard errors are about `r round(100 * sqrt(0.95 * 0.05 / M), 1)` percentage points.
```{r}
#| label: coverage-functions
#| code-fold: true
#| code-summary: "Show the coverage experiment"
within_band <- function(fit, target) {
all(target >= fit$lower & target <= fit$upper)
}
run_coverage <- function(scenarios, M, B, n, alpha, k_coverage) {
records <- vector("list", length(scenarios) * M * length(k_coverage) * 2L)
count <- 0L
for (scenario in scenarios) {
for (r in seq_len(M)) {
sample <- simulate_sample(scenario, t_grid, n = n)
for (k in k_coverage) {
q <- Q_by_k[[as.character(k)]]
projected_mean <- as.vector(project_on_Q(sample$mu, q))
projected_future <- as.vector(project_on_Q(sample$future, q))
for (type in c("confidence", "prediction")) {
fit <- funbootband::band(sample$Y, type = type, alpha = alpha,
iid = TRUE, B = B, k.coef = k)
# Check that our projection matches the one used by band().
if (r == 1L) {
stopifnot(isTRUE(all.equal(as.numeric(fit$mean),
as.numeric(project_on_Q(rowMeans(sample$Y), q)),
tolerance = 1e-8)))
}
stopifnot(length(fit$lower) == T_grid, length(fit$upper) == T_grid,
all(is.finite(c(fit$lower, fit$upper))),
all(fit$lower <= fit$upper))
target_projected <- if (type == "confidence") projected_mean else projected_future
target_raw <- if (type == "confidence") sample$mu else sample$future
covered_projected <- within_band(fit, target_projected)
covered_original <- within_band(fit, target_raw)
count <- count + 1L
records[[count]] <- data.frame(
scenario = scenario, repetition = r, k = k, type = type,
cover_projected = covered_projected,
cover_raw = covered_original,
difference = as.integer(covered_original) - as.integer(covered_projected),
mean_width = mean(fit$upper - fit$lower)
)
}
}
}
message("Finished: ", scenario)
}
do.call(rbind, records)
}
```
```{r}
#| label: coverage-run
#| code-fold: true
#| code-summary: "Run the Monte Carlo simulation"
set.seed(20261125)
mc_results <- run_coverage(scenarios, M, B, n, alpha, k_coverage)
coverage_summary <- aggregate(
cbind(cover_projected, cover_raw, mean_width, difference) ~ scenario + k + type,
data = mc_results, FUN = mean)
names(coverage_summary)[4:7] <- c("coverage_projected", "coverage_original",
"average_width", "difference")
coverage_summary$MCSE_projected <- with(coverage_summary,
sqrt(coverage_projected * (1 - coverage_projected) / M))
coverage_summary$MCSE_original <- with(coverage_summary,
sqrt(coverage_original * (1 - coverage_original) / M))
paired_se <- aggregate(difference ~ scenario + k + type, data = mc_results,
FUN = function(x) sd(x) / sqrt(length(x)))
names(paired_se)[4] <- "MCSE_difference"
coverage_summary <- merge(coverage_summary, paired_se,
by = c("scenario", "k", "type"))
# Helpers for the inline results below
coverage_pct <- function(scenario_name, harmonics, band_type, target = "original") {
x <- subset(coverage_summary, scenario == scenario_name &
k == harmonics & type == band_type)
stopifnot(nrow(x) == 1L)
sprintf("%.1f%%", 100 * x[[paste0("coverage_", target)]])
}
# Paired change in coverage from k = 4 to k = 40
change_text <- function(scenario_name, band_type, target = "cover_raw") {
x <- subset(mc_results, scenario == scenario_name & type == band_type)
a <- x[x$k == 4, c("repetition", target)]
b <- x[x$k == 40, c("repetition", target)]
ab <- merge(a, b, by = "repetition", suffixes = c("_4", "_40"))
stopifnot(nrow(ab) == M)
d <- as.numeric(ab[[paste0(target, "_40")]]) -
as.numeric(ab[[paste0(target, "_4")]])
sprintf("%+.1f pp (MCSE %.1f pp)", 100 * mean(d),
100 * sd(d) / sqrt(length(d)))
}
```
```{r}
#| label: fig-coverage-plot
#| fig-cap: "Estimated simultaneous coverage at the observed grid points. The dashed line is nominal 95% coverage; error bars show 95% Monte Carlo intervals (Wilson)."
#| fig-width: 9
#| fig-height: 6
coverage_plot_data <- melt(coverage_summary,
id.vars = c("scenario", "k", "type"),
measure.vars = c("coverage_projected", "coverage_original"),
variable.name = "target", value.name = "coverage")
coverage_plot_data$scenario <- factor(coverage_plot_data$scenario,
levels = scenarios, labels = scenario_labels)
coverage_plot_data$target <- factor(coverage_plot_data$target,
levels = c("coverage_projected", "coverage_original"),
labels = c("Fourier-projected", "Original curve"))
# Wilson intervals for the Monte Carlo coverage estimates
p <- coverage_plot_data$coverage
z <- qnorm(0.975)
center <- (p + z^2 / (2 * M)) / (1 + z^2 / M)
half_width <- z * sqrt(p * (1 - p) / M + z^2 / (4 * M^2)) / (1 + z^2 / M)
coverage_plot_data$lo <- pmax(0, center - half_width)
coverage_plot_data$hi <- pmin(1, center + half_width)
p_coverage <- ggplot(coverage_plot_data,
aes(k, coverage, color = target, linetype = target,
shape = target, group = target)) +
geom_hline(yintercept = 1 - alpha, linetype = 2) +
geom_line(linewidth = 0.75) +
geom_point(size = 2) +
geom_errorbar(aes(ymin = lo, ymax = hi),
width = 1.5, alpha = 0.6) +
facet_grid(type ~ scenario) +
scale_x_continuous(breaks = k_coverage) +
coord_cartesian(ylim = c(0, 1)) +
labs(x = "Fourier harmonics (k.coef)",
y = "Estimated simultaneous coverage", color = "Target",
linetype = "Target", shape = "Target") +
theme_minimal(base_size = 11)
print(p_coverage)
```
The population mean in the three periodic scenarios is represented exactly even at $k=4$. Thus, confidence-band coverage of the original and projected mean is the same (up to numerical precision). Individual curves are a different story.
For the globally rough curves, increasing $k$ from 4 to 40 changes prediction-band coverage of the original curves from `r coverage_pct("rough_global", 4, "prediction")` to `r coverage_pct("rough_global", 40, "prediction")`. For the locally rough curves, it changes from `r coverage_pct("rough_local", 4, "prediction")` to `r coverage_pct("rough_local", 40, "prediction")`. At $k=40$, the corresponding projected-target coverages are `r coverage_pct("rough_global", 40, "prediction", "projected")` and `r coverage_pct("rough_local", 40, "prediction", "projected")`. Why does this happen? With too few harmonics, rapid fluctuations are lost during reconstruction. The prediction bands are constructed from the reconstructed curves, so they do not account for the variation that has been removed. They can therefore be too narrow for the original curves, even if they work well for the reconstructed ones. And since coverage is simultaneous, just one missed peak is enough for the entire curve to count as uncovered.
**Does a larger $k$ always help?** Not necessarily. For example, confidence-band coverage in the smooth scenario changes from `r coverage_pct("smooth", 4, "confidence")` to `r coverage_pct("smooth", 40, "confidence")` (a paired change of `r change_text("smooth", "confidence")`). The mean is already represented exactly, so there is no approximation bias to remove. Additional harmonics instead retain more sampling fluctuations in the estimated mean, changing its variability and the calibration problem for the band. This does not necessarily reduce coverage if the band is properly calibrated. Small observed changes may simply be Monte Carlo noise. Prediction-band coverage for the smooth curves at $k=40$ is `r coverage_pct("smooth", 40, "prediction")`, despite an almost perfect reconstruction.
The nonperiodic mean is the clearest counterexample to simply adding harmonics: at $k=40$, confidence-band coverage is `r coverage_pct("nonperiodic", 40, "confidence", "projected")` for the projected mean but `r coverage_pct("nonperiodic", 40, "confidence")` for the original mean. The endpoint constraint remains.
```{r}
#| label: coverage-table
#| echo: false
#| results: asis
tab <- coverage_summary[, c("scenario", "k", "type", "coverage_projected",
"coverage_original", "difference", "MCSE_difference",
"average_width")]
tab$scenario <- factor(tab$scenario, levels = scenarios, labels = scenario_labels)
tab <- tab[order(tab$type, tab$scenario, tab$k), ]
tab[, 4:7] <- 100 * tab[, 4:7]
names(tab) <- c("Scenario", "k", "Band", "Projected (%)", "Original (%)",
"Gap (pp)", "MCSE of gap (pp)", "Average width")
cat("<details><summary>Exact coverage estimates and average band widths</summary>\n\n")
print(kable(tab, digits = 2, row.names = FALSE))
cat("\n\n</details>\n")
```
### What I take away
**Reconstruction:** For the simulated periodic curves, even moderate roughness is manageable with enough harmonics. Nonperiodic endpoints are a separate problem.
**Coverage:** Too few harmonics can substantially reduce prediction-band coverage for rough curves, but good reconstruction alone does not guarantee nominal coverage. For the future development of `funbootband`, these findings tell me that it might be a good idea to further explore data-driven choices of `k.coef`, whether reconstruction residuals can be accounted for in prediction bands, and maybe alternative bases for nonperiodic data.
Whether roughness-aware calibration could improve the bands is yet another question. Maybe something for Part II.
```{r}
#| label: save-results
#| include: false
if (identical(Sys.getenv("FBB_SAVE_RESULTS", unset = "0"), "1")) {
dir.create("roughness-results", showWarnings = FALSE)
write.csv(recon_results, "roughness-results/reconstruction_errors.csv",
row.names = FALSE)
write.csv(mc_results, "roughness-results/monte_carlo_runs.csv",
row.names = FALSE)
write.csv(coverage_summary, "roughness-results/coverage_summary.csv",
row.names = FALSE)
saveRDS(
list(config = list(M = M, B = B, n = n, alpha = alpha,
T_grid = T_grid, k_values = k_values,
k_coverage = k_coverage,
matern_nu = c(2.5, 1.5),
matern_ell = c(0.16, 0.045)),
reconstruction = recon_results, outcomes = mc_results,
summary = coverage_summary, session = sessionInfo()),
"roughness-results/study_results.rds"
)
ggsave("roughness-results/original_curves.png", p_original,
width = 10, height = 6, dpi = 180)
ggsave("roughness-results/roughness_diagnostic.png", p_diagnostic,
width = 8, height = 5.3, dpi = 180)
ggsave("roughness-results/reconstruction_rmse.png", p_recon,
width = 9, height = 6, dpi = 180)
ggsave("roughness-results/reconstruction_examples.png", p_recon_examples,
width = 10, height = 8, dpi = 180)
ggsave("roughness-results/coverage.png", p_coverage,
width = 9, height = 6, dpi = 180)
}
```
```{r}
#| label: reproducibility
#| echo: false
#| results: asis
cat("<details><summary>Reproducibility details</summary>\n\n")
cat("```\n")
cat("funbootband version: ", as.character(packageVersion("funbootband")), "\n", sep = "")
cat("R version: ", R.version.string, "\n", sep = "")
cat("M = ", M, "; B = ", B, "; n = ", n, "\n", sep = "")
cat("```\n\n</details>\n")
```