## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----setup--------------------------------------------------------------------
library(convergenceDFM)

## ----conjugate----------------------------------------------------------------
set.seed(1)
Tn <- 20; K <- 4
cpi <- 100 * cumprod(1 + rnorm(Tn, 0.02, 0.01)) + 50   # a positive aggregate index
W   <- matrix(runif(Tn * K), Tn, K); W <- W / rowSums(W)

fit <- BayesianDisaggregation::disaggregate_conjugate(cpi, W)
dim(fit$phi_summary$median)     # [T x K] smoothed sectoral levels

## ----reweight, eval=FALSE-----------------------------------------------------
# # `path_cpi` and `path_weights` are Excel files; `X_matrix` is the production-side
# # panel. The function reads the CPI, aligns it to the weight years, and for each
# # alternative prior calls disaggregate_conjugate() internally.
# rw <- test_reweighting_robustness(path_cpi, path_weights, X_matrix,
#                                   max_comp = 3, seed = 11)
# rw$cv_coupling   # coefficient of variation of the coupling across schemes
# rw$robust        # TRUE if CV < 0.30

## ----lco-data-----------------------------------------------------------------
set.seed(123)
Tn <- 30; K <- 6
f   <- cumsum(rnorm(Tn))
Phi <- sapply(1:K, function(k) 100 + 5 * f + rnorm(Tn, 0, 1))   # production side
phi <- sapply(1:K, function(k) Phi[, k] + rnorm(Tn, 0, 0.5))    # market side
colnames(Phi) <- colnames(phi) <- paste0("sector_", 1:K)

chains <- list(chainA = c("sector_1", "sector_2"),
               chainB = c("sector_3", "sector_4"),
               chainC = c("sector_5", "sector_6"))
lco <- test_leave_cluster_out(Phi, phi, cluster_map = chains, seed = 7,
                              verbose = FALSE)
lco$baseline
lco$cluster_estimates     # coupling with each chain removed
lco$robust                # TRUE if no chain changes the coupling by > 50%

## ----fallback-----------------------------------------------------------------
build_cluster_map(phi, n_clusters = 3, method = "correlation")

